FileSystemModel.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/LexicalPath.h>
  8. #include <AK/NumberFormat.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibCore/DirIterator.h>
  12. #include <LibCore/File.h>
  13. #include <LibCore/StandardPaths.h>
  14. #include <LibGUI/FileIconProvider.h>
  15. #include <LibGUI/FileSystemModel.h>
  16. #include <LibGUI/Painter.h>
  17. #include <LibGfx/Bitmap.h>
  18. #include <LibThread/BackgroundAction.h>
  19. #include <grp.h>
  20. #include <pwd.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include <sys/stat.h>
  24. #include <unistd.h>
  25. namespace GUI {
  26. ModelIndex FileSystemModel::Node::index(int column) const
  27. {
  28. if (!parent)
  29. return {};
  30. for (size_t row = 0; row < parent->children.size(); ++row) {
  31. if (&parent->children[row] == this)
  32. return m_model.create_index(row, column, const_cast<Node*>(this));
  33. }
  34. VERIFY_NOT_REACHED();
  35. }
  36. bool FileSystemModel::Node::fetch_data(const String& full_path, bool is_root)
  37. {
  38. struct stat st;
  39. int rc;
  40. if (is_root)
  41. rc = stat(full_path.characters(), &st);
  42. else
  43. rc = lstat(full_path.characters(), &st);
  44. if (rc < 0) {
  45. m_error = errno;
  46. perror("stat/lstat");
  47. return false;
  48. }
  49. size = st.st_size;
  50. mode = st.st_mode;
  51. uid = st.st_uid;
  52. gid = st.st_gid;
  53. inode = st.st_ino;
  54. mtime = st.st_mtime;
  55. if (S_ISLNK(mode)) {
  56. symlink_target = Core::File::read_link(full_path);
  57. if (symlink_target.is_null())
  58. perror("readlink");
  59. }
  60. if (S_ISDIR(mode)) {
  61. is_accessible_directory = access(full_path.characters(), R_OK | X_OK) == 0;
  62. }
  63. return true;
  64. }
  65. void FileSystemModel::Node::traverse_if_needed()
  66. {
  67. if (!is_directory() || has_traversed)
  68. return;
  69. has_traversed = true;
  70. if (m_parent_of_root) {
  71. auto root = adopt_own(*new Node(m_model));
  72. root->fetch_data("/", true);
  73. root->name = "/";
  74. root->parent = this;
  75. children.append(move(root));
  76. return;
  77. }
  78. total_size = 0;
  79. auto full_path = this->full_path();
  80. Core::DirIterator di(full_path, m_model.should_show_dotfiles() ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  81. if (di.has_error()) {
  82. m_error = di.error();
  83. fprintf(stderr, "DirIterator: %s\n", di.error_string());
  84. return;
  85. }
  86. Vector<String> child_names;
  87. while (di.has_next()) {
  88. child_names.append(di.next_path());
  89. }
  90. quick_sort(child_names);
  91. NonnullOwnPtrVector<Node> directory_children;
  92. NonnullOwnPtrVector<Node> file_children;
  93. for (auto& child_name : child_names) {
  94. String child_path = String::formatted("{}/{}", full_path, child_name);
  95. auto child = adopt_own(*new Node(m_model));
  96. bool ok = child->fetch_data(child_path, false);
  97. if (!ok)
  98. continue;
  99. if (m_model.m_mode == DirectoriesOnly && !S_ISDIR(child->mode))
  100. continue;
  101. child->name = child_name;
  102. child->parent = this;
  103. total_size += child->size;
  104. if (S_ISDIR(child->mode))
  105. directory_children.append(move(child));
  106. else
  107. file_children.append(move(child));
  108. }
  109. children.append(move(directory_children));
  110. children.append(move(file_children));
  111. if (!m_model.m_file_watcher->is_watching(full_path)) {
  112. // We are not already watching this file, watch it
  113. auto result = m_model.m_file_watcher->add_watch(full_path,
  114. Core::FileWatcherEvent::Type::MetadataModified
  115. | Core::FileWatcherEvent::Type::ChildCreated
  116. | Core::FileWatcherEvent::Type::ChildDeleted
  117. | Core::FileWatcherEvent::Type::Deleted);
  118. if (result.is_error()) {
  119. dbgln("Couldn't watch '{}': {}", full_path, result.error());
  120. } else if (result.value() == false) {
  121. dbgln("Couldn't watch '{}', probably already watching", full_path);
  122. }
  123. }
  124. }
  125. void FileSystemModel::Node::reify_if_needed()
  126. {
  127. traverse_if_needed();
  128. if (mode != 0)
  129. return;
  130. fetch_data(full_path(), parent == nullptr || parent->m_parent_of_root);
  131. }
  132. bool FileSystemModel::Node::is_symlink_to_directory() const
  133. {
  134. if (!S_ISLNK(mode))
  135. return false;
  136. struct stat st;
  137. if (lstat(symlink_target.characters(), &st) < 0)
  138. return false;
  139. return S_ISDIR(st.st_mode);
  140. }
  141. String FileSystemModel::Node::full_path() const
  142. {
  143. Vector<String, 32> lineage;
  144. for (auto* ancestor = parent; ancestor; ancestor = ancestor->parent) {
  145. lineage.append(ancestor->name);
  146. }
  147. StringBuilder builder;
  148. builder.append(m_model.root_path());
  149. for (int i = lineage.size() - 1; i >= 0; --i) {
  150. builder.append('/');
  151. builder.append(lineage[i]);
  152. }
  153. builder.append('/');
  154. builder.append(name);
  155. return LexicalPath::canonicalized_path(builder.to_string());
  156. }
  157. ModelIndex FileSystemModel::index(String path, int column) const
  158. {
  159. Node const* node = node_for_path(move(path));
  160. if (node != nullptr) {
  161. return node->index(column);
  162. }
  163. return {};
  164. }
  165. FileSystemModel::Node const* FileSystemModel::node_for_path(String const& path) const
  166. {
  167. LexicalPath lexical_path;
  168. if (path == m_root_path) {
  169. lexical_path = LexicalPath { "/" };
  170. } else if (!m_root_path.is_empty() && path.starts_with(m_root_path)) {
  171. lexical_path = LexicalPath { LexicalPath::relative_path(path, m_root_path) };
  172. } else {
  173. lexical_path = LexicalPath { move(path) };
  174. }
  175. const Node* node = m_root->m_parent_of_root ? &m_root->children.first() : m_root;
  176. if (lexical_path.string() == "/")
  177. return node;
  178. for (size_t i = 0; i < lexical_path.parts().size(); ++i) {
  179. auto& part = lexical_path.parts()[i];
  180. bool found = false;
  181. for (auto& child : node->children) {
  182. if (child.name == part) {
  183. const_cast<Node&>(child).reify_if_needed();
  184. node = &child;
  185. found = true;
  186. if (i == lexical_path.parts().size() - 1)
  187. return node;
  188. break;
  189. }
  190. }
  191. if (!found)
  192. return nullptr;
  193. }
  194. return nullptr;
  195. }
  196. String FileSystemModel::full_path(const ModelIndex& index) const
  197. {
  198. auto& node = this->node(index);
  199. const_cast<Node&>(node).reify_if_needed();
  200. return node.full_path();
  201. }
  202. FileSystemModel::FileSystemModel(String root_path, Mode mode)
  203. : m_root_path(LexicalPath::canonicalized_path(move(root_path)))
  204. , m_mode(mode)
  205. {
  206. setpwent();
  207. while (auto* passwd = getpwent())
  208. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  209. endpwent();
  210. setgrent();
  211. while (auto* group = getgrent())
  212. m_group_names.set(group->gr_gid, group->gr_name);
  213. endgrent();
  214. auto result = Core::FileWatcher::create();
  215. if (result.is_error()) {
  216. dbgln("{}", result.error());
  217. VERIFY_NOT_REACHED();
  218. }
  219. m_file_watcher = result.release_value();
  220. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  221. Node const* maybe_node = node_for_path(event.event_path);
  222. if (maybe_node == nullptr) {
  223. dbgln("Received event at \"{}\" but we don't have that node", event.event_path);
  224. return;
  225. }
  226. auto& node = *const_cast<Node*>(maybe_node);
  227. dbgln("Event at \"{}\" on Node {}: {}", node.full_path(), &node, event);
  228. // FIXME: Your time is coming, un-granular updates.
  229. node.has_traversed = false;
  230. node.mode = 0;
  231. node.children.clear();
  232. node.reify_if_needed();
  233. did_update();
  234. };
  235. update();
  236. }
  237. FileSystemModel::~FileSystemModel()
  238. {
  239. }
  240. String FileSystemModel::name_for_uid(uid_t uid) const
  241. {
  242. auto it = m_user_names.find(uid);
  243. if (it == m_user_names.end())
  244. return String::number(uid);
  245. return (*it).value;
  246. }
  247. String FileSystemModel::name_for_gid(gid_t gid) const
  248. {
  249. auto it = m_group_names.find(gid);
  250. if (it == m_group_names.end())
  251. return String::number(gid);
  252. return (*it).value;
  253. }
  254. static String permission_string(mode_t mode)
  255. {
  256. StringBuilder builder;
  257. if (S_ISDIR(mode))
  258. builder.append("d");
  259. else if (S_ISLNK(mode))
  260. builder.append("l");
  261. else if (S_ISBLK(mode))
  262. builder.append("b");
  263. else if (S_ISCHR(mode))
  264. builder.append("c");
  265. else if (S_ISFIFO(mode))
  266. builder.append("f");
  267. else if (S_ISSOCK(mode))
  268. builder.append("s");
  269. else if (S_ISREG(mode))
  270. builder.append("-");
  271. else
  272. builder.append("?");
  273. builder.append(mode & S_IRUSR ? 'r' : '-');
  274. builder.append(mode & S_IWUSR ? 'w' : '-');
  275. builder.append(mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'));
  276. builder.append(mode & S_IRGRP ? 'r' : '-');
  277. builder.append(mode & S_IWGRP ? 'w' : '-');
  278. builder.append(mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'));
  279. builder.append(mode & S_IROTH ? 'r' : '-');
  280. builder.append(mode & S_IWOTH ? 'w' : '-');
  281. if (mode & S_ISVTX)
  282. builder.append('t');
  283. else
  284. builder.append(mode & S_IXOTH ? 'x' : '-');
  285. return builder.to_string();
  286. }
  287. void FileSystemModel::Node::set_selected(bool selected)
  288. {
  289. if (m_selected == selected)
  290. return;
  291. m_selected = selected;
  292. }
  293. void FileSystemModel::update_node_on_selection(const ModelIndex& index, const bool selected)
  294. {
  295. Node& node = const_cast<Node&>(this->node(index));
  296. node.set_selected(selected);
  297. }
  298. void FileSystemModel::set_root_path(String root_path)
  299. {
  300. if (root_path.is_null())
  301. m_root_path = {};
  302. else
  303. m_root_path = LexicalPath::canonicalized_path(move(root_path));
  304. update();
  305. if (m_root->has_error()) {
  306. if (on_error)
  307. on_error(m_root->error(), m_root->error_string());
  308. } else if (on_complete) {
  309. on_complete();
  310. }
  311. }
  312. void FileSystemModel::update()
  313. {
  314. m_root = adopt_own(*new Node(*this));
  315. if (m_root_path.is_null())
  316. m_root->m_parent_of_root = true;
  317. m_root->reify_if_needed();
  318. did_update();
  319. }
  320. int FileSystemModel::row_count(const ModelIndex& index) const
  321. {
  322. Node& node = const_cast<Node&>(this->node(index));
  323. node.reify_if_needed();
  324. if (node.is_directory())
  325. return node.children.size();
  326. return 0;
  327. }
  328. const FileSystemModel::Node& FileSystemModel::node(const ModelIndex& index) const
  329. {
  330. if (!index.is_valid())
  331. return *m_root;
  332. VERIFY(index.internal_data());
  333. return *(Node*)index.internal_data();
  334. }
  335. ModelIndex FileSystemModel::index(int row, int column, const ModelIndex& parent) const
  336. {
  337. if (row < 0 || column < 0)
  338. return {};
  339. auto& node = this->node(parent);
  340. const_cast<Node&>(node).reify_if_needed();
  341. if (static_cast<size_t>(row) >= node.children.size())
  342. return {};
  343. return create_index(row, column, &node.children[row]);
  344. }
  345. ModelIndex FileSystemModel::parent_index(const ModelIndex& index) const
  346. {
  347. if (!index.is_valid())
  348. return {};
  349. auto& node = this->node(index);
  350. if (!node.parent) {
  351. VERIFY(&node == m_root);
  352. return {};
  353. }
  354. return node.parent->index(index.column());
  355. }
  356. Variant FileSystemModel::data(const ModelIndex& index, ModelRole role) const
  357. {
  358. VERIFY(index.is_valid());
  359. if (role == ModelRole::TextAlignment) {
  360. switch (index.column()) {
  361. case Column::Icon:
  362. return Gfx::TextAlignment::Center;
  363. case Column::Size:
  364. case Column::Inode:
  365. return Gfx::TextAlignment::CenterRight;
  366. case Column::Name:
  367. case Column::Owner:
  368. case Column::Group:
  369. case Column::ModificationTime:
  370. case Column::Permissions:
  371. case Column::SymlinkTarget:
  372. return Gfx::TextAlignment::CenterLeft;
  373. default:
  374. VERIFY_NOT_REACHED();
  375. }
  376. }
  377. auto& node = this->node(index);
  378. if (role == ModelRole::Custom) {
  379. // For GUI::FileSystemModel, custom role means the full path.
  380. VERIFY(index.column() == Column::Name);
  381. return node.full_path();
  382. }
  383. if (role == ModelRole::MimeData) {
  384. if (index.column() == Column::Name) {
  385. StringBuilder builder;
  386. builder.append("file://");
  387. builder.append(node.full_path());
  388. return builder.to_string();
  389. }
  390. return {};
  391. }
  392. if (role == ModelRole::Sort) {
  393. switch (index.column()) {
  394. case Column::Icon:
  395. return node.is_directory() ? 0 : 1;
  396. case Column::Name:
  397. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  398. // Hence, the sort value for the name column is simply the index row. :^)
  399. return index.row();
  400. case Column::Size:
  401. return (int)node.size;
  402. case Column::Owner:
  403. return name_for_uid(node.uid);
  404. case Column::Group:
  405. return name_for_gid(node.gid);
  406. case Column::Permissions:
  407. return permission_string(node.mode);
  408. case Column::ModificationTime:
  409. return node.mtime;
  410. case Column::Inode:
  411. return (int)node.inode;
  412. case Column::SymlinkTarget:
  413. return node.symlink_target;
  414. }
  415. VERIFY_NOT_REACHED();
  416. }
  417. if (role == ModelRole::Display) {
  418. switch (index.column()) {
  419. case Column::Icon:
  420. return icon_for(node);
  421. case Column::Name:
  422. return node.name;
  423. case Column::Size:
  424. return human_readable_size(node.size);
  425. case Column::Owner:
  426. return name_for_uid(node.uid);
  427. case Column::Group:
  428. return name_for_gid(node.gid);
  429. case Column::Permissions:
  430. return permission_string(node.mode);
  431. case Column::ModificationTime:
  432. return timestamp_string(node.mtime);
  433. case Column::Inode:
  434. return (int)node.inode;
  435. case Column::SymlinkTarget:
  436. return node.symlink_target;
  437. }
  438. }
  439. if (role == ModelRole::Icon) {
  440. return icon_for(node);
  441. }
  442. return {};
  443. }
  444. Icon FileSystemModel::icon_for(const Node& node) const
  445. {
  446. if (node.full_path() == "/")
  447. return FileIconProvider::icon_for_path("/");
  448. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  449. if (!node.thumbnail) {
  450. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  451. return FileIconProvider::filetype_image_icon();
  452. }
  453. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  454. }
  455. if (node.is_directory()) {
  456. if (node.full_path() == Core::StandardPaths::home_directory()) {
  457. if (node.is_selected())
  458. return FileIconProvider::home_directory_open_icon();
  459. return FileIconProvider::home_directory_icon();
  460. }
  461. if (node.full_path() == Core::StandardPaths::desktop_directory())
  462. return FileIconProvider::desktop_directory_icon();
  463. if (node.is_selected() && node.is_accessible_directory)
  464. return FileIconProvider::directory_open_icon();
  465. }
  466. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  467. }
  468. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  469. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  470. {
  471. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  472. if (!png_bitmap)
  473. return nullptr;
  474. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  475. auto thumbnail = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 32, 32 });
  476. Gfx::IntRect destination = Gfx::IntRect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  477. destination.center_within(thumbnail->rect());
  478. Painter painter(*thumbnail);
  479. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  480. return thumbnail;
  481. }
  482. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  483. {
  484. // See if we already have the thumbnail
  485. // we're looking for in the cache.
  486. auto path = node.full_path();
  487. auto it = s_thumbnail_cache.find(path);
  488. if (it != s_thumbnail_cache.end()) {
  489. if (!(*it).value)
  490. return false;
  491. node.thumbnail = (*it).value;
  492. return true;
  493. }
  494. // Otherwise, arrange to render the thumbnail
  495. // in background and make it available later.
  496. s_thumbnail_cache.set(path, nullptr);
  497. m_thumbnail_progress_total++;
  498. auto weak_this = make_weak_ptr();
  499. LibThread::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  500. [path] {
  501. return render_thumbnail(path);
  502. },
  503. [this, path, weak_this](auto thumbnail) {
  504. s_thumbnail_cache.set(path, move(thumbnail));
  505. // The model was destroyed, no need to update
  506. // progress or call any event handlers.
  507. if (weak_this.is_null())
  508. return;
  509. m_thumbnail_progress++;
  510. if (on_thumbnail_progress)
  511. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  512. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  513. m_thumbnail_progress = 0;
  514. m_thumbnail_progress_total = 0;
  515. }
  516. did_update();
  517. });
  518. return false;
  519. }
  520. int FileSystemModel::column_count(const ModelIndex&) const
  521. {
  522. return Column::__Count;
  523. }
  524. String FileSystemModel::column_name(int column) const
  525. {
  526. switch (column) {
  527. case Column::Icon:
  528. return "";
  529. case Column::Name:
  530. return "Name";
  531. case Column::Size:
  532. return "Size";
  533. case Column::Owner:
  534. return "Owner";
  535. case Column::Group:
  536. return "Group";
  537. case Column::Permissions:
  538. return "Mode";
  539. case Column::ModificationTime:
  540. return "Modified";
  541. case Column::Inode:
  542. return "Inode";
  543. case Column::SymlinkTarget:
  544. return "Symlink target";
  545. }
  546. VERIFY_NOT_REACHED();
  547. }
  548. bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) const
  549. {
  550. if (!index.is_valid())
  551. return false;
  552. if (!mime_types.contains_slow("text/uri-list"))
  553. return false;
  554. auto& node = this->node(index);
  555. return node.is_directory();
  556. }
  557. void FileSystemModel::set_should_show_dotfiles(bool show)
  558. {
  559. if (m_should_show_dotfiles == show)
  560. return;
  561. m_should_show_dotfiles = show;
  562. update();
  563. }
  564. bool FileSystemModel::is_editable(const ModelIndex& index) const
  565. {
  566. if (!index.is_valid())
  567. return false;
  568. return index.column() == Column::Name;
  569. }
  570. void FileSystemModel::set_data(const ModelIndex& index, const Variant& data)
  571. {
  572. VERIFY(is_editable(index));
  573. Node& node = const_cast<Node&>(this->node(index));
  574. auto dirname = LexicalPath(node.full_path()).dirname();
  575. auto new_full_path = String::formatted("{}/{}", dirname, data.to_string());
  576. int rc = rename(node.full_path().characters(), new_full_path.characters());
  577. if (rc < 0) {
  578. if (on_error)
  579. on_error(errno, strerror(errno));
  580. }
  581. }
  582. Vector<ModelIndex, 1> FileSystemModel::matches(const StringView& searching, unsigned flags, const ModelIndex& index)
  583. {
  584. Node& node = const_cast<Node&>(this->node(index));
  585. node.reify_if_needed();
  586. Vector<ModelIndex, 1> found_indices;
  587. for (auto& child : node.children) {
  588. if (string_matches(child.name, searching, flags)) {
  589. const_cast<Node&>(child).reify_if_needed();
  590. found_indices.append(child.index(Column::Name));
  591. if (flags & FirstMatchOnly)
  592. break;
  593. }
  594. }
  595. return found_indices;
  596. }
  597. }