FileSystemModel.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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. auto parent_name = path.parent().string();
  335. auto parent = node_for_path(parent_name);
  336. if (!parent.has_value()) {
  337. dbgln("Got a ChildCreated on '{}' but that path does not exist?!", parent_name);
  338. break;
  339. }
  340. int child_count = parent->m_children.size();
  341. auto& mutable_parent = const_cast<Node&>(*parent);
  342. auto maybe_child = mutable_parent.create_child(child_name);
  343. if (!maybe_child)
  344. break;
  345. begin_insert_rows(parent->index(0), child_count, child_count);
  346. auto child = maybe_child.release_nonnull();
  347. mutable_parent.total_size += child->size;
  348. mutable_parent.m_children.append(move(child));
  349. end_insert_rows();
  350. break;
  351. }
  352. case Core::FileWatcherEvent::Type::Deleted:
  353. case Core::FileWatcherEvent::Type::ChildDeleted: {
  354. auto child = node_for_path(event.event_path);
  355. if (!child.has_value()) {
  356. dbgln("Got a ChildDeleted/Deleted on '{}' but the child does not exist?! (already gone?)", event.event_path);
  357. break;
  358. }
  359. auto index = child->index(0);
  360. begin_delete_rows(index.parent(), index.row(), index.row());
  361. Node* parent = child->m_parent;
  362. parent->m_children.remove(index.row());
  363. end_delete_rows();
  364. for_each_view([&](AbstractView& view) {
  365. view.selection().remove_all_matching([&](auto& selection_index) {
  366. return selection_index.internal_data() == index.internal_data();
  367. });
  368. if (view.cursor_index().internal_data() == index.internal_data()) {
  369. view.set_cursor({}, GUI::AbstractView::SelectionUpdate::None);
  370. }
  371. });
  372. break;
  373. }
  374. case Core::FileWatcherEvent::Type::MetadataModified: {
  375. // FIXME: Do we do anything in case the metadata is modified?
  376. // Perhaps re-stat'ing the modified node would make sense
  377. // here, but let's leave that to when we actually need it.
  378. break;
  379. }
  380. default:
  381. VERIFY_NOT_REACHED();
  382. }
  383. did_update(UpdateFlag::DontInvalidateIndices);
  384. }
  385. int FileSystemModel::row_count(ModelIndex const& index) const
  386. {
  387. Node& node = const_cast<Node&>(this->node(index));
  388. node.reify_if_needed();
  389. if (node.is_directory())
  390. return node.m_children.size();
  391. return 0;
  392. }
  393. FileSystemModel::Node const& FileSystemModel::node(ModelIndex const& index) const
  394. {
  395. if (!index.is_valid())
  396. return *m_root;
  397. VERIFY(index.internal_data());
  398. return *(Node*)index.internal_data();
  399. }
  400. ModelIndex FileSystemModel::index(int row, int column, ModelIndex const& parent) const
  401. {
  402. if (row < 0 || column < 0)
  403. return {};
  404. auto& node = this->node(parent);
  405. const_cast<Node&>(node).reify_if_needed();
  406. if (static_cast<size_t>(row) >= node.m_children.size())
  407. return {};
  408. return create_index(row, column, &node.m_children[row]);
  409. }
  410. ModelIndex FileSystemModel::parent_index(ModelIndex const& index) const
  411. {
  412. if (!index.is_valid())
  413. return {};
  414. auto& node = this->node(index);
  415. if (!node.m_parent) {
  416. VERIFY(&node == m_root);
  417. return {};
  418. }
  419. return node.m_parent->index(index.column());
  420. }
  421. Variant FileSystemModel::data(ModelIndex const& index, ModelRole role) const
  422. {
  423. VERIFY(index.is_valid());
  424. if (role == ModelRole::TextAlignment) {
  425. switch (index.column()) {
  426. case Column::Icon:
  427. return Gfx::TextAlignment::Center;
  428. case Column::Size:
  429. case Column::Inode:
  430. return Gfx::TextAlignment::CenterRight;
  431. case Column::Name:
  432. case Column::User:
  433. case Column::Group:
  434. case Column::ModificationTime:
  435. case Column::Permissions:
  436. case Column::SymlinkTarget:
  437. return Gfx::TextAlignment::CenterLeft;
  438. default:
  439. VERIFY_NOT_REACHED();
  440. }
  441. }
  442. auto& node = this->node(index);
  443. if (role == ModelRole::Custom) {
  444. // For GUI::FileSystemModel, custom role means the full path.
  445. VERIFY(index.column() == Column::Name);
  446. return node.full_path();
  447. }
  448. if (role == ModelRole::MimeData) {
  449. if (index.column() == Column::Name)
  450. return URL::create_with_file_scheme(node.full_path()).serialize();
  451. return {};
  452. }
  453. if (role == ModelRole::Sort) {
  454. switch (index.column()) {
  455. case Column::Icon:
  456. return node.is_directory() ? 0 : 1;
  457. case Column::Name:
  458. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  459. // Hence, the sort value for the name column is simply the index row. :^)
  460. return index.row();
  461. case Column::Size:
  462. return (int)node.size;
  463. case Column::User:
  464. return name_for_uid(node.uid);
  465. case Column::Group:
  466. return name_for_gid(node.gid);
  467. case Column::Permissions:
  468. return permission_string(node.mode);
  469. case Column::ModificationTime:
  470. return node.mtime;
  471. case Column::Inode:
  472. return (int)node.inode;
  473. case Column::SymlinkTarget:
  474. return node.symlink_target;
  475. }
  476. VERIFY_NOT_REACHED();
  477. }
  478. if (role == ModelRole::Display) {
  479. switch (index.column()) {
  480. case Column::Icon:
  481. return icon_for(node);
  482. case Column::Name:
  483. return node.name;
  484. case Column::Size:
  485. return human_readable_size(node.size);
  486. case Column::User:
  487. return name_for_uid(node.uid);
  488. case Column::Group:
  489. return name_for_gid(node.gid);
  490. case Column::Permissions:
  491. return permission_string(node.mode);
  492. case Column::ModificationTime:
  493. return timestamp_string(node.mtime);
  494. case Column::Inode:
  495. return (int)node.inode;
  496. case Column::SymlinkTarget:
  497. return node.symlink_target;
  498. }
  499. }
  500. if (role == ModelRole::Icon) {
  501. return icon_for(node);
  502. }
  503. if (role == ModelRole::IconOpacity) {
  504. if (node.name.starts_with('.'))
  505. return 0.5f;
  506. return {};
  507. }
  508. return {};
  509. }
  510. Icon FileSystemModel::icon_for(Node const& node) const
  511. {
  512. if (node.full_path() == "/")
  513. return FileIconProvider::icon_for_path("/");
  514. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  515. if (!node.thumbnail) {
  516. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  517. return FileIconProvider::filetype_image_icon();
  518. }
  519. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  520. }
  521. if (node.is_directory()) {
  522. if (node.full_path() == Core::StandardPaths::home_directory()) {
  523. if (node.is_selected())
  524. return FileIconProvider::home_directory_open_icon();
  525. return FileIconProvider::home_directory_icon();
  526. }
  527. if (node.full_path() == Core::StandardPaths::desktop_directory())
  528. return FileIconProvider::desktop_directory_icon();
  529. if (node.is_selected() && node.is_accessible_directory)
  530. return FileIconProvider::directory_open_icon();
  531. }
  532. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  533. }
  534. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  535. static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> render_thumbnail(StringView path)
  536. {
  537. auto bitmap = TRY(Gfx::Bitmap::try_load_from_file(path));
  538. auto thumbnail = TRY(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, { 32, 32 }));
  539. double scale = min(32 / (double)bitmap->width(), 32 / (double)bitmap->height());
  540. auto destination = Gfx::IntRect(0, 0, (int)(bitmap->width() * scale), (int)(bitmap->height() * scale)).centered_within(thumbnail->rect());
  541. Painter painter(thumbnail);
  542. painter.draw_scaled_bitmap(destination, *bitmap, bitmap->rect());
  543. return thumbnail;
  544. }
  545. bool FileSystemModel::fetch_thumbnail_for(Node const& node)
  546. {
  547. // See if we already have the thumbnail
  548. // we're looking for in the cache.
  549. auto path = node.full_path();
  550. auto it = s_thumbnail_cache.find(path);
  551. if (it != s_thumbnail_cache.end()) {
  552. if (!(*it).value)
  553. return false;
  554. node.thumbnail = (*it).value;
  555. return true;
  556. }
  557. // Otherwise, arrange to render the thumbnail
  558. // in background and make it available later.
  559. s_thumbnail_cache.set(path, nullptr);
  560. m_thumbnail_progress_total++;
  561. auto weak_this = make_weak_ptr();
  562. (void)Threading::BackgroundAction<ErrorOr<NonnullRefPtr<Gfx::Bitmap>>>::construct(
  563. [path](auto&) {
  564. return render_thumbnail(path);
  565. },
  566. [this, path, weak_this](auto thumbnail_or_error) {
  567. if (thumbnail_or_error.is_error()) {
  568. s_thumbnail_cache.set(path, nullptr);
  569. dbgln("Failed to load thumbnail for {}: {}", path, thumbnail_or_error.error());
  570. } else {
  571. s_thumbnail_cache.set(path, thumbnail_or_error.release_value());
  572. }
  573. // The model was destroyed, no need to update
  574. // progress or call any event handlers.
  575. if (weak_this.is_null())
  576. return;
  577. m_thumbnail_progress++;
  578. if (on_thumbnail_progress)
  579. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  580. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  581. m_thumbnail_progress = 0;
  582. m_thumbnail_progress_total = 0;
  583. }
  584. did_update(UpdateFlag::DontInvalidateIndices);
  585. });
  586. return false;
  587. }
  588. int FileSystemModel::column_count(ModelIndex const&) const
  589. {
  590. return Column::__Count;
  591. }
  592. String FileSystemModel::column_name(int column) const
  593. {
  594. switch (column) {
  595. case Column::Icon:
  596. return "";
  597. case Column::Name:
  598. return "Name";
  599. case Column::Size:
  600. return "Size";
  601. case Column::User:
  602. return "User";
  603. case Column::Group:
  604. return "Group";
  605. case Column::Permissions:
  606. return "Mode";
  607. case Column::ModificationTime:
  608. return "Modified";
  609. case Column::Inode:
  610. return "Inode";
  611. case Column::SymlinkTarget:
  612. return "Symlink target";
  613. }
  614. VERIFY_NOT_REACHED();
  615. }
  616. bool FileSystemModel::accepts_drag(ModelIndex const& index, Vector<String> const& mime_types) const
  617. {
  618. if (!mime_types.contains_slow("text/uri-list"))
  619. return false;
  620. if (!index.is_valid())
  621. return true;
  622. auto& node = this->node(index);
  623. return node.is_directory();
  624. }
  625. void FileSystemModel::set_should_show_dotfiles(bool show)
  626. {
  627. if (m_should_show_dotfiles == show)
  628. return;
  629. m_should_show_dotfiles = show;
  630. // FIXME: add a way to granularly update in this case.
  631. invalidate();
  632. }
  633. bool FileSystemModel::is_editable(ModelIndex const& index) const
  634. {
  635. if (!index.is_valid())
  636. return false;
  637. return index.column() == Column::Name;
  638. }
  639. void FileSystemModel::set_data(ModelIndex const& index, Variant const& data)
  640. {
  641. VERIFY(is_editable(index));
  642. Node& node = const_cast<Node&>(this->node(index));
  643. auto dirname = LexicalPath::dirname(node.full_path());
  644. auto new_full_path = String::formatted("{}/{}", dirname, data.to_string());
  645. int rc = rename(node.full_path().characters(), new_full_path.characters());
  646. if (rc < 0) {
  647. if (on_rename_error)
  648. on_rename_error(errno, strerror(errno));
  649. return;
  650. }
  651. if (on_rename_successful)
  652. on_rename_successful(node.full_path(), new_full_path);
  653. }
  654. Vector<ModelIndex> FileSystemModel::matches(StringView searching, unsigned flags, ModelIndex const& index)
  655. {
  656. Node& node = const_cast<Node&>(this->node(index));
  657. node.reify_if_needed();
  658. Vector<ModelIndex> found_indices;
  659. for (auto& child : node.m_children) {
  660. if (string_matches(child.name, searching, flags)) {
  661. const_cast<Node&>(child).reify_if_needed();
  662. found_indices.append(child.index(Column::Name));
  663. if (flags & FirstMatchOnly)
  664. break;
  665. }
  666. }
  667. return found_indices;
  668. }
  669. }