Project.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "Project.h"
  2. #include <LibCore/CFile.h>
  3. class ProjectModel final : public GModel {
  4. public:
  5. explicit ProjectModel(Project& project)
  6. : m_project(project)
  7. {
  8. }
  9. virtual int row_count(const GModelIndex& = GModelIndex()) const override { return m_project.m_files.size(); }
  10. virtual int column_count(const GModelIndex& = GModelIndex()) const override { return 1; }
  11. virtual GVariant data(const GModelIndex& index, Role role = Role::Display) const override
  12. {
  13. int row = index.row();
  14. if (role == Role::Display) {
  15. return m_project.m_files.at(row).name();
  16. }
  17. if (role == Role::Font) {
  18. extern String g_currently_open_file;
  19. if (m_project.m_files.at(row).name() == g_currently_open_file)
  20. return Font::default_bold_font();
  21. return {};
  22. }
  23. return {};
  24. }
  25. virtual void update() override
  26. {
  27. did_update();
  28. }
  29. private:
  30. Project& m_project;
  31. };
  32. Project::Project(const String& path, Vector<String>&& filenames)
  33. : m_path(path)
  34. {
  35. for (auto& filename : filenames) {
  36. m_files.append(TextDocument::construct_with_name(filename));
  37. }
  38. m_model = adopt(*new ProjectModel(*this));
  39. }
  40. OwnPtr<Project> Project::load_from_file(const String& path)
  41. {
  42. auto file = CFile::construct(path);
  43. if (!file->open(CFile::ReadOnly))
  44. return nullptr;
  45. Vector<String> files;
  46. for (;;) {
  47. auto line = file->read_line(1024);
  48. if (line.is_null())
  49. break;
  50. files.append(String::copy(line, Chomp));
  51. }
  52. return OwnPtr(new Project(path, move(files)));
  53. }
  54. bool Project::add_file(const String& filename)
  55. {
  56. auto project_file = CFile::construct(m_path);
  57. if (!project_file->open(CFile::WriteOnly))
  58. return false;
  59. for (auto& file : m_files) {
  60. // FIXME: Check for error here. CIODevice::printf() needs some work on error reporting.
  61. project_file->printf("%s\n", file.name().characters());
  62. }
  63. project_file->printf("%s\n", filename.characters());
  64. if (!project_file->close())
  65. return false;
  66. m_files.append(TextDocument::construct_with_name(filename));
  67. m_model->update();
  68. return true;
  69. }
  70. TextDocument* Project::get_file(const String& filename)
  71. {
  72. for (auto& file : m_files) {
  73. if (file.name() == filename)
  74. return &file;
  75. }
  76. return nullptr;
  77. }