FileSystemModel.cpp 26 KB

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