FileSystemModel.cpp 22 KB

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