FileSystemModel.cpp 28 KB

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