FileSystemModel.cpp 24 KB

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