PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/navigator/File.cc

https://github.com/zhongxingzhi/sourceweb
C++ | 91 lines | 77 code | 10 blank | 4 comment | 19 complexity | c7e43ac335a92b00794a0b24143c0fcc MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #include "File.h"
  2. #include <QString>
  3. #include <QFile>
  4. #include <QFileInfo>
  5. #include <cassert>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <string>
  9. #include <utility>
  10. namespace Nav {
  11. File::File(Folder *parent, const QString &path) :
  12. m_parent(parent), m_path(path), m_loaded(false)
  13. {
  14. }
  15. QString File::path()
  16. {
  17. return m_path;
  18. }
  19. QString File::title()
  20. {
  21. QFileInfo fi(m_path);
  22. return fi.fileName();
  23. }
  24. // 0-based line number. The offset must be less than the content size. The
  25. // result will be <= the line count.
  26. int File::lineForOffset(int offset)
  27. {
  28. ensureLoaded();
  29. assert(offset < static_cast<int>(m_content.size()));
  30. int line1 = 0;
  31. int line2 = lineCount() - 1;
  32. while (line1 < line2) {
  33. int midLine = line1 + (line2 - line1) / 2 + 1;
  34. assert(midLine > line1 && midLine <= line2);
  35. if (offset < m_lines[midLine].first)
  36. line2 = midLine - 1;
  37. else
  38. line1 = midLine;
  39. }
  40. return line1;
  41. }
  42. void File::loadFile()
  43. {
  44. QFile qfile(m_path);
  45. if (!qfile.open(QFile::ReadOnly)) {
  46. m_content = "Error: cannot open " + m_path.toStdString();
  47. } else {
  48. // Read the file and canonicalize CRLF and CR line endings to LF.
  49. char *buf = new char[qfile.size() + 1];
  50. qfile.read(buf, qfile.size());
  51. buf[qfile.size()] = '\0';
  52. char *d = buf, *s = buf;
  53. while (*s != '\0') {
  54. if (*s == '\r') {
  55. *(d++) = '\n';
  56. ++s;
  57. if (*s == '\n')
  58. ++s;
  59. } else {
  60. *(d++) = *(s++);
  61. }
  62. }
  63. m_content = std::string(buf, d - buf);
  64. delete [] buf;
  65. }
  66. // Identify where each line begins.
  67. const char *data = m_content.c_str();
  68. int lineStart = 0;
  69. for (int i = 0; ; i++) {
  70. if (data[i] == '\n') {
  71. m_lines.push_back(std::make_pair(lineStart, i - lineStart));
  72. lineStart = i + 1;
  73. } else if (data[i] == '\0') {
  74. if (i > lineStart)
  75. m_lines.push_back(std::make_pair(lineStart, i - lineStart));
  76. break;
  77. }
  78. }
  79. m_loaded = true;
  80. }
  81. } // namespace Nav