FileSystemModel.cpp 23 KB

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