FileSystemModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/FileSystemPath.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibCore/DirIterator.h>
  29. #include <LibGUI/FileSystemModel.h>
  30. #include <LibGUI/Painter.h>
  31. #include <LibGfx/Bitmap.h>
  32. #include <LibThread/BackgroundAction.h>
  33. #include <dirent.h>
  34. #include <grp.h>
  35. #include <pwd.h>
  36. #include <stdio.h>
  37. #include <sys/stat.h>
  38. #include <unistd.h>
  39. namespace GUI {
  40. ModelIndex FileSystemModel::Node::index(const FileSystemModel& model, int column) const
  41. {
  42. if (!parent)
  43. return {};
  44. for (size_t row = 0; row < parent->children.size(); ++row) {
  45. if (&parent->children[row] == this)
  46. return model.create_index(row, column, const_cast<Node*>(this));
  47. }
  48. ASSERT_NOT_REACHED();
  49. }
  50. bool FileSystemModel::Node::fetch_data(const String& full_path, bool is_root)
  51. {
  52. struct stat st;
  53. int rc;
  54. if (is_root)
  55. rc = stat(full_path.characters(), &st);
  56. else
  57. rc = lstat(full_path.characters(), &st);
  58. if (rc < 0) {
  59. perror("stat/lstat");
  60. return false;
  61. }
  62. size = st.st_size;
  63. mode = st.st_mode;
  64. uid = st.st_uid;
  65. gid = st.st_gid;
  66. inode = st.st_ino;
  67. mtime = st.st_mtime;
  68. if (S_ISLNK(mode)) {
  69. char buffer[PATH_MAX];
  70. int length = readlink(full_path.characters(), buffer, sizeof(buffer));
  71. if (length < 0) {
  72. perror("readlink");
  73. } else {
  74. ASSERT(length > 0);
  75. symlink_target = String(buffer, length - 1);
  76. }
  77. }
  78. return true;
  79. }
  80. void FileSystemModel::Node::traverse_if_needed(const FileSystemModel& model)
  81. {
  82. if (!is_directory() || has_traversed)
  83. return;
  84. has_traversed = true;
  85. total_size = 0;
  86. auto full_path = this->full_path(model);
  87. Core::DirIterator di(full_path, Core::DirIterator::SkipDots);
  88. if (di.has_error()) {
  89. fprintf(stderr, "DirIterator: %s\n", di.error_string());
  90. return;
  91. }
  92. while (di.has_next()) {
  93. String name = di.next_path();
  94. String child_path = String::format("%s/%s", full_path.characters(), name.characters());
  95. NonnullOwnPtr<Node> child = make<Node>();
  96. bool ok = child->fetch_data(child_path, false);
  97. if (!ok)
  98. continue;
  99. if (model.m_mode == DirectoriesOnly && !S_ISDIR(child->mode))
  100. continue;
  101. child->name = name;
  102. child->parent = this;
  103. total_size += child->size;
  104. children.append(move(child));
  105. }
  106. if (m_watch_fd >= 0)
  107. return;
  108. m_watch_fd = watch_file(full_path.characters(), full_path.length());
  109. if (m_watch_fd < 0) {
  110. perror("watch_file");
  111. return;
  112. }
  113. fcntl(m_watch_fd, F_SETFD, FD_CLOEXEC);
  114. dbg() << "Watching " << full_path << " for changes, m_watch_fd = " << m_watch_fd;
  115. m_notifier = Core::Notifier::construct(m_watch_fd, Core::Notifier::Event::Read);
  116. m_notifier->on_ready_to_read = [this, &model] {
  117. char buffer[32];
  118. int rc = read(m_notifier->fd(), buffer, sizeof(buffer));
  119. ASSERT(rc >= 0);
  120. has_traversed = false;
  121. mode = 0;
  122. children.clear();
  123. reify_if_needed(model);
  124. const_cast<FileSystemModel&>(model).did_update();
  125. };
  126. }
  127. void FileSystemModel::Node::reify_if_needed(const FileSystemModel& model)
  128. {
  129. traverse_if_needed(model);
  130. if (mode != 0)
  131. return;
  132. fetch_data(full_path(model), parent == nullptr);
  133. }
  134. String FileSystemModel::Node::full_path(const FileSystemModel& model) const
  135. {
  136. Vector<String, 32> lineage;
  137. for (auto* ancestor = parent; ancestor; ancestor = ancestor->parent) {
  138. lineage.append(ancestor->name);
  139. }
  140. StringBuilder builder;
  141. builder.append(model.root_path());
  142. for (int i = lineage.size() - 1; i >= 0; --i) {
  143. builder.append('/');
  144. builder.append(lineage[i]);
  145. }
  146. builder.append('/');
  147. builder.append(name);
  148. return canonicalized_path(builder.to_string());
  149. }
  150. ModelIndex FileSystemModel::index(const StringView& path, int column) const
  151. {
  152. FileSystemPath canonical_path(path);
  153. const Node* node = m_root;
  154. if (canonical_path.string() == "/")
  155. return m_root->index(*this, column);
  156. for (size_t i = 0; i < canonical_path.parts().size(); ++i) {
  157. auto& part = canonical_path.parts()[i];
  158. bool found = false;
  159. for (auto& child : node->children) {
  160. if (child.name == part) {
  161. const_cast<Node&>(child).reify_if_needed(*this);
  162. node = &child;
  163. found = true;
  164. if (i == canonical_path.parts().size() - 1)
  165. return child.index(*this, column);
  166. break;
  167. }
  168. }
  169. if (!found)
  170. return {};
  171. }
  172. return {};
  173. }
  174. String FileSystemModel::full_path(const ModelIndex& index) const
  175. {
  176. auto& node = this->node(index);
  177. const_cast<Node&>(node).reify_if_needed(*this);
  178. return node.full_path(*this);
  179. }
  180. FileSystemModel::FileSystemModel(const StringView& root_path, Mode mode)
  181. : m_root_path(canonicalized_path(root_path))
  182. , m_mode(mode)
  183. {
  184. m_directory_icon = Icon::default_icon("filetype-folder");
  185. m_file_icon = Icon::default_icon("filetype-unknown");
  186. m_symlink_icon = Icon::default_icon("filetype-symlink");
  187. m_socket_icon = Icon::default_icon("filetype-socket");
  188. m_executable_icon = Icon::default_icon("filetype-executable");
  189. m_filetype_image_icon = Icon::default_icon("filetype-image");
  190. m_filetype_sound_icon = Icon::default_icon("filetype-sound");
  191. m_filetype_html_icon = Icon::default_icon("filetype-html");
  192. m_filetype_cplusplus_icon = Icon::default_icon("filetype-cplusplus");
  193. m_filetype_java_icon = Icon::default_icon("filetype-java");
  194. m_filetype_javascript_icon = Icon::default_icon("filetype-javascript");
  195. m_filetype_text_icon = Icon::default_icon("filetype-text");
  196. m_filetype_pdf_icon = Icon::default_icon("filetype-pdf");
  197. m_filetype_library_icon = Icon::default_icon("filetype-library");
  198. m_filetype_object_icon = Icon::default_icon("filetype-object");
  199. setpwent();
  200. while (auto* passwd = getpwent())
  201. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  202. endpwent();
  203. setgrent();
  204. while (auto* group = getgrent())
  205. m_group_names.set(group->gr_gid, group->gr_name);
  206. endgrent();
  207. update();
  208. }
  209. FileSystemModel::~FileSystemModel()
  210. {
  211. }
  212. String FileSystemModel::name_for_uid(uid_t uid) const
  213. {
  214. auto it = m_user_names.find(uid);
  215. if (it == m_user_names.end())
  216. return String::number(uid);
  217. return (*it).value;
  218. }
  219. String FileSystemModel::name_for_gid(gid_t gid) const
  220. {
  221. auto it = m_group_names.find(gid);
  222. if (it == m_group_names.end())
  223. return String::number(gid);
  224. return (*it).value;
  225. }
  226. static String permission_string(mode_t mode)
  227. {
  228. StringBuilder builder;
  229. if (S_ISDIR(mode))
  230. builder.append("d");
  231. else if (S_ISLNK(mode))
  232. builder.append("l");
  233. else if (S_ISBLK(mode))
  234. builder.append("b");
  235. else if (S_ISCHR(mode))
  236. builder.append("c");
  237. else if (S_ISFIFO(mode))
  238. builder.append("f");
  239. else if (S_ISSOCK(mode))
  240. builder.append("s");
  241. else if (S_ISREG(mode))
  242. builder.append("-");
  243. else
  244. builder.append("?");
  245. builder.appendf("%c%c%c%c%c%c%c%c",
  246. mode & S_IRUSR ? 'r' : '-',
  247. mode & S_IWUSR ? 'w' : '-',
  248. mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'),
  249. mode & S_IRGRP ? 'r' : '-',
  250. mode & S_IWGRP ? 'w' : '-',
  251. mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'),
  252. mode & S_IROTH ? 'r' : '-',
  253. mode & S_IWOTH ? 'w' : '-');
  254. if (mode & S_ISVTX)
  255. builder.append("t");
  256. else
  257. builder.appendf("%c", mode & S_IXOTH ? 'x' : '-');
  258. return builder.to_string();
  259. }
  260. void FileSystemModel::set_root_path(const StringView& root_path)
  261. {
  262. m_root_path = canonicalized_path(root_path);
  263. if (on_root_path_change)
  264. on_root_path_change();
  265. update();
  266. }
  267. void FileSystemModel::update()
  268. {
  269. m_root = make<Node>();
  270. m_root->reify_if_needed(*this);
  271. did_update();
  272. }
  273. int FileSystemModel::row_count(const ModelIndex& index) const
  274. {
  275. Node& node = const_cast<Node&>(this->node(index));
  276. node.reify_if_needed(*this);
  277. if (node.is_directory())
  278. return node.children.size();
  279. return 0;
  280. }
  281. const FileSystemModel::Node& FileSystemModel::node(const ModelIndex& index) const
  282. {
  283. if (!index.is_valid())
  284. return *m_root;
  285. return *(Node*)index.internal_data();
  286. }
  287. ModelIndex FileSystemModel::index(int row, int column, const ModelIndex& parent) const
  288. {
  289. if (row < 0 || column < 0)
  290. return {};
  291. auto& node = this->node(parent);
  292. const_cast<Node&>(node).reify_if_needed(*this);
  293. if (static_cast<size_t>(row) >= node.children.size())
  294. return {};
  295. return create_index(row, column, &node.children[row]);
  296. }
  297. ModelIndex FileSystemModel::parent_index(const ModelIndex& index) const
  298. {
  299. if (!index.is_valid())
  300. return {};
  301. auto& node = this->node(index);
  302. if (!node.parent) {
  303. ASSERT(&node == m_root);
  304. return {};
  305. }
  306. return node.parent->index(*this, index.column());
  307. }
  308. Variant FileSystemModel::data(const ModelIndex& index, Role role) const
  309. {
  310. ASSERT(index.is_valid());
  311. auto& node = this->node(index);
  312. if (role == Role::Custom) {
  313. // For GUI::FileSystemModel, custom role means the full path.
  314. ASSERT(index.column() == Column::Name);
  315. return node.full_path(*this);
  316. }
  317. if (role == Role::DragData) {
  318. if (index.column() == Column::Name) {
  319. StringBuilder builder;
  320. builder.append("file://");
  321. builder.append(node.full_path(*this));
  322. return builder.to_string();
  323. }
  324. return {};
  325. }
  326. if (role == Role::Sort) {
  327. switch (index.column()) {
  328. case Column::Icon:
  329. return node.is_directory() ? 0 : 1;
  330. case Column::Name:
  331. return node.name;
  332. case Column::Size:
  333. return (int)node.size;
  334. case Column::Owner:
  335. return name_for_uid(node.uid);
  336. case Column::Group:
  337. return name_for_gid(node.gid);
  338. case Column::Permissions:
  339. return permission_string(node.mode);
  340. case Column::ModificationTime:
  341. return node.mtime;
  342. case Column::Inode:
  343. return (int)node.inode;
  344. case Column::SymlinkTarget:
  345. return node.symlink_target;
  346. }
  347. ASSERT_NOT_REACHED();
  348. }
  349. if (role == Role::Display) {
  350. switch (index.column()) {
  351. case Column::Icon:
  352. return icon_for(node);
  353. case Column::Name:
  354. return node.name;
  355. case Column::Size:
  356. return (int)node.size;
  357. case Column::Owner:
  358. return name_for_uid(node.uid);
  359. case Column::Group:
  360. return name_for_gid(node.gid);
  361. case Column::Permissions:
  362. return permission_string(node.mode);
  363. case Column::ModificationTime:
  364. return timestamp_string(node.mtime);
  365. case Column::Inode:
  366. return (int)node.inode;
  367. case Column::SymlinkTarget:
  368. return node.symlink_target;
  369. }
  370. }
  371. if (role == Role::Icon) {
  372. return icon_for(node);
  373. }
  374. return {};
  375. }
  376. Icon FileSystemModel::icon_for_file(const mode_t mode, const String& name) const
  377. {
  378. if (S_ISDIR(mode))
  379. return m_directory_icon;
  380. if (S_ISLNK(mode))
  381. return m_symlink_icon;
  382. if (S_ISSOCK(mode))
  383. return m_socket_icon;
  384. if (mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  385. return m_executable_icon;
  386. if (name.to_lowercase().ends_with(".wav"))
  387. return m_filetype_sound_icon;
  388. if (name.to_lowercase().ends_with(".html"))
  389. return m_filetype_html_icon;
  390. if (name.to_lowercase().ends_with(".png"))
  391. return m_filetype_image_icon;
  392. if (name.to_lowercase().ends_with(".cpp"))
  393. return m_filetype_cplusplus_icon;
  394. if (name.to_lowercase().ends_with(".java"))
  395. return m_filetype_java_icon;
  396. if (name.to_lowercase().ends_with(".js"))
  397. return m_filetype_javascript_icon;
  398. if (name.to_lowercase().ends_with(".txt"))
  399. return m_filetype_text_icon;
  400. if (name.to_lowercase().ends_with(".pdf"))
  401. return m_filetype_pdf_icon;
  402. if (name.to_lowercase().ends_with(".o") || name.to_lowercase().ends_with(".obj"))
  403. return m_filetype_object_icon;
  404. if (name.to_lowercase().ends_with(".so") || name.to_lowercase().ends_with(".a"))
  405. return m_filetype_library_icon;
  406. return m_file_icon;
  407. }
  408. Icon FileSystemModel::icon_for(const Node& node) const
  409. {
  410. if (node.name.to_lowercase().ends_with(".png")) {
  411. if (!node.thumbnail) {
  412. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  413. return m_filetype_image_icon;
  414. }
  415. return GUI::Icon(m_filetype_image_icon.bitmap_for_size(16), *node.thumbnail);
  416. }
  417. return icon_for_file(node.mode, node.name);
  418. }
  419. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  420. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  421. {
  422. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  423. if (!png_bitmap)
  424. return nullptr;
  425. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  426. auto thumbnail = Gfx::Bitmap::create(png_bitmap->format(), { 32, 32 });
  427. Gfx::Rect destination = Gfx::Rect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  428. destination.center_within(thumbnail->rect());
  429. Painter painter(*thumbnail);
  430. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  431. return thumbnail;
  432. }
  433. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  434. {
  435. // See if we already have the thumbnail
  436. // we're looking for in the cache.
  437. auto path = node.full_path(*this);
  438. auto it = s_thumbnail_cache.find(path);
  439. if (it != s_thumbnail_cache.end()) {
  440. if (!(*it).value)
  441. return false;
  442. node.thumbnail = (*it).value;
  443. return true;
  444. }
  445. // Otherwise, arrange to render the thumbnail
  446. // in background and make it available later.
  447. s_thumbnail_cache.set(path, nullptr);
  448. m_thumbnail_progress_total++;
  449. auto weak_this = make_weak_ptr();
  450. LibThread::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  451. [path] {
  452. return render_thumbnail(path);
  453. },
  454. [this, path, weak_this](auto thumbnail) {
  455. s_thumbnail_cache.set(path, move(thumbnail));
  456. // The model was destroyed, no need to update
  457. // progress or call any event handlers.
  458. if (weak_this.is_null())
  459. return;
  460. m_thumbnail_progress++;
  461. if (on_thumbnail_progress)
  462. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  463. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  464. m_thumbnail_progress = 0;
  465. m_thumbnail_progress_total = 0;
  466. }
  467. did_update();
  468. });
  469. return false;
  470. }
  471. int FileSystemModel::column_count(const ModelIndex&) const
  472. {
  473. return Column::__Count;
  474. }
  475. String FileSystemModel::column_name(int column) const
  476. {
  477. switch (column) {
  478. case Column::Icon:
  479. return "";
  480. case Column::Name:
  481. return "Name";
  482. case Column::Size:
  483. return "Size";
  484. case Column::Owner:
  485. return "Owner";
  486. case Column::Group:
  487. return "Group";
  488. case Column::Permissions:
  489. return "Mode";
  490. case Column::ModificationTime:
  491. return "Modified";
  492. case Column::Inode:
  493. return "Inode";
  494. case Column::SymlinkTarget:
  495. return "Symlink target";
  496. }
  497. ASSERT_NOT_REACHED();
  498. }
  499. Model::ColumnMetadata FileSystemModel::column_metadata(int column) const
  500. {
  501. switch (column) {
  502. case Column::Icon:
  503. return { 16, Gfx::TextAlignment::Center, nullptr, Model::ColumnMetadata::Sortable::False };
  504. case Column::Name:
  505. return { 120, Gfx::TextAlignment::CenterLeft };
  506. case Column::Size:
  507. return { 80, Gfx::TextAlignment::CenterRight };
  508. case Column::Owner:
  509. return { 50, Gfx::TextAlignment::CenterLeft };
  510. case Column::Group:
  511. return { 50, Gfx::TextAlignment::CenterLeft };
  512. case Column::ModificationTime:
  513. return { 110, Gfx::TextAlignment::CenterLeft };
  514. case Column::Permissions:
  515. return { 65, Gfx::TextAlignment::CenterLeft };
  516. case Column::Inode:
  517. return { 60, Gfx::TextAlignment::CenterRight };
  518. case Column::SymlinkTarget:
  519. return { 120, Gfx::TextAlignment::CenterLeft };
  520. }
  521. ASSERT_NOT_REACHED();
  522. }
  523. bool FileSystemModel::accepts_drag(const ModelIndex& index, const StringView& data_type)
  524. {
  525. if (!index.is_valid())
  526. return false;
  527. if (data_type != "text/uri-list")
  528. return false;
  529. auto& node = this->node(index);
  530. return node.is_directory();
  531. }
  532. }