FileSystemModel.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/LexicalPath.h>
  9. #include <AK/NumberFormat.h>
  10. #include <AK/QuickSort.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Types.h>
  13. #include <LibCore/DirIterator.h>
  14. #include <LibCore/StandardPaths.h>
  15. #include <LibFileSystem/FileSystem.h>
  16. #include <LibGUI/AbstractView.h>
  17. #include <LibGUI/FileIconProvider.h>
  18. #include <LibGUI/FileSystemModel.h>
  19. #include <LibGUI/Painter.h>
  20. #include <LibGfx/Bitmap.h>
  21. #include <LibThreading/BackgroundAction.h>
  22. #include <LibThreading/MutexProtected.h>
  23. #include <grp.h>
  24. #include <pwd.h>
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <sys/stat.h>
  28. #include <unistd.h>
  29. namespace GUI {
  30. ModelIndex FileSystemModel::Node::index(int column) const
  31. {
  32. if (!m_parent)
  33. return {};
  34. for (size_t row = 0; row < m_parent->m_children.size(); ++row) {
  35. if (m_parent->m_children[row] == this)
  36. return m_model.create_index(row, column, const_cast<Node*>(this));
  37. }
  38. VERIFY_NOT_REACHED();
  39. }
  40. bool FileSystemModel::Node::fetch_data(DeprecatedString const& full_path, bool is_root)
  41. {
  42. struct stat st;
  43. int rc;
  44. if (is_root)
  45. rc = stat(full_path.characters(), &st);
  46. else
  47. rc = lstat(full_path.characters(), &st);
  48. if (rc < 0) {
  49. m_error = errno;
  50. perror("stat/lstat");
  51. return false;
  52. }
  53. size = st.st_size;
  54. mode = st.st_mode;
  55. uid = st.st_uid;
  56. gid = st.st_gid;
  57. inode = st.st_ino;
  58. mtime = st.st_mtime;
  59. if (S_ISLNK(mode)) {
  60. auto sym_link_target_or_error = FileSystem::read_link(full_path);
  61. if (sym_link_target_or_error.is_error())
  62. perror("readlink");
  63. else {
  64. symlink_target = sym_link_target_or_error.release_value().to_deprecated_string();
  65. if (symlink_target.is_empty())
  66. perror("readlink");
  67. }
  68. }
  69. if (S_ISDIR(mode)) {
  70. is_accessible_directory = access(full_path.characters(), R_OK | X_OK) == 0;
  71. }
  72. return true;
  73. }
  74. void FileSystemModel::Node::traverse_if_needed()
  75. {
  76. if (!is_directory() || m_has_traversed)
  77. return;
  78. m_has_traversed = true;
  79. if (m_parent_of_root) {
  80. auto root = adopt_own(*new Node(m_model));
  81. root->fetch_data("/", true);
  82. root->name = "/";
  83. root->m_parent = this;
  84. m_children.append(move(root));
  85. return;
  86. }
  87. total_size = 0;
  88. auto full_path = this->full_path();
  89. Core::DirIterator di(full_path, m_model.should_show_dotfiles() ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  90. if (di.has_error()) {
  91. auto error = di.error();
  92. m_error = error.code();
  93. warnln("DirIterator: {}", error);
  94. return;
  95. }
  96. Vector<DeprecatedString> child_names;
  97. while (di.has_next()) {
  98. child_names.append(di.next_path());
  99. }
  100. quick_sort(child_names);
  101. Vector<NonnullOwnPtr<Node>> directory_children;
  102. Vector<NonnullOwnPtr<Node>> file_children;
  103. for (auto& child_name : child_names) {
  104. auto maybe_child = create_child(child_name);
  105. if (!maybe_child)
  106. continue;
  107. auto child = maybe_child.release_nonnull();
  108. total_size += child->size;
  109. if (S_ISDIR(child->mode)) {
  110. directory_children.append(move(child));
  111. } else {
  112. if (!m_model.m_allowed_file_extensions.has_value()) {
  113. file_children.append(move(child));
  114. continue;
  115. }
  116. for (auto& extension : *m_model.m_allowed_file_extensions) {
  117. if (child_name.ends_with(DeprecatedString::formatted(".{}", extension))) {
  118. file_children.append(move(child));
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. m_children.extend(move(directory_children));
  125. m_children.extend(move(file_children));
  126. if (!m_model.m_file_watcher->is_watching(full_path)) {
  127. // We are not already watching this file, watch it
  128. auto result = m_model.m_file_watcher->add_watch(full_path,
  129. Core::FileWatcherEvent::Type::MetadataModified
  130. | Core::FileWatcherEvent::Type::ChildCreated
  131. | Core::FileWatcherEvent::Type::ChildDeleted
  132. | Core::FileWatcherEvent::Type::Deleted);
  133. if (result.is_error()) {
  134. dbgln("Couldn't watch '{}': {}", full_path, result.error());
  135. } else if (result.value() == false) {
  136. dbgln("Couldn't watch '{}', probably already watching", full_path);
  137. }
  138. }
  139. }
  140. bool FileSystemModel::Node::can_delete_or_move() const
  141. {
  142. if (!m_can_delete_or_move.has_value())
  143. m_can_delete_or_move = FileSystem::can_delete_or_move(full_path());
  144. return m_can_delete_or_move.value();
  145. }
  146. OwnPtr<FileSystemModel::Node> FileSystemModel::Node::create_child(DeprecatedString const& child_name)
  147. {
  148. DeprecatedString child_path = LexicalPath::join(full_path(), child_name).string();
  149. auto child = adopt_own(*new Node(m_model));
  150. bool ok = child->fetch_data(child_path, false);
  151. if (!ok)
  152. return {};
  153. if (m_model.m_mode == DirectoriesOnly && !S_ISDIR(child->mode))
  154. return {};
  155. child->name = child_name;
  156. child->m_parent = this;
  157. return child;
  158. }
  159. void FileSystemModel::Node::reify_if_needed()
  160. {
  161. traverse_if_needed();
  162. if (mode != 0)
  163. return;
  164. fetch_data(full_path(), m_parent == nullptr || m_parent->m_parent_of_root);
  165. }
  166. bool FileSystemModel::Node::is_symlink_to_directory() const
  167. {
  168. if (!S_ISLNK(mode))
  169. return false;
  170. struct stat st;
  171. if (lstat(symlink_target.characters(), &st) < 0)
  172. return false;
  173. return S_ISDIR(st.st_mode);
  174. }
  175. DeprecatedString FileSystemModel::Node::full_path() const
  176. {
  177. Vector<DeprecatedString, 32> lineage;
  178. for (auto* ancestor = m_parent; ancestor; ancestor = ancestor->m_parent) {
  179. lineage.append(ancestor->name);
  180. }
  181. StringBuilder builder;
  182. builder.append(m_model.root_path());
  183. for (int i = lineage.size() - 1; i >= 0; --i) {
  184. builder.append('/');
  185. builder.append(lineage[i]);
  186. }
  187. builder.append('/');
  188. builder.append(name);
  189. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  190. }
  191. ModelIndex FileSystemModel::index(DeprecatedString path, int column) const
  192. {
  193. auto node = node_for_path(move(path));
  194. if (node.has_value())
  195. return node->index(column);
  196. return {};
  197. }
  198. Optional<FileSystemModel::Node const&> FileSystemModel::node_for_path(DeprecatedString const& path) const
  199. {
  200. DeprecatedString resolved_path;
  201. if (path == m_root_path)
  202. resolved_path = "/";
  203. else if (m_root_path.has_value() && !m_root_path->is_empty() && path.starts_with(*m_root_path))
  204. resolved_path = LexicalPath::relative_path(path, *m_root_path);
  205. else
  206. resolved_path = path;
  207. LexicalPath lexical_path(resolved_path);
  208. Node const* node = m_root->m_parent_of_root ? m_root->m_children.first() : m_root.ptr();
  209. if (lexical_path.string() == "/")
  210. return *node;
  211. auto& parts = lexical_path.parts_view();
  212. for (size_t i = 0; i < parts.size(); ++i) {
  213. auto& part = parts[i];
  214. bool found = false;
  215. for (auto& child : node->m_children) {
  216. if (child->name == part) {
  217. const_cast<Node&>(*child).reify_if_needed();
  218. node = child;
  219. found = true;
  220. if (i == parts.size() - 1)
  221. return *node;
  222. break;
  223. }
  224. }
  225. if (!found)
  226. return {};
  227. }
  228. return {};
  229. }
  230. DeprecatedString FileSystemModel::full_path(ModelIndex const& index) const
  231. {
  232. auto& node = this->node(index);
  233. const_cast<Node&>(node).reify_if_needed();
  234. return node.full_path();
  235. }
  236. FileSystemModel::FileSystemModel(Optional<DeprecatedString> root_path, Mode mode)
  237. : m_root_path(root_path.map(LexicalPath::canonicalized_path))
  238. , m_mode(mode)
  239. {
  240. setpwent();
  241. while (auto* passwd = getpwent())
  242. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  243. endpwent();
  244. setgrent();
  245. while (auto* group = getgrent())
  246. m_group_names.set(group->gr_gid, group->gr_name);
  247. endgrent();
  248. auto result = Core::FileWatcher::create();
  249. if (result.is_error()) {
  250. dbgln("{}", result.error());
  251. VERIFY_NOT_REACHED();
  252. }
  253. m_file_watcher = result.release_value();
  254. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  255. handle_file_event(event);
  256. };
  257. invalidate();
  258. }
  259. DeprecatedString FileSystemModel::name_for_uid(uid_t uid) const
  260. {
  261. auto it = m_user_names.find(uid);
  262. if (it == m_user_names.end())
  263. return DeprecatedString::number(uid);
  264. return (*it).value;
  265. }
  266. DeprecatedString FileSystemModel::name_for_gid(gid_t gid) const
  267. {
  268. auto it = m_group_names.find(gid);
  269. if (it == m_group_names.end())
  270. return DeprecatedString::number(gid);
  271. return (*it).value;
  272. }
  273. static DeprecatedString permission_string(mode_t mode)
  274. {
  275. StringBuilder builder;
  276. if (S_ISDIR(mode))
  277. builder.append('d');
  278. else if (S_ISLNK(mode))
  279. builder.append('l');
  280. else if (S_ISBLK(mode))
  281. builder.append('b');
  282. else if (S_ISCHR(mode))
  283. builder.append('c');
  284. else if (S_ISFIFO(mode))
  285. builder.append('f');
  286. else if (S_ISSOCK(mode))
  287. builder.append('s');
  288. else if (S_ISREG(mode))
  289. builder.append('-');
  290. else
  291. builder.append('?');
  292. builder.append(mode & S_IRUSR ? 'r' : '-');
  293. builder.append(mode & S_IWUSR ? 'w' : '-');
  294. builder.append(mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'));
  295. builder.append(mode & S_IRGRP ? 'r' : '-');
  296. builder.append(mode & S_IWGRP ? 'w' : '-');
  297. builder.append(mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'));
  298. builder.append(mode & S_IROTH ? 'r' : '-');
  299. builder.append(mode & S_IWOTH ? 'w' : '-');
  300. if (mode & S_ISVTX)
  301. builder.append('t');
  302. else
  303. builder.append(mode & S_IXOTH ? 'x' : '-');
  304. return builder.to_deprecated_string();
  305. }
  306. void FileSystemModel::Node::set_selected(bool selected)
  307. {
  308. if (m_selected == selected)
  309. return;
  310. m_selected = selected;
  311. }
  312. void FileSystemModel::update_node_on_selection(ModelIndex const& index, bool const selected)
  313. {
  314. Node& node = const_cast<Node&>(this->node(index));
  315. node.set_selected(selected);
  316. }
  317. void FileSystemModel::set_root_path(Optional<DeprecatedString> root_path)
  318. {
  319. if (!root_path.has_value())
  320. m_root_path = {};
  321. else
  322. m_root_path = LexicalPath::canonicalized_path(move(*root_path));
  323. invalidate();
  324. if (m_root->has_error()) {
  325. if (on_directory_change_error)
  326. on_directory_change_error(m_root->error(), m_root->error_string());
  327. } else if (on_complete) {
  328. on_complete();
  329. }
  330. }
  331. void FileSystemModel::invalidate()
  332. {
  333. m_root = adopt_own(*new Node(*this));
  334. if (!m_root_path.has_value())
  335. m_root->m_parent_of_root = true;
  336. m_root->reify_if_needed();
  337. Model::invalidate();
  338. }
  339. void FileSystemModel::handle_file_event(Core::FileWatcherEvent const& event)
  340. {
  341. if (event.type == Core::FileWatcherEvent::Type::ChildCreated) {
  342. if (node_for_path(event.event_path).has_value())
  343. return;
  344. } else {
  345. if (!node_for_path(event.event_path).has_value())
  346. return;
  347. }
  348. switch (event.type) {
  349. case Core::FileWatcherEvent::Type::ChildCreated: {
  350. LexicalPath path { event.event_path };
  351. auto& parts = path.parts_view();
  352. StringView child_name = parts.last();
  353. if (!m_should_show_dotfiles && child_name.starts_with('.'))
  354. break;
  355. auto parent_name = path.parent().string();
  356. auto parent = node_for_path(parent_name);
  357. if (!parent.has_value()) {
  358. dbgln("Got a ChildCreated on '{}' but that path does not exist?!", parent_name);
  359. break;
  360. }
  361. auto& mutable_parent = const_cast<Node&>(*parent);
  362. auto maybe_child = mutable_parent.create_child(child_name);
  363. if (!maybe_child)
  364. break;
  365. auto child = maybe_child.release_nonnull();
  366. bool const is_new_child_dir = S_ISDIR(child->mode);
  367. int insert_index = 0;
  368. for (auto const& other_child : mutable_parent.m_children) {
  369. bool const is_other_child_dir = S_ISDIR(other_child->mode);
  370. if (!is_new_child_dir && is_other_child_dir) {
  371. ++insert_index;
  372. continue;
  373. }
  374. if (is_new_child_dir && !is_other_child_dir)
  375. break;
  376. if (other_child->name.view() > child_name)
  377. break;
  378. ++insert_index;
  379. }
  380. begin_insert_rows(parent->index(0), insert_index, insert_index);
  381. mutable_parent.total_size += child->size;
  382. mutable_parent.m_children.insert(insert_index, move(child));
  383. end_insert_rows();
  384. break;
  385. }
  386. case Core::FileWatcherEvent::Type::Deleted:
  387. case Core::FileWatcherEvent::Type::ChildDeleted: {
  388. auto child = node_for_path(event.event_path);
  389. if (!child.has_value()) {
  390. dbgln("Got a ChildDeleted/Deleted on '{}' but the child does not exist?! (already gone?)", event.event_path);
  391. break;
  392. }
  393. if (&child.value() == m_root) {
  394. // Root directory of the filesystem model has been removed. All items became invalid.
  395. invalidate();
  396. on_root_path_removed();
  397. break;
  398. }
  399. auto index = child->index(0);
  400. begin_delete_rows(index.parent(), index.row(), index.row());
  401. Node* parent = child->m_parent;
  402. parent->m_children.remove(index.row());
  403. end_delete_rows();
  404. for_each_view([&](AbstractView& view) {
  405. view.selection().remove_all_matching([&](auto& selection_index) {
  406. return selection_index.internal_data() == index.internal_data();
  407. });
  408. if (view.cursor_index().internal_data() == index.internal_data()) {
  409. view.set_cursor({}, GUI::AbstractView::SelectionUpdate::None);
  410. }
  411. });
  412. break;
  413. }
  414. case Core::FileWatcherEvent::Type::MetadataModified: {
  415. // FIXME: Do we do anything in case the metadata is modified?
  416. // Perhaps re-stat'ing the modified node would make sense
  417. // here, but let's leave that to when we actually need it.
  418. break;
  419. }
  420. default:
  421. VERIFY_NOT_REACHED();
  422. }
  423. did_update(UpdateFlag::DontInvalidateIndices);
  424. }
  425. int FileSystemModel::row_count(ModelIndex const& index) const
  426. {
  427. Node& node = const_cast<Node&>(this->node(index));
  428. node.reify_if_needed();
  429. if (node.is_directory())
  430. return node.m_children.size();
  431. return 0;
  432. }
  433. FileSystemModel::Node const& FileSystemModel::node(ModelIndex const& index) const
  434. {
  435. if (!index.is_valid())
  436. return *m_root;
  437. VERIFY(index.internal_data());
  438. return *(Node*)index.internal_data();
  439. }
  440. ModelIndex FileSystemModel::index(int row, int column, ModelIndex const& parent) const
  441. {
  442. if (row < 0 || column < 0)
  443. return {};
  444. auto& node = this->node(parent);
  445. const_cast<Node&>(node).reify_if_needed();
  446. if (static_cast<size_t>(row) >= node.m_children.size())
  447. return {};
  448. return create_index(row, column, node.m_children[row].ptr());
  449. }
  450. ModelIndex FileSystemModel::parent_index(ModelIndex const& index) const
  451. {
  452. if (!index.is_valid())
  453. return {};
  454. auto& node = this->node(index);
  455. if (!node.m_parent) {
  456. VERIFY(&node == m_root);
  457. return {};
  458. }
  459. return node.m_parent->index(index.column());
  460. }
  461. Variant FileSystemModel::data(ModelIndex const& index, ModelRole role) const
  462. {
  463. VERIFY(index.is_valid());
  464. if (role == ModelRole::TextAlignment) {
  465. switch (index.column()) {
  466. case Column::Icon:
  467. return Gfx::TextAlignment::Center;
  468. case Column::Size:
  469. case Column::Inode:
  470. return Gfx::TextAlignment::CenterRight;
  471. case Column::Name:
  472. case Column::User:
  473. case Column::Group:
  474. case Column::ModificationTime:
  475. case Column::Permissions:
  476. case Column::SymlinkTarget:
  477. return Gfx::TextAlignment::CenterLeft;
  478. default:
  479. VERIFY_NOT_REACHED();
  480. }
  481. }
  482. auto& node = this->node(index);
  483. if (role == ModelRole::Custom) {
  484. // For GUI::FileSystemModel, custom role means the full path.
  485. VERIFY(index.column() == Column::Name);
  486. return node.full_path();
  487. }
  488. if (role == ModelRole::MimeData) {
  489. if (index.column() == Column::Name)
  490. return URL::create_with_file_scheme(node.full_path()).serialize();
  491. return {};
  492. }
  493. if (role == ModelRole::Sort) {
  494. switch (index.column()) {
  495. case Column::Icon:
  496. return node.is_directory() ? 0 : 1;
  497. case Column::Name:
  498. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  499. // Hence, the sort value for the name column is simply the index row. :^)
  500. return index.row();
  501. case Column::Size:
  502. return (int)node.size;
  503. case Column::User:
  504. return name_for_uid(node.uid);
  505. case Column::Group:
  506. return name_for_gid(node.gid);
  507. case Column::Permissions:
  508. return permission_string(node.mode);
  509. case Column::ModificationTime:
  510. return node.mtime;
  511. case Column::Inode:
  512. return (int)node.inode;
  513. case Column::SymlinkTarget:
  514. return node.symlink_target;
  515. }
  516. VERIFY_NOT_REACHED();
  517. }
  518. if (role == ModelRole::Display) {
  519. switch (index.column()) {
  520. case Column::Icon:
  521. return icon_for(node);
  522. case Column::Name:
  523. return node.name;
  524. case Column::Size:
  525. return human_readable_size(node.size);
  526. case Column::User:
  527. return name_for_uid(node.uid);
  528. case Column::Group:
  529. return name_for_gid(node.gid);
  530. case Column::Permissions:
  531. return permission_string(node.mode);
  532. case Column::ModificationTime:
  533. return timestamp_string(node.mtime);
  534. case Column::Inode:
  535. return (int)node.inode;
  536. case Column::SymlinkTarget:
  537. return node.symlink_target;
  538. }
  539. }
  540. if (role == ModelRole::Icon) {
  541. return icon_for(node);
  542. }
  543. if (role == ModelRole::IconOpacity) {
  544. if (node.name.starts_with('.'))
  545. return 0.5f;
  546. return {};
  547. }
  548. return {};
  549. }
  550. Icon FileSystemModel::icon_for(Node const& node) const
  551. {
  552. if (node.full_path() == "/")
  553. return FileIconProvider::icon_for_path("/"sv);
  554. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  555. if (!node.thumbnail) {
  556. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  557. return FileIconProvider::filetype_image_icon();
  558. }
  559. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  560. }
  561. if (node.is_directory()) {
  562. if (node.full_path() == Core::StandardPaths::home_directory()) {
  563. if (node.is_selected())
  564. return FileIconProvider::home_directory_open_icon();
  565. return FileIconProvider::home_directory_icon();
  566. }
  567. if (node.full_path().ends_with(".git"sv)) {
  568. if (node.is_selected())
  569. return FileIconProvider::git_directory_open_icon();
  570. return FileIconProvider::git_directory_icon();
  571. }
  572. if (node.full_path() == Core::StandardPaths::desktop_directory())
  573. return FileIconProvider::desktop_directory_icon();
  574. if (node.is_selected() && node.is_accessible_directory)
  575. return FileIconProvider::directory_open_icon();
  576. }
  577. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  578. }
  579. using BitmapBackgroundAction = Threading::BackgroundAction<NonnullRefPtr<Gfx::Bitmap>>;
  580. // Mutex protected thumbnail cache data shared between threads.
  581. struct ThumbnailCache {
  582. // Null pointers indicate an image that couldn't be loaded due to errors.
  583. HashMap<DeprecatedString, RefPtr<Gfx::Bitmap>> thumbnail_cache {};
  584. HashMap<DeprecatedString, NonnullRefPtr<BitmapBackgroundAction>> loading_thumbnails {};
  585. };
  586. static Threading::MutexProtected<ThumbnailCache> s_thumbnail_cache {};
  587. static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> render_thumbnail(StringView path)
  588. {
  589. Gfx::IntSize thumbnail_size { 32, 32 };
  590. auto bitmap = TRY(Gfx::Bitmap::load_from_file(path, 1, thumbnail_size));
  591. auto thumbnail = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, thumbnail_size));
  592. double scale = min(thumbnail_size.width() / (double)bitmap->width(), thumbnail_size.height() / (double)bitmap->height());
  593. auto destination = Gfx::IntRect(0, 0, (int)(bitmap->width() * scale), (int)(bitmap->height() * scale)).centered_within(thumbnail->rect());
  594. Painter painter(thumbnail);
  595. painter.draw_scaled_bitmap(destination, *bitmap, bitmap->rect());
  596. return thumbnail;
  597. }
  598. bool FileSystemModel::fetch_thumbnail_for(Node const& node)
  599. {
  600. auto path = node.full_path();
  601. // See if we already have the thumbnail we're looking for in the cache.
  602. auto was_in_cache = s_thumbnail_cache.with_locked([&](auto& cache) {
  603. auto it = cache.thumbnail_cache.find(path);
  604. if (it != cache.thumbnail_cache.end()) {
  605. // Loading was unsuccessful.
  606. if (!(*it).value)
  607. return TriState::False;
  608. // Loading was successful.
  609. node.thumbnail = (*it).value;
  610. return TriState::True;
  611. }
  612. // Loading is in progress.
  613. if (cache.loading_thumbnails.contains(path))
  614. return TriState::False;
  615. return TriState::Unknown;
  616. });
  617. if (was_in_cache != TriState::Unknown)
  618. return was_in_cache == TriState::True;
  619. // Otherwise, arrange to render the thumbnail in background and make it available later.
  620. m_thumbnail_progress_total++;
  621. auto weak_this = make_weak_ptr();
  622. auto const action = [path](auto&) {
  623. return render_thumbnail(path);
  624. };
  625. auto const update_progress = [weak_this](bool with_success) {
  626. using namespace AK::TimeLiterals;
  627. if (auto strong_this = weak_this.strong_ref(); !strong_this.is_null()) {
  628. strong_this->m_thumbnail_progress++;
  629. if (strong_this->on_thumbnail_progress)
  630. strong_this->on_thumbnail_progress(strong_this->m_thumbnail_progress, strong_this->m_thumbnail_progress_total);
  631. if (strong_this->m_thumbnail_progress == strong_this->m_thumbnail_progress_total) {
  632. strong_this->m_thumbnail_progress = 0;
  633. strong_this->m_thumbnail_progress_total = 0;
  634. }
  635. if (with_success && (!strong_this->m_ui_update_timer.is_valid() || strong_this->m_ui_update_timer.elapsed_time() > 100_ms)) {
  636. strong_this->did_update(UpdateFlag::DontInvalidateIndices);
  637. strong_this->m_ui_update_timer.start();
  638. }
  639. }
  640. };
  641. auto const on_complete = [weak_this, path, update_progress](auto thumbnail) -> ErrorOr<void> {
  642. auto finished_generating_thumbnails = false;
  643. s_thumbnail_cache.with_locked([path, thumbnail, &finished_generating_thumbnails](auto& cache) {
  644. cache.thumbnail_cache.set(path, thumbnail);
  645. cache.loading_thumbnails.remove(path);
  646. finished_generating_thumbnails = cache.loading_thumbnails.is_empty();
  647. });
  648. if (auto strong_this = weak_this.strong_ref(); finished_generating_thumbnails && !strong_this.is_null())
  649. strong_this->m_ui_update_timer.reset();
  650. update_progress(true);
  651. return {};
  652. };
  653. auto const on_error = [path, update_progress](Error error) -> void {
  654. // Note: We need to defer that to avoid the function removing its last reference
  655. // i.e. trying to destroy itself, which is prohibited.
  656. Core::EventLoop::current().deferred_invoke([path, error = Error::copy(error)]() mutable {
  657. s_thumbnail_cache.with_locked([path, error = move(error)](auto& cache) {
  658. if (error != Error::from_errno(ECANCELED)) {
  659. cache.thumbnail_cache.set(path, nullptr);
  660. dbgln("Failed to load thumbnail for {}: {}", path, error);
  661. }
  662. cache.loading_thumbnails.remove(path);
  663. });
  664. });
  665. update_progress(false);
  666. };
  667. s_thumbnail_cache.with_locked([path, action, on_complete, on_error](auto& cache) {
  668. cache.loading_thumbnails.set(path, BitmapBackgroundAction::construct(move(action), move(on_complete), move(on_error)));
  669. });
  670. return false;
  671. }
  672. int FileSystemModel::column_count(ModelIndex const&) const
  673. {
  674. return Column::__Count;
  675. }
  676. ErrorOr<String> FileSystemModel::column_name(int column) const
  677. {
  678. switch (column) {
  679. case Column::Icon:
  680. return String {};
  681. case Column::Name:
  682. return "Name"_string;
  683. case Column::Size:
  684. return "Size"_string;
  685. case Column::User:
  686. return "User"_string;
  687. case Column::Group:
  688. return "Group"_string;
  689. case Column::Permissions:
  690. return "Mode"_string;
  691. case Column::ModificationTime:
  692. return "Modified"_string;
  693. case Column::Inode:
  694. return "Inode"_string;
  695. case Column::SymlinkTarget:
  696. return "Symlink target"_string;
  697. }
  698. VERIFY_NOT_REACHED();
  699. }
  700. bool FileSystemModel::accepts_drag(ModelIndex const& index, Vector<String> const& mime_types) const
  701. {
  702. if (!mime_types.contains_slow("text/uri-list"sv))
  703. return false;
  704. if (!index.is_valid())
  705. return true;
  706. auto& node = this->node(index);
  707. return node.is_directory();
  708. }
  709. void FileSystemModel::set_should_show_dotfiles(bool show)
  710. {
  711. if (m_should_show_dotfiles == show)
  712. return;
  713. m_should_show_dotfiles = show;
  714. // FIXME: add a way to granularly update in this case.
  715. invalidate();
  716. }
  717. void FileSystemModel::set_allowed_file_extensions(Optional<Vector<DeprecatedString>> const& allowed_file_extensions)
  718. {
  719. if (m_allowed_file_extensions == allowed_file_extensions)
  720. return;
  721. m_allowed_file_extensions = allowed_file_extensions;
  722. invalidate();
  723. }
  724. bool FileSystemModel::is_editable(ModelIndex const& index) const
  725. {
  726. if (!index.is_valid())
  727. return false;
  728. return index.column() == Column::Name;
  729. }
  730. void FileSystemModel::set_data(ModelIndex const& index, Variant const& data)
  731. {
  732. VERIFY(is_editable(index));
  733. Node& node = const_cast<Node&>(this->node(index));
  734. auto dirname = LexicalPath::dirname(node.full_path());
  735. auto new_full_path = DeprecatedString::formatted("{}/{}", dirname, data.to_deprecated_string());
  736. int rc = rename(node.full_path().characters(), new_full_path.characters());
  737. if (rc < 0) {
  738. if (on_rename_error)
  739. on_rename_error(errno, strerror(errno));
  740. return;
  741. }
  742. if (on_rename_successful)
  743. on_rename_successful(node.full_path(), new_full_path);
  744. }
  745. Vector<ModelIndex> FileSystemModel::matches(StringView searching, unsigned flags, ModelIndex const& index)
  746. {
  747. Node& node = const_cast<Node&>(this->node(index));
  748. node.reify_if_needed();
  749. Vector<ModelIndex> found_indices;
  750. for (auto& child : node.m_children) {
  751. if (string_matches(child->name, searching, flags)) {
  752. const_cast<Node&>(*child).reify_if_needed();
  753. found_indices.append(child->index(Column::Name));
  754. if (flags & FirstMatchOnly)
  755. break;
  756. }
  757. }
  758. return found_indices;
  759. }
  760. }