FileSystemModel.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 <LibThreading/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. warnln("DirIterator: {}", 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.extend(move(directory_children));
  110. children.extend(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. String resolved_path;
  168. if (path == m_root_path)
  169. resolved_path = "/";
  170. else if (!m_root_path.is_empty() && path.starts_with(m_root_path))
  171. resolved_path = LexicalPath::relative_path(path, m_root_path);
  172. else
  173. resolved_path = path;
  174. LexicalPath lexical_path(resolved_path);
  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. auto& parts = lexical_path.parts_view();
  179. for (size_t i = 0; i < parts.size(); ++i) {
  180. auto& part = parts[i];
  181. bool found = false;
  182. for (auto& child : node->children) {
  183. if (child.name == part) {
  184. const_cast<Node&>(child).reify_if_needed();
  185. node = &child;
  186. found = true;
  187. if (i == parts.size() - 1)
  188. return node;
  189. break;
  190. }
  191. }
  192. if (!found)
  193. return nullptr;
  194. }
  195. return nullptr;
  196. }
  197. String FileSystemModel::full_path(const ModelIndex& index) const
  198. {
  199. auto& node = this->node(index);
  200. const_cast<Node&>(node).reify_if_needed();
  201. return node.full_path();
  202. }
  203. FileSystemModel::FileSystemModel(String root_path, Mode mode)
  204. : m_root_path(LexicalPath::canonicalized_path(move(root_path)))
  205. , m_mode(mode)
  206. {
  207. setpwent();
  208. while (auto* passwd = getpwent())
  209. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  210. endpwent();
  211. setgrent();
  212. while (auto* group = getgrent())
  213. m_group_names.set(group->gr_gid, group->gr_name);
  214. endgrent();
  215. auto result = Core::FileWatcher::create();
  216. if (result.is_error()) {
  217. dbgln("{}", result.error());
  218. VERIFY_NOT_REACHED();
  219. }
  220. m_file_watcher = result.release_value();
  221. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  222. Node const* maybe_node = node_for_path(event.event_path);
  223. if (maybe_node == nullptr) {
  224. dbgln("Received event at \"{}\" but we don't have that node", event.event_path);
  225. return;
  226. }
  227. auto& node = *const_cast<Node*>(maybe_node);
  228. dbgln("Event at \"{}\" on Node {}: {}", node.full_path(), &node, event);
  229. // FIXME: Your time is coming, un-granular updates.
  230. node.has_traversed = false;
  231. node.mode = 0;
  232. node.children.clear();
  233. node.reify_if_needed();
  234. did_update();
  235. };
  236. update();
  237. }
  238. FileSystemModel::~FileSystemModel()
  239. {
  240. }
  241. String FileSystemModel::name_for_uid(uid_t uid) const
  242. {
  243. auto it = m_user_names.find(uid);
  244. if (it == m_user_names.end())
  245. return String::number(uid);
  246. return (*it).value;
  247. }
  248. String FileSystemModel::name_for_gid(gid_t gid) const
  249. {
  250. auto it = m_group_names.find(gid);
  251. if (it == m_group_names.end())
  252. return String::number(gid);
  253. return (*it).value;
  254. }
  255. static String permission_string(mode_t mode)
  256. {
  257. StringBuilder builder;
  258. if (S_ISDIR(mode))
  259. builder.append("d");
  260. else if (S_ISLNK(mode))
  261. builder.append("l");
  262. else if (S_ISBLK(mode))
  263. builder.append("b");
  264. else if (S_ISCHR(mode))
  265. builder.append("c");
  266. else if (S_ISFIFO(mode))
  267. builder.append("f");
  268. else if (S_ISSOCK(mode))
  269. builder.append("s");
  270. else if (S_ISREG(mode))
  271. builder.append("-");
  272. else
  273. builder.append("?");
  274. builder.append(mode & S_IRUSR ? 'r' : '-');
  275. builder.append(mode & S_IWUSR ? 'w' : '-');
  276. builder.append(mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'));
  277. builder.append(mode & S_IRGRP ? 'r' : '-');
  278. builder.append(mode & S_IWGRP ? 'w' : '-');
  279. builder.append(mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'));
  280. builder.append(mode & S_IROTH ? 'r' : '-');
  281. builder.append(mode & S_IWOTH ? 'w' : '-');
  282. if (mode & S_ISVTX)
  283. builder.append('t');
  284. else
  285. builder.append(mode & S_IXOTH ? 'x' : '-');
  286. return builder.to_string();
  287. }
  288. void FileSystemModel::Node::set_selected(bool selected)
  289. {
  290. if (m_selected == selected)
  291. return;
  292. m_selected = selected;
  293. }
  294. void FileSystemModel::update_node_on_selection(const ModelIndex& index, const bool selected)
  295. {
  296. Node& node = const_cast<Node&>(this->node(index));
  297. node.set_selected(selected);
  298. }
  299. void FileSystemModel::set_root_path(String root_path)
  300. {
  301. if (root_path.is_null())
  302. m_root_path = {};
  303. else
  304. m_root_path = LexicalPath::canonicalized_path(move(root_path));
  305. update();
  306. if (m_root->has_error()) {
  307. if (on_error)
  308. on_error(m_root->error(), m_root->error_string());
  309. } else if (on_complete) {
  310. on_complete();
  311. }
  312. }
  313. void FileSystemModel::update()
  314. {
  315. m_root = adopt_own(*new Node(*this));
  316. if (m_root_path.is_null())
  317. m_root->m_parent_of_root = true;
  318. m_root->reify_if_needed();
  319. did_update();
  320. }
  321. int FileSystemModel::row_count(const ModelIndex& index) const
  322. {
  323. Node& node = const_cast<Node&>(this->node(index));
  324. node.reify_if_needed();
  325. if (node.is_directory())
  326. return node.children.size();
  327. return 0;
  328. }
  329. const FileSystemModel::Node& FileSystemModel::node(const ModelIndex& index) const
  330. {
  331. if (!index.is_valid())
  332. return *m_root;
  333. VERIFY(index.internal_data());
  334. return *(Node*)index.internal_data();
  335. }
  336. ModelIndex FileSystemModel::index(int row, int column, const ModelIndex& parent) const
  337. {
  338. if (row < 0 || column < 0)
  339. return {};
  340. auto& node = this->node(parent);
  341. const_cast<Node&>(node).reify_if_needed();
  342. if (static_cast<size_t>(row) >= node.children.size())
  343. return {};
  344. return create_index(row, column, &node.children[row]);
  345. }
  346. ModelIndex FileSystemModel::parent_index(const ModelIndex& index) const
  347. {
  348. if (!index.is_valid())
  349. return {};
  350. auto& node = this->node(index);
  351. if (!node.parent) {
  352. VERIFY(&node == m_root);
  353. return {};
  354. }
  355. return node.parent->index(index.column());
  356. }
  357. Variant FileSystemModel::data(const ModelIndex& index, ModelRole role) const
  358. {
  359. VERIFY(index.is_valid());
  360. if (role == ModelRole::TextAlignment) {
  361. switch (index.column()) {
  362. case Column::Icon:
  363. return Gfx::TextAlignment::Center;
  364. case Column::Size:
  365. case Column::Inode:
  366. return Gfx::TextAlignment::CenterRight;
  367. case Column::Name:
  368. case Column::Owner:
  369. case Column::Group:
  370. case Column::ModificationTime:
  371. case Column::Permissions:
  372. case Column::SymlinkTarget:
  373. return Gfx::TextAlignment::CenterLeft;
  374. default:
  375. VERIFY_NOT_REACHED();
  376. }
  377. }
  378. auto& node = this->node(index);
  379. if (role == ModelRole::Custom) {
  380. // For GUI::FileSystemModel, custom role means the full path.
  381. VERIFY(index.column() == Column::Name);
  382. return node.full_path();
  383. }
  384. if (role == ModelRole::MimeData) {
  385. if (index.column() == Column::Name)
  386. return URL::create_with_file_scheme(node.full_path()).serialize();
  387. return {};
  388. }
  389. if (role == ModelRole::Sort) {
  390. switch (index.column()) {
  391. case Column::Icon:
  392. return node.is_directory() ? 0 : 1;
  393. case Column::Name:
  394. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  395. // Hence, the sort value for the name column is simply the index row. :^)
  396. return index.row();
  397. case Column::Size:
  398. return (int)node.size;
  399. case Column::Owner:
  400. return name_for_uid(node.uid);
  401. case Column::Group:
  402. return name_for_gid(node.gid);
  403. case Column::Permissions:
  404. return permission_string(node.mode);
  405. case Column::ModificationTime:
  406. return node.mtime;
  407. case Column::Inode:
  408. return (int)node.inode;
  409. case Column::SymlinkTarget:
  410. return node.symlink_target;
  411. }
  412. VERIFY_NOT_REACHED();
  413. }
  414. if (role == ModelRole::Display) {
  415. switch (index.column()) {
  416. case Column::Icon:
  417. return icon_for(node);
  418. case Column::Name:
  419. return node.name;
  420. case Column::Size:
  421. return human_readable_size(node.size);
  422. case Column::Owner:
  423. return name_for_uid(node.uid);
  424. case Column::Group:
  425. return name_for_gid(node.gid);
  426. case Column::Permissions:
  427. return permission_string(node.mode);
  428. case Column::ModificationTime:
  429. return timestamp_string(node.mtime);
  430. case Column::Inode:
  431. return (int)node.inode;
  432. case Column::SymlinkTarget:
  433. return node.symlink_target;
  434. }
  435. }
  436. if (role == ModelRole::Icon) {
  437. return icon_for(node);
  438. }
  439. return {};
  440. }
  441. Icon FileSystemModel::icon_for(const Node& node) const
  442. {
  443. if (node.full_path() == "/")
  444. return FileIconProvider::icon_for_path("/");
  445. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  446. if (!node.thumbnail) {
  447. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  448. return FileIconProvider::filetype_image_icon();
  449. }
  450. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  451. }
  452. if (node.is_directory()) {
  453. if (node.full_path() == Core::StandardPaths::home_directory()) {
  454. if (node.is_selected())
  455. return FileIconProvider::home_directory_open_icon();
  456. return FileIconProvider::home_directory_icon();
  457. }
  458. if (node.full_path() == Core::StandardPaths::desktop_directory())
  459. return FileIconProvider::desktop_directory_icon();
  460. if (node.is_selected() && node.is_accessible_directory)
  461. return FileIconProvider::directory_open_icon();
  462. }
  463. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  464. }
  465. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  466. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  467. {
  468. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  469. if (!png_bitmap)
  470. return nullptr;
  471. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  472. auto thumbnail = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 32, 32 });
  473. Gfx::IntRect destination = Gfx::IntRect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  474. destination.center_within(thumbnail->rect());
  475. Painter painter(*thumbnail);
  476. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  477. return thumbnail;
  478. }
  479. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  480. {
  481. // See if we already have the thumbnail
  482. // we're looking for in the cache.
  483. auto path = node.full_path();
  484. auto it = s_thumbnail_cache.find(path);
  485. if (it != s_thumbnail_cache.end()) {
  486. if (!(*it).value)
  487. return false;
  488. node.thumbnail = (*it).value;
  489. return true;
  490. }
  491. // Otherwise, arrange to render the thumbnail
  492. // in background and make it available later.
  493. s_thumbnail_cache.set(path, nullptr);
  494. m_thumbnail_progress_total++;
  495. auto weak_this = make_weak_ptr();
  496. Threading::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  497. [path] {
  498. return render_thumbnail(path);
  499. },
  500. [this, path, weak_this](auto thumbnail) {
  501. s_thumbnail_cache.set(path, move(thumbnail));
  502. // The model was destroyed, no need to update
  503. // progress or call any event handlers.
  504. if (weak_this.is_null())
  505. return;
  506. m_thumbnail_progress++;
  507. if (on_thumbnail_progress)
  508. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  509. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  510. m_thumbnail_progress = 0;
  511. m_thumbnail_progress_total = 0;
  512. }
  513. did_update(UpdateFlag::DontInvalidateIndices);
  514. });
  515. return false;
  516. }
  517. int FileSystemModel::column_count(const ModelIndex&) const
  518. {
  519. return Column::__Count;
  520. }
  521. String FileSystemModel::column_name(int column) const
  522. {
  523. switch (column) {
  524. case Column::Icon:
  525. return "";
  526. case Column::Name:
  527. return "Name";
  528. case Column::Size:
  529. return "Size";
  530. case Column::Owner:
  531. return "Owner";
  532. case Column::Group:
  533. return "Group";
  534. case Column::Permissions:
  535. return "Mode";
  536. case Column::ModificationTime:
  537. return "Modified";
  538. case Column::Inode:
  539. return "Inode";
  540. case Column::SymlinkTarget:
  541. return "Symlink target";
  542. }
  543. VERIFY_NOT_REACHED();
  544. }
  545. bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) const
  546. {
  547. if (!index.is_valid())
  548. return false;
  549. if (!mime_types.contains_slow("text/uri-list"))
  550. return false;
  551. auto& node = this->node(index);
  552. return node.is_directory();
  553. }
  554. void FileSystemModel::set_should_show_dotfiles(bool show)
  555. {
  556. if (m_should_show_dotfiles == show)
  557. return;
  558. m_should_show_dotfiles = show;
  559. update();
  560. }
  561. bool FileSystemModel::is_editable(const ModelIndex& index) const
  562. {
  563. if (!index.is_valid())
  564. return false;
  565. return index.column() == Column::Name;
  566. }
  567. void FileSystemModel::set_data(const ModelIndex& index, const Variant& data)
  568. {
  569. VERIFY(is_editable(index));
  570. Node& node = const_cast<Node&>(this->node(index));
  571. auto dirname = LexicalPath::dirname(node.full_path());
  572. auto new_full_path = String::formatted("{}/{}", dirname, data.to_string());
  573. int rc = rename(node.full_path().characters(), new_full_path.characters());
  574. if (rc < 0) {
  575. if (on_error)
  576. on_error(errno, strerror(errno));
  577. }
  578. }
  579. Vector<ModelIndex, 1> FileSystemModel::matches(const StringView& searching, unsigned flags, const ModelIndex& index)
  580. {
  581. Node& node = const_cast<Node&>(this->node(index));
  582. node.reify_if_needed();
  583. Vector<ModelIndex, 1> found_indices;
  584. for (auto& child : node.children) {
  585. if (string_matches(child.name, searching, flags)) {
  586. const_cast<Node&>(child).reify_if_needed();
  587. found_indices.append(child.index(Column::Name));
  588. if (flags & FirstMatchOnly)
  589. break;
  590. }
  591. }
  592. return found_indices;
  593. }
  594. }