FileSystemModel.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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.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(DeprecatedString root_path, Mode mode)
  237. : m_root_path(LexicalPath::canonicalized_path(move(root_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(DeprecatedString root_path)
  318. {
  319. if (root_path.is_empty())
  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.is_empty())
  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. int child_count = parent->m_children.size();
  362. auto& mutable_parent = const_cast<Node&>(*parent);
  363. auto maybe_child = mutable_parent.create_child(child_name);
  364. if (!maybe_child)
  365. break;
  366. begin_insert_rows(parent->index(0), child_count, child_count);
  367. auto child = maybe_child.release_nonnull();
  368. mutable_parent.total_size += child->size;
  369. mutable_parent.m_children.append(move(child));
  370. end_insert_rows();
  371. break;
  372. }
  373. case Core::FileWatcherEvent::Type::Deleted:
  374. case Core::FileWatcherEvent::Type::ChildDeleted: {
  375. auto child = node_for_path(event.event_path);
  376. if (!child.has_value()) {
  377. dbgln("Got a ChildDeleted/Deleted on '{}' but the child does not exist?! (already gone?)", event.event_path);
  378. break;
  379. }
  380. if (&child.value() == m_root) {
  381. // Root directory of the filesystem model has been removed. All items became invalid.
  382. invalidate();
  383. on_root_path_removed();
  384. break;
  385. }
  386. auto index = child->index(0);
  387. begin_delete_rows(index.parent(), index.row(), index.row());
  388. Node* parent = child->m_parent;
  389. parent->m_children.remove(index.row());
  390. end_delete_rows();
  391. for_each_view([&](AbstractView& view) {
  392. view.selection().remove_all_matching([&](auto& selection_index) {
  393. return selection_index.internal_data() == index.internal_data();
  394. });
  395. if (view.cursor_index().internal_data() == index.internal_data()) {
  396. view.set_cursor({}, GUI::AbstractView::SelectionUpdate::None);
  397. }
  398. });
  399. break;
  400. }
  401. case Core::FileWatcherEvent::Type::MetadataModified: {
  402. // FIXME: Do we do anything in case the metadata is modified?
  403. // Perhaps re-stat'ing the modified node would make sense
  404. // here, but let's leave that to when we actually need it.
  405. break;
  406. }
  407. default:
  408. VERIFY_NOT_REACHED();
  409. }
  410. did_update(UpdateFlag::DontInvalidateIndices);
  411. }
  412. int FileSystemModel::row_count(ModelIndex const& index) const
  413. {
  414. Node& node = const_cast<Node&>(this->node(index));
  415. node.reify_if_needed();
  416. if (node.is_directory())
  417. return node.m_children.size();
  418. return 0;
  419. }
  420. FileSystemModel::Node const& FileSystemModel::node(ModelIndex const& index) const
  421. {
  422. if (!index.is_valid())
  423. return *m_root;
  424. VERIFY(index.internal_data());
  425. return *(Node*)index.internal_data();
  426. }
  427. ModelIndex FileSystemModel::index(int row, int column, ModelIndex const& parent) const
  428. {
  429. if (row < 0 || column < 0)
  430. return {};
  431. auto& node = this->node(parent);
  432. const_cast<Node&>(node).reify_if_needed();
  433. if (static_cast<size_t>(row) >= node.m_children.size())
  434. return {};
  435. return create_index(row, column, node.m_children[row].ptr());
  436. }
  437. ModelIndex FileSystemModel::parent_index(ModelIndex const& index) const
  438. {
  439. if (!index.is_valid())
  440. return {};
  441. auto& node = this->node(index);
  442. if (!node.m_parent) {
  443. VERIFY(&node == m_root);
  444. return {};
  445. }
  446. return node.m_parent->index(index.column());
  447. }
  448. Variant FileSystemModel::data(ModelIndex const& index, ModelRole role) const
  449. {
  450. VERIFY(index.is_valid());
  451. if (role == ModelRole::TextAlignment) {
  452. switch (index.column()) {
  453. case Column::Icon:
  454. return Gfx::TextAlignment::Center;
  455. case Column::Size:
  456. case Column::Inode:
  457. return Gfx::TextAlignment::CenterRight;
  458. case Column::Name:
  459. case Column::User:
  460. case Column::Group:
  461. case Column::ModificationTime:
  462. case Column::Permissions:
  463. case Column::SymlinkTarget:
  464. return Gfx::TextAlignment::CenterLeft;
  465. default:
  466. VERIFY_NOT_REACHED();
  467. }
  468. }
  469. auto& node = this->node(index);
  470. if (role == ModelRole::Custom) {
  471. // For GUI::FileSystemModel, custom role means the full path.
  472. VERIFY(index.column() == Column::Name);
  473. return node.full_path();
  474. }
  475. if (role == ModelRole::MimeData) {
  476. if (index.column() == Column::Name)
  477. return URL::create_with_file_scheme(node.full_path()).serialize();
  478. return {};
  479. }
  480. if (role == ModelRole::Sort) {
  481. switch (index.column()) {
  482. case Column::Icon:
  483. return node.is_directory() ? 0 : 1;
  484. case Column::Name:
  485. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  486. // Hence, the sort value for the name column is simply the index row. :^)
  487. return index.row();
  488. case Column::Size:
  489. return (int)node.size;
  490. case Column::User:
  491. return name_for_uid(node.uid);
  492. case Column::Group:
  493. return name_for_gid(node.gid);
  494. case Column::Permissions:
  495. return permission_string(node.mode);
  496. case Column::ModificationTime:
  497. return node.mtime;
  498. case Column::Inode:
  499. return (int)node.inode;
  500. case Column::SymlinkTarget:
  501. return node.symlink_target;
  502. }
  503. VERIFY_NOT_REACHED();
  504. }
  505. if (role == ModelRole::Display) {
  506. switch (index.column()) {
  507. case Column::Icon:
  508. return icon_for(node);
  509. case Column::Name:
  510. return node.name;
  511. case Column::Size:
  512. return human_readable_size(node.size);
  513. case Column::User:
  514. return name_for_uid(node.uid);
  515. case Column::Group:
  516. return name_for_gid(node.gid);
  517. case Column::Permissions:
  518. return permission_string(node.mode);
  519. case Column::ModificationTime:
  520. return timestamp_string(node.mtime);
  521. case Column::Inode:
  522. return (int)node.inode;
  523. case Column::SymlinkTarget:
  524. return node.symlink_target;
  525. }
  526. }
  527. if (role == ModelRole::Icon) {
  528. return icon_for(node);
  529. }
  530. if (role == ModelRole::IconOpacity) {
  531. if (node.name.starts_with('.'))
  532. return 0.5f;
  533. return {};
  534. }
  535. return {};
  536. }
  537. Icon FileSystemModel::icon_for(Node const& node) const
  538. {
  539. if (node.full_path() == "/")
  540. return FileIconProvider::icon_for_path("/"sv);
  541. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  542. if (!node.thumbnail) {
  543. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  544. return FileIconProvider::filetype_image_icon();
  545. }
  546. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  547. }
  548. if (node.is_directory()) {
  549. if (node.full_path() == Core::StandardPaths::home_directory()) {
  550. if (node.is_selected())
  551. return FileIconProvider::home_directory_open_icon();
  552. return FileIconProvider::home_directory_icon();
  553. }
  554. if (node.full_path().ends_with(".git"sv)) {
  555. if (node.is_selected())
  556. return FileIconProvider::git_directory_open_icon();
  557. return FileIconProvider::git_directory_icon();
  558. }
  559. if (node.full_path() == Core::StandardPaths::desktop_directory())
  560. return FileIconProvider::desktop_directory_icon();
  561. if (node.is_selected() && node.is_accessible_directory)
  562. return FileIconProvider::directory_open_icon();
  563. }
  564. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  565. }
  566. using BitmapBackgroundAction = Threading::BackgroundAction<NonnullRefPtr<Gfx::Bitmap>>;
  567. // Mutex protected thumbnail cache data shared between threads.
  568. struct ThumbnailCache {
  569. // Null pointers indicate an image that couldn't be loaded due to errors.
  570. HashMap<DeprecatedString, RefPtr<Gfx::Bitmap>> thumbnail_cache {};
  571. HashMap<DeprecatedString, NonnullRefPtr<BitmapBackgroundAction>> loading_thumbnails {};
  572. };
  573. static Threading::MutexProtected<ThumbnailCache> s_thumbnail_cache {};
  574. static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> render_thumbnail(StringView path)
  575. {
  576. Gfx::IntSize thumbnail_size { 32, 32 };
  577. auto bitmap = TRY(Gfx::Bitmap::load_from_file(path, 1, thumbnail_size));
  578. auto thumbnail = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, thumbnail_size));
  579. double scale = min(thumbnail_size.width() / (double)bitmap->width(), thumbnail_size.height() / (double)bitmap->height());
  580. auto destination = Gfx::IntRect(0, 0, (int)(bitmap->width() * scale), (int)(bitmap->height() * scale)).centered_within(thumbnail->rect());
  581. Painter painter(thumbnail);
  582. painter.draw_scaled_bitmap(destination, *bitmap, bitmap->rect());
  583. return thumbnail;
  584. }
  585. bool FileSystemModel::fetch_thumbnail_for(Node const& node)
  586. {
  587. auto path = node.full_path();
  588. // See if we already have the thumbnail we're looking for in the cache.
  589. auto was_in_cache = s_thumbnail_cache.with_locked([&](auto& cache) {
  590. auto it = cache.thumbnail_cache.find(path);
  591. if (it != cache.thumbnail_cache.end()) {
  592. // Loading was unsuccessful.
  593. if (!(*it).value)
  594. return TriState::False;
  595. // Loading was successful.
  596. node.thumbnail = (*it).value;
  597. return TriState::True;
  598. }
  599. // Loading is in progress.
  600. if (cache.loading_thumbnails.contains(path))
  601. return TriState::False;
  602. return TriState::Unknown;
  603. });
  604. if (was_in_cache != TriState::Unknown)
  605. return was_in_cache == TriState::True;
  606. // Otherwise, arrange to render the thumbnail in background and make it available later.
  607. m_thumbnail_progress_total++;
  608. auto weak_this = make_weak_ptr();
  609. auto const action = [path](auto&) {
  610. return render_thumbnail(path);
  611. };
  612. auto const update_progress = [weak_this](bool with_success) {
  613. using namespace AK::TimeLiterals;
  614. if (auto strong_this = weak_this.strong_ref(); !strong_this.is_null()) {
  615. strong_this->m_thumbnail_progress++;
  616. if (strong_this->on_thumbnail_progress)
  617. strong_this->on_thumbnail_progress(strong_this->m_thumbnail_progress, strong_this->m_thumbnail_progress_total);
  618. if (strong_this->m_thumbnail_progress == strong_this->m_thumbnail_progress_total) {
  619. strong_this->m_thumbnail_progress = 0;
  620. strong_this->m_thumbnail_progress_total = 0;
  621. }
  622. if (with_success && (!strong_this->m_ui_update_timer.is_valid() || strong_this->m_ui_update_timer.elapsed_time() > 100_ms)) {
  623. strong_this->did_update(UpdateFlag::DontInvalidateIndices);
  624. strong_this->m_ui_update_timer.start();
  625. }
  626. }
  627. };
  628. auto const on_complete = [weak_this, path, update_progress](auto thumbnail) -> ErrorOr<void> {
  629. auto finished_generating_thumbnails = false;
  630. s_thumbnail_cache.with_locked([path, thumbnail, &finished_generating_thumbnails](auto& cache) {
  631. cache.thumbnail_cache.set(path, thumbnail);
  632. cache.loading_thumbnails.remove(path);
  633. finished_generating_thumbnails = cache.loading_thumbnails.is_empty();
  634. });
  635. if (auto strong_this = weak_this.strong_ref(); finished_generating_thumbnails && !strong_this.is_null())
  636. strong_this->m_ui_update_timer.reset();
  637. update_progress(true);
  638. return {};
  639. };
  640. auto const on_error = [path, update_progress](Error error) -> void {
  641. // Note: We need to defer that to avoid the function removing its last reference
  642. // i.e. trying to destroy itself, which is prohibited.
  643. Core::EventLoop::current().deferred_invoke([path, error = Error::copy(error)]() mutable {
  644. s_thumbnail_cache.with_locked([path, error = move(error)](auto& cache) {
  645. if (error != Error::from_errno(ECANCELED)) {
  646. cache.thumbnail_cache.set(path, nullptr);
  647. dbgln("Failed to load thumbnail for {}: {}", path, error);
  648. }
  649. cache.loading_thumbnails.remove(path);
  650. });
  651. });
  652. update_progress(false);
  653. };
  654. s_thumbnail_cache.with_locked([path, action, on_complete, on_error](auto& cache) {
  655. cache.loading_thumbnails.set(path, BitmapBackgroundAction::construct(move(action), move(on_complete), move(on_error)));
  656. });
  657. return false;
  658. }
  659. int FileSystemModel::column_count(ModelIndex const&) const
  660. {
  661. return Column::__Count;
  662. }
  663. ErrorOr<String> FileSystemModel::column_name(int column) const
  664. {
  665. switch (column) {
  666. case Column::Icon:
  667. return String {};
  668. case Column::Name:
  669. return "Name"_string;
  670. case Column::Size:
  671. return "Size"_string;
  672. case Column::User:
  673. return "User"_string;
  674. case Column::Group:
  675. return "Group"_string;
  676. case Column::Permissions:
  677. return "Mode"_string;
  678. case Column::ModificationTime:
  679. return "Modified"_string;
  680. case Column::Inode:
  681. return "Inode"_string;
  682. case Column::SymlinkTarget:
  683. return "Symlink target"_string;
  684. }
  685. VERIFY_NOT_REACHED();
  686. }
  687. bool FileSystemModel::accepts_drag(ModelIndex const& index, Vector<String> const& mime_types) const
  688. {
  689. if (!mime_types.contains_slow("text/uri-list"sv))
  690. return false;
  691. if (!index.is_valid())
  692. return true;
  693. auto& node = this->node(index);
  694. return node.is_directory();
  695. }
  696. void FileSystemModel::set_should_show_dotfiles(bool show)
  697. {
  698. if (m_should_show_dotfiles == show)
  699. return;
  700. m_should_show_dotfiles = show;
  701. // FIXME: add a way to granularly update in this case.
  702. invalidate();
  703. }
  704. void FileSystemModel::set_allowed_file_extensions(Optional<Vector<DeprecatedString>> const& allowed_file_extensions)
  705. {
  706. if (m_allowed_file_extensions == allowed_file_extensions)
  707. return;
  708. m_allowed_file_extensions = allowed_file_extensions;
  709. invalidate();
  710. }
  711. bool FileSystemModel::is_editable(ModelIndex const& index) const
  712. {
  713. if (!index.is_valid())
  714. return false;
  715. return index.column() == Column::Name;
  716. }
  717. void FileSystemModel::set_data(ModelIndex const& index, Variant const& data)
  718. {
  719. VERIFY(is_editable(index));
  720. Node& node = const_cast<Node&>(this->node(index));
  721. auto dirname = LexicalPath::dirname(node.full_path());
  722. auto new_full_path = DeprecatedString::formatted("{}/{}", dirname, data.to_deprecated_string());
  723. int rc = rename(node.full_path().characters(), new_full_path.characters());
  724. if (rc < 0) {
  725. if (on_rename_error)
  726. on_rename_error(errno, strerror(errno));
  727. return;
  728. }
  729. if (on_rename_successful)
  730. on_rename_successful(node.full_path(), new_full_path);
  731. }
  732. Vector<ModelIndex> FileSystemModel::matches(StringView searching, unsigned flags, ModelIndex const& index)
  733. {
  734. Node& node = const_cast<Node&>(this->node(index));
  735. node.reify_if_needed();
  736. Vector<ModelIndex> found_indices;
  737. for (auto& child : node.m_children) {
  738. if (string_matches(child->name, searching, flags)) {
  739. const_cast<Node&>(*child).reify_if_needed();
  740. found_indices.append(child->index(Column::Name));
  741. if (flags & FirstMatchOnly)
  742. break;
  743. }
  744. }
  745. return found_indices;
  746. }
  747. }