FileSystemModel.cpp 28 KB

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