FileSystemModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <AK/NumberFormat.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/DirIterator.h>
  11. #include <LibCore/File.h>
  12. #include <LibCore/StandardPaths.h>
  13. #include <LibGUI/FileIconProvider.h>
  14. #include <LibGUI/FileSystemModel.h>
  15. #include <LibGUI/Painter.h>
  16. #include <LibGfx/Bitmap.h>
  17. #include <LibThread/BackgroundAction.h>
  18. #include <grp.h>
  19. #include <pwd.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <sys/stat.h>
  23. #include <unistd.h>
  24. namespace GUI {
  25. ModelIndex FileSystemModel::Node::index(int column) const
  26. {
  27. if (!parent)
  28. return {};
  29. for (size_t row = 0; row < parent->children.size(); ++row) {
  30. if (&parent->children[row] == this)
  31. return m_model.create_index(row, column, const_cast<Node*>(this));
  32. }
  33. VERIFY_NOT_REACHED();
  34. }
  35. bool FileSystemModel::Node::fetch_data(const String& full_path, bool is_root)
  36. {
  37. struct stat st;
  38. int rc;
  39. if (is_root)
  40. rc = stat(full_path.characters(), &st);
  41. else
  42. rc = lstat(full_path.characters(), &st);
  43. if (rc < 0) {
  44. m_error = errno;
  45. perror("stat/lstat");
  46. return false;
  47. }
  48. size = st.st_size;
  49. mode = st.st_mode;
  50. uid = st.st_uid;
  51. gid = st.st_gid;
  52. inode = st.st_ino;
  53. mtime = st.st_mtime;
  54. if (S_ISLNK(mode)) {
  55. symlink_target = Core::File::read_link(full_path);
  56. if (symlink_target.is_null())
  57. perror("readlink");
  58. }
  59. if (S_ISDIR(mode)) {
  60. is_accessible_directory = access(full_path.characters(), R_OK | X_OK) == 0;
  61. }
  62. return true;
  63. }
  64. void FileSystemModel::Node::traverse_if_needed()
  65. {
  66. if (!is_directory() || has_traversed)
  67. return;
  68. has_traversed = true;
  69. if (m_parent_of_root) {
  70. auto root = adopt_own(*new Node(m_model));
  71. root->fetch_data("/", true);
  72. root->name = "/";
  73. root->parent = this;
  74. children.append(move(root));
  75. return;
  76. }
  77. total_size = 0;
  78. auto full_path = this->full_path();
  79. Core::DirIterator di(full_path, m_model.should_show_dotfiles() ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  80. if (di.has_error()) {
  81. m_error = di.error();
  82. fprintf(stderr, "DirIterator: %s\n", di.error_string());
  83. return;
  84. }
  85. Vector<String> child_names;
  86. while (di.has_next()) {
  87. child_names.append(di.next_path());
  88. }
  89. quick_sort(child_names);
  90. NonnullOwnPtrVector<Node> directory_children;
  91. NonnullOwnPtrVector<Node> file_children;
  92. for (auto& child_name : child_names) {
  93. String child_path = String::formatted("{}/{}", full_path, child_name);
  94. auto child = adopt_own(*new Node(m_model));
  95. bool ok = child->fetch_data(child_path, false);
  96. if (!ok)
  97. continue;
  98. if (m_model.m_mode == DirectoriesOnly && !S_ISDIR(child->mode))
  99. continue;
  100. child->name = child_name;
  101. child->parent = this;
  102. total_size += child->size;
  103. if (S_ISDIR(child->mode))
  104. directory_children.append(move(child));
  105. else
  106. file_children.append(move(child));
  107. }
  108. children.append(move(directory_children));
  109. children.append(move(file_children));
  110. if (!m_file_watcher) {
  111. // We are not already watching this file, create a new watcher
  112. auto watcher_or_error = Core::FileWatcher::watch(full_path);
  113. // Note : the watcher may not be created (e.g. we do not have access rights.) This is expected, just don't watch if that's the case.
  114. if (!watcher_or_error.is_error()) {
  115. m_file_watcher = watcher_or_error.release_value();
  116. m_file_watcher->on_change = [this](auto) {
  117. has_traversed = false;
  118. mode = 0;
  119. children.clear();
  120. reify_if_needed();
  121. m_model.did_update();
  122. };
  123. }
  124. }
  125. }
  126. void FileSystemModel::Node::reify_if_needed()
  127. {
  128. traverse_if_needed();
  129. if (mode != 0)
  130. return;
  131. fetch_data(full_path(), parent == nullptr || parent->m_parent_of_root);
  132. }
  133. bool FileSystemModel::Node::is_symlink_to_directory() const
  134. {
  135. if (!S_ISLNK(mode))
  136. return false;
  137. struct stat st;
  138. if (lstat(symlink_target.characters(), &st) < 0)
  139. return false;
  140. return S_ISDIR(st.st_mode);
  141. }
  142. String FileSystemModel::Node::full_path() const
  143. {
  144. Vector<String, 32> lineage;
  145. for (auto* ancestor = parent; ancestor; ancestor = ancestor->parent) {
  146. lineage.append(ancestor->name);
  147. }
  148. StringBuilder builder;
  149. builder.append(m_model.root_path());
  150. for (int i = lineage.size() - 1; i >= 0; --i) {
  151. builder.append('/');
  152. builder.append(lineage[i]);
  153. }
  154. builder.append('/');
  155. builder.append(name);
  156. return LexicalPath::canonicalized_path(builder.to_string());
  157. }
  158. ModelIndex FileSystemModel::index(String path, int column) const
  159. {
  160. LexicalPath lexical_path(move(path));
  161. const Node* node = m_root->m_parent_of_root ? &m_root->children.first() : m_root;
  162. if (lexical_path.string() == "/")
  163. return node->index(column);
  164. for (size_t i = 0; i < lexical_path.parts().size(); ++i) {
  165. auto& part = lexical_path.parts()[i];
  166. bool found = false;
  167. for (auto& child : node->children) {
  168. if (child.name == part) {
  169. const_cast<Node&>(child).reify_if_needed();
  170. node = &child;
  171. found = true;
  172. if (i == lexical_path.parts().size() - 1)
  173. return child.index(column);
  174. break;
  175. }
  176. }
  177. if (!found)
  178. return {};
  179. }
  180. return {};
  181. }
  182. String FileSystemModel::full_path(const ModelIndex& index) const
  183. {
  184. auto& node = this->node(index);
  185. const_cast<Node&>(node).reify_if_needed();
  186. return node.full_path();
  187. }
  188. FileSystemModel::FileSystemModel(String root_path, Mode mode)
  189. : m_root_path(LexicalPath::canonicalized_path(move(root_path)))
  190. , m_mode(mode)
  191. {
  192. setpwent();
  193. while (auto* passwd = getpwent())
  194. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  195. endpwent();
  196. setgrent();
  197. while (auto* group = getgrent())
  198. m_group_names.set(group->gr_gid, group->gr_name);
  199. endgrent();
  200. update();
  201. }
  202. FileSystemModel::~FileSystemModel()
  203. {
  204. }
  205. String FileSystemModel::name_for_uid(uid_t uid) const
  206. {
  207. auto it = m_user_names.find(uid);
  208. if (it == m_user_names.end())
  209. return String::number(uid);
  210. return (*it).value;
  211. }
  212. String FileSystemModel::name_for_gid(gid_t gid) const
  213. {
  214. auto it = m_group_names.find(gid);
  215. if (it == m_group_names.end())
  216. return String::number(gid);
  217. return (*it).value;
  218. }
  219. static String permission_string(mode_t mode)
  220. {
  221. StringBuilder builder;
  222. if (S_ISDIR(mode))
  223. builder.append("d");
  224. else if (S_ISLNK(mode))
  225. builder.append("l");
  226. else if (S_ISBLK(mode))
  227. builder.append("b");
  228. else if (S_ISCHR(mode))
  229. builder.append("c");
  230. else if (S_ISFIFO(mode))
  231. builder.append("f");
  232. else if (S_ISSOCK(mode))
  233. builder.append("s");
  234. else if (S_ISREG(mode))
  235. builder.append("-");
  236. else
  237. builder.append("?");
  238. builder.append(mode & S_IRUSR ? 'r' : '-');
  239. builder.append(mode & S_IWUSR ? 'w' : '-');
  240. builder.append(mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'));
  241. builder.append(mode & S_IRGRP ? 'r' : '-');
  242. builder.append(mode & S_IWGRP ? 'w' : '-');
  243. builder.append(mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'));
  244. builder.append(mode & S_IROTH ? 'r' : '-');
  245. builder.append(mode & S_IWOTH ? 'w' : '-');
  246. if (mode & S_ISVTX)
  247. builder.append('t');
  248. else
  249. builder.append(mode & S_IXOTH ? 'x' : '-');
  250. return builder.to_string();
  251. }
  252. void FileSystemModel::Node::set_selected(bool selected)
  253. {
  254. if (m_selected == selected)
  255. return;
  256. m_selected = selected;
  257. }
  258. void FileSystemModel::update_node_on_selection(const ModelIndex& index, const bool selected)
  259. {
  260. Node& node = const_cast<Node&>(this->node(index));
  261. node.set_selected(selected);
  262. }
  263. void FileSystemModel::set_root_path(String root_path)
  264. {
  265. if (root_path.is_null())
  266. m_root_path = {};
  267. else
  268. m_root_path = LexicalPath::canonicalized_path(move(root_path));
  269. update();
  270. if (m_root->has_error()) {
  271. if (on_error)
  272. on_error(m_root->error(), m_root->error_string());
  273. } else if (on_complete) {
  274. on_complete();
  275. }
  276. }
  277. void FileSystemModel::update()
  278. {
  279. m_root = adopt_own(*new Node(*this));
  280. if (m_root_path.is_null())
  281. m_root->m_parent_of_root = true;
  282. m_root->reify_if_needed();
  283. did_update();
  284. }
  285. int FileSystemModel::row_count(const ModelIndex& index) const
  286. {
  287. Node& node = const_cast<Node&>(this->node(index));
  288. node.reify_if_needed();
  289. if (node.is_directory())
  290. return node.children.size();
  291. return 0;
  292. }
  293. const FileSystemModel::Node& FileSystemModel::node(const ModelIndex& index) const
  294. {
  295. if (!index.is_valid())
  296. return *m_root;
  297. VERIFY(index.internal_data());
  298. return *(Node*)index.internal_data();
  299. }
  300. ModelIndex FileSystemModel::index(int row, int column, const ModelIndex& parent) const
  301. {
  302. if (row < 0 || column < 0)
  303. return {};
  304. auto& node = this->node(parent);
  305. const_cast<Node&>(node).reify_if_needed();
  306. if (static_cast<size_t>(row) >= node.children.size())
  307. return {};
  308. return create_index(row, column, &node.children[row]);
  309. }
  310. ModelIndex FileSystemModel::parent_index(const ModelIndex& index) const
  311. {
  312. if (!index.is_valid())
  313. return {};
  314. auto& node = this->node(index);
  315. if (!node.parent) {
  316. VERIFY(&node == m_root);
  317. return {};
  318. }
  319. return node.parent->index(index.column());
  320. }
  321. Variant FileSystemModel::data(const ModelIndex& index, ModelRole role) const
  322. {
  323. VERIFY(index.is_valid());
  324. if (role == ModelRole::TextAlignment) {
  325. switch (index.column()) {
  326. case Column::Icon:
  327. return Gfx::TextAlignment::Center;
  328. case Column::Size:
  329. case Column::Inode:
  330. return Gfx::TextAlignment::CenterRight;
  331. case Column::Name:
  332. case Column::Owner:
  333. case Column::Group:
  334. case Column::ModificationTime:
  335. case Column::Permissions:
  336. case Column::SymlinkTarget:
  337. return Gfx::TextAlignment::CenterLeft;
  338. default:
  339. VERIFY_NOT_REACHED();
  340. }
  341. }
  342. auto& node = this->node(index);
  343. if (role == ModelRole::Custom) {
  344. // For GUI::FileSystemModel, custom role means the full path.
  345. VERIFY(index.column() == Column::Name);
  346. return node.full_path();
  347. }
  348. if (role == ModelRole::MimeData) {
  349. if (index.column() == Column::Name) {
  350. StringBuilder builder;
  351. builder.append("file://");
  352. builder.append(node.full_path());
  353. return builder.to_string();
  354. }
  355. return {};
  356. }
  357. if (role == ModelRole::Sort) {
  358. switch (index.column()) {
  359. case Column::Icon:
  360. return node.is_directory() ? 0 : 1;
  361. case Column::Name:
  362. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  363. // Hence, the sort value for the name column is simply the index row. :^)
  364. return index.row();
  365. case Column::Size:
  366. return (int)node.size;
  367. case Column::Owner:
  368. return name_for_uid(node.uid);
  369. case Column::Group:
  370. return name_for_gid(node.gid);
  371. case Column::Permissions:
  372. return permission_string(node.mode);
  373. case Column::ModificationTime:
  374. return node.mtime;
  375. case Column::Inode:
  376. return (int)node.inode;
  377. case Column::SymlinkTarget:
  378. return node.symlink_target;
  379. }
  380. VERIFY_NOT_REACHED();
  381. }
  382. if (role == ModelRole::Display) {
  383. switch (index.column()) {
  384. case Column::Icon:
  385. return icon_for(node);
  386. case Column::Name:
  387. return node.name;
  388. case Column::Size:
  389. return human_readable_size(node.size);
  390. case Column::Owner:
  391. return name_for_uid(node.uid);
  392. case Column::Group:
  393. return name_for_gid(node.gid);
  394. case Column::Permissions:
  395. return permission_string(node.mode);
  396. case Column::ModificationTime:
  397. return timestamp_string(node.mtime);
  398. case Column::Inode:
  399. return (int)node.inode;
  400. case Column::SymlinkTarget:
  401. return node.symlink_target;
  402. }
  403. }
  404. if (role == ModelRole::Icon) {
  405. return icon_for(node);
  406. }
  407. return {};
  408. }
  409. Icon FileSystemModel::icon_for(const Node& node) const
  410. {
  411. if (node.full_path() == "/")
  412. return FileIconProvider::icon_for_path("/");
  413. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  414. if (!node.thumbnail) {
  415. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  416. return FileIconProvider::filetype_image_icon();
  417. }
  418. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  419. }
  420. if (node.is_directory()) {
  421. if (node.full_path() == Core::StandardPaths::home_directory()) {
  422. if (node.is_selected())
  423. return FileIconProvider::home_directory_open_icon();
  424. return FileIconProvider::home_directory_icon();
  425. }
  426. if (node.full_path() == Core::StandardPaths::desktop_directory())
  427. return FileIconProvider::desktop_directory_icon();
  428. if (node.is_selected() && node.is_accessible_directory)
  429. return FileIconProvider::directory_open_icon();
  430. }
  431. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  432. }
  433. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  434. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  435. {
  436. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  437. if (!png_bitmap)
  438. return nullptr;
  439. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  440. auto thumbnail = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 32, 32 });
  441. Gfx::IntRect destination = Gfx::IntRect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  442. destination.center_within(thumbnail->rect());
  443. Painter painter(*thumbnail);
  444. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  445. return thumbnail;
  446. }
  447. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  448. {
  449. // See if we already have the thumbnail
  450. // we're looking for in the cache.
  451. auto path = node.full_path();
  452. auto it = s_thumbnail_cache.find(path);
  453. if (it != s_thumbnail_cache.end()) {
  454. if (!(*it).value)
  455. return false;
  456. node.thumbnail = (*it).value;
  457. return true;
  458. }
  459. // Otherwise, arrange to render the thumbnail
  460. // in background and make it available later.
  461. s_thumbnail_cache.set(path, nullptr);
  462. m_thumbnail_progress_total++;
  463. auto weak_this = make_weak_ptr();
  464. LibThread::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  465. [path] {
  466. return render_thumbnail(path);
  467. },
  468. [this, path, weak_this](auto thumbnail) {
  469. s_thumbnail_cache.set(path, move(thumbnail));
  470. // The model was destroyed, no need to update
  471. // progress or call any event handlers.
  472. if (weak_this.is_null())
  473. return;
  474. m_thumbnail_progress++;
  475. if (on_thumbnail_progress)
  476. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  477. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  478. m_thumbnail_progress = 0;
  479. m_thumbnail_progress_total = 0;
  480. }
  481. did_update();
  482. });
  483. return false;
  484. }
  485. int FileSystemModel::column_count(const ModelIndex&) const
  486. {
  487. return Column::__Count;
  488. }
  489. String FileSystemModel::column_name(int column) const
  490. {
  491. switch (column) {
  492. case Column::Icon:
  493. return "";
  494. case Column::Name:
  495. return "Name";
  496. case Column::Size:
  497. return "Size";
  498. case Column::Owner:
  499. return "Owner";
  500. case Column::Group:
  501. return "Group";
  502. case Column::Permissions:
  503. return "Mode";
  504. case Column::ModificationTime:
  505. return "Modified";
  506. case Column::Inode:
  507. return "Inode";
  508. case Column::SymlinkTarget:
  509. return "Symlink target";
  510. }
  511. VERIFY_NOT_REACHED();
  512. }
  513. bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) const
  514. {
  515. if (!index.is_valid())
  516. return false;
  517. if (!mime_types.contains_slow("text/uri-list"))
  518. return false;
  519. auto& node = this->node(index);
  520. return node.is_directory();
  521. }
  522. void FileSystemModel::set_should_show_dotfiles(bool show)
  523. {
  524. if (m_should_show_dotfiles == show)
  525. return;
  526. m_should_show_dotfiles = show;
  527. update();
  528. }
  529. bool FileSystemModel::is_editable(const ModelIndex& index) const
  530. {
  531. if (!index.is_valid())
  532. return false;
  533. return index.column() == Column::Name;
  534. }
  535. void FileSystemModel::set_data(const ModelIndex& index, const Variant& data)
  536. {
  537. VERIFY(is_editable(index));
  538. Node& node = const_cast<Node&>(this->node(index));
  539. auto dirname = LexicalPath(node.full_path()).dirname();
  540. auto new_full_path = String::formatted("{}/{}", dirname, data.to_string());
  541. int rc = rename(node.full_path().characters(), new_full_path.characters());
  542. if (rc < 0) {
  543. if (on_error)
  544. on_error(errno, strerror(errno));
  545. }
  546. }
  547. Vector<ModelIndex, 1> FileSystemModel::matches(const StringView& searching, unsigned flags, const ModelIndex& index)
  548. {
  549. Node& node = const_cast<Node&>(this->node(index));
  550. node.reify_if_needed();
  551. Vector<ModelIndex, 1> found_indices;
  552. for (auto& child : node.children) {
  553. if (string_matches(child.name, searching, flags)) {
  554. const_cast<Node&>(child).reify_if_needed();
  555. found_indices.append(child.index(Column::Name));
  556. if (flags & FirstMatchOnly)
  557. break;
  558. }
  559. }
  560. return found_indices;
  561. }
  562. }