FileSystemModel.cpp 24 KB

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