FileSystemModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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.appendf("%c%c%c%c%c%c%c%c",
  239. mode & S_IRUSR ? 'r' : '-',
  240. mode & S_IWUSR ? 'w' : '-',
  241. mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'),
  242. mode & S_IRGRP ? 'r' : '-',
  243. mode & S_IWGRP ? 'w' : '-',
  244. mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'),
  245. mode & S_IROTH ? 'r' : '-',
  246. mode & S_IWOTH ? 'w' : '-');
  247. if (mode & S_ISVTX)
  248. builder.append("t");
  249. else
  250. builder.appendf("%c", mode & S_IXOTH ? 'x' : '-');
  251. return builder.to_string();
  252. }
  253. void FileSystemModel::Node::set_selected(bool selected)
  254. {
  255. if (m_selected == selected)
  256. return;
  257. m_selected = selected;
  258. }
  259. void FileSystemModel::update_node_on_selection(const ModelIndex& index, const bool selected)
  260. {
  261. Node& node = const_cast<Node&>(this->node(index));
  262. node.set_selected(selected);
  263. }
  264. void FileSystemModel::set_root_path(String root_path)
  265. {
  266. if (root_path.is_null())
  267. m_root_path = {};
  268. else
  269. m_root_path = LexicalPath::canonicalized_path(move(root_path));
  270. update();
  271. if (m_root->has_error()) {
  272. if (on_error)
  273. on_error(m_root->error(), m_root->error_string());
  274. } else if (on_complete) {
  275. on_complete();
  276. }
  277. }
  278. void FileSystemModel::update()
  279. {
  280. m_root = adopt_own(*new Node(*this));
  281. if (m_root_path.is_null())
  282. m_root->m_parent_of_root = true;
  283. m_root->reify_if_needed();
  284. did_update();
  285. }
  286. int FileSystemModel::row_count(const ModelIndex& index) const
  287. {
  288. Node& node = const_cast<Node&>(this->node(index));
  289. node.reify_if_needed();
  290. if (node.is_directory())
  291. return node.children.size();
  292. return 0;
  293. }
  294. const FileSystemModel::Node& FileSystemModel::node(const ModelIndex& index) const
  295. {
  296. if (!index.is_valid())
  297. return *m_root;
  298. VERIFY(index.internal_data());
  299. return *(Node*)index.internal_data();
  300. }
  301. ModelIndex FileSystemModel::index(int row, int column, const ModelIndex& parent) const
  302. {
  303. if (row < 0 || column < 0)
  304. return {};
  305. auto& node = this->node(parent);
  306. const_cast<Node&>(node).reify_if_needed();
  307. if (static_cast<size_t>(row) >= node.children.size())
  308. return {};
  309. return create_index(row, column, &node.children[row]);
  310. }
  311. ModelIndex FileSystemModel::parent_index(const ModelIndex& index) const
  312. {
  313. if (!index.is_valid())
  314. return {};
  315. auto& node = this->node(index);
  316. if (!node.parent) {
  317. VERIFY(&node == m_root);
  318. return {};
  319. }
  320. return node.parent->index(index.column());
  321. }
  322. Variant FileSystemModel::data(const ModelIndex& index, ModelRole role) const
  323. {
  324. VERIFY(index.is_valid());
  325. if (role == ModelRole::TextAlignment) {
  326. switch (index.column()) {
  327. case Column::Icon:
  328. return Gfx::TextAlignment::Center;
  329. case Column::Size:
  330. case Column::Inode:
  331. return Gfx::TextAlignment::CenterRight;
  332. case Column::Name:
  333. case Column::Owner:
  334. case Column::Group:
  335. case Column::ModificationTime:
  336. case Column::Permissions:
  337. case Column::SymlinkTarget:
  338. return Gfx::TextAlignment::CenterLeft;
  339. default:
  340. VERIFY_NOT_REACHED();
  341. }
  342. }
  343. auto& node = this->node(index);
  344. if (role == ModelRole::Custom) {
  345. // For GUI::FileSystemModel, custom role means the full path.
  346. VERIFY(index.column() == Column::Name);
  347. return node.full_path();
  348. }
  349. if (role == ModelRole::MimeData) {
  350. if (index.column() == Column::Name) {
  351. StringBuilder builder;
  352. builder.append("file://");
  353. builder.append(node.full_path());
  354. return builder.to_string();
  355. }
  356. return {};
  357. }
  358. if (role == ModelRole::Sort) {
  359. switch (index.column()) {
  360. case Column::Icon:
  361. return node.is_directory() ? 0 : 1;
  362. case Column::Name:
  363. // NOTE: The children of a Node are grouped by directory-or-file and then sorted alphabetically.
  364. // Hence, the sort value for the name column is simply the index row. :^)
  365. return index.row();
  366. case Column::Size:
  367. return (int)node.size;
  368. case Column::Owner:
  369. return name_for_uid(node.uid);
  370. case Column::Group:
  371. return name_for_gid(node.gid);
  372. case Column::Permissions:
  373. return permission_string(node.mode);
  374. case Column::ModificationTime:
  375. return node.mtime;
  376. case Column::Inode:
  377. return (int)node.inode;
  378. case Column::SymlinkTarget:
  379. return node.symlink_target;
  380. }
  381. VERIFY_NOT_REACHED();
  382. }
  383. if (role == ModelRole::Display) {
  384. switch (index.column()) {
  385. case Column::Icon:
  386. return icon_for(node);
  387. case Column::Name:
  388. return node.name;
  389. case Column::Size:
  390. return human_readable_size(node.size);
  391. case Column::Owner:
  392. return name_for_uid(node.uid);
  393. case Column::Group:
  394. return name_for_gid(node.gid);
  395. case Column::Permissions:
  396. return permission_string(node.mode);
  397. case Column::ModificationTime:
  398. return timestamp_string(node.mtime);
  399. case Column::Inode:
  400. return (int)node.inode;
  401. case Column::SymlinkTarget:
  402. return node.symlink_target;
  403. }
  404. }
  405. if (role == ModelRole::Icon) {
  406. return icon_for(node);
  407. }
  408. return {};
  409. }
  410. Icon FileSystemModel::icon_for(const Node& node) const
  411. {
  412. if (node.full_path() == "/")
  413. return FileIconProvider::icon_for_path("/");
  414. if (Gfx::Bitmap::is_path_a_supported_image_format(node.name)) {
  415. if (!node.thumbnail) {
  416. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  417. return FileIconProvider::filetype_image_icon();
  418. }
  419. return GUI::Icon(FileIconProvider::filetype_image_icon().bitmap_for_size(16), *node.thumbnail);
  420. }
  421. if (node.is_directory()) {
  422. if (node.full_path() == Core::StandardPaths::home_directory()) {
  423. if (node.is_selected())
  424. return FileIconProvider::home_directory_open_icon();
  425. return FileIconProvider::home_directory_icon();
  426. }
  427. if (node.full_path() == Core::StandardPaths::desktop_directory())
  428. return FileIconProvider::desktop_directory_icon();
  429. if (node.is_selected() && node.is_accessible_directory)
  430. return FileIconProvider::directory_open_icon();
  431. }
  432. return FileIconProvider::icon_for_path(node.full_path(), node.mode);
  433. }
  434. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  435. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  436. {
  437. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  438. if (!png_bitmap)
  439. return nullptr;
  440. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  441. auto thumbnail = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 32, 32 });
  442. Gfx::IntRect destination = Gfx::IntRect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  443. destination.center_within(thumbnail->rect());
  444. Painter painter(*thumbnail);
  445. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  446. return thumbnail;
  447. }
  448. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  449. {
  450. // See if we already have the thumbnail
  451. // we're looking for in the cache.
  452. auto path = node.full_path();
  453. auto it = s_thumbnail_cache.find(path);
  454. if (it != s_thumbnail_cache.end()) {
  455. if (!(*it).value)
  456. return false;
  457. node.thumbnail = (*it).value;
  458. return true;
  459. }
  460. // Otherwise, arrange to render the thumbnail
  461. // in background and make it available later.
  462. s_thumbnail_cache.set(path, nullptr);
  463. m_thumbnail_progress_total++;
  464. auto weak_this = make_weak_ptr();
  465. LibThread::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  466. [path] {
  467. return render_thumbnail(path);
  468. },
  469. [this, path, weak_this](auto thumbnail) {
  470. s_thumbnail_cache.set(path, move(thumbnail));
  471. // The model was destroyed, no need to update
  472. // progress or call any event handlers.
  473. if (weak_this.is_null())
  474. return;
  475. m_thumbnail_progress++;
  476. if (on_thumbnail_progress)
  477. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  478. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  479. m_thumbnail_progress = 0;
  480. m_thumbnail_progress_total = 0;
  481. }
  482. did_update();
  483. });
  484. return false;
  485. }
  486. int FileSystemModel::column_count(const ModelIndex&) const
  487. {
  488. return Column::__Count;
  489. }
  490. String FileSystemModel::column_name(int column) const
  491. {
  492. switch (column) {
  493. case Column::Icon:
  494. return "";
  495. case Column::Name:
  496. return "Name";
  497. case Column::Size:
  498. return "Size";
  499. case Column::Owner:
  500. return "Owner";
  501. case Column::Group:
  502. return "Group";
  503. case Column::Permissions:
  504. return "Mode";
  505. case Column::ModificationTime:
  506. return "Modified";
  507. case Column::Inode:
  508. return "Inode";
  509. case Column::SymlinkTarget:
  510. return "Symlink target";
  511. }
  512. VERIFY_NOT_REACHED();
  513. }
  514. bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) const
  515. {
  516. if (!index.is_valid())
  517. return false;
  518. if (!mime_types.contains_slow("text/uri-list"))
  519. return false;
  520. auto& node = this->node(index);
  521. return node.is_directory();
  522. }
  523. void FileSystemModel::set_should_show_dotfiles(bool show)
  524. {
  525. if (m_should_show_dotfiles == show)
  526. return;
  527. m_should_show_dotfiles = show;
  528. update();
  529. }
  530. bool FileSystemModel::is_editable(const ModelIndex& index) const
  531. {
  532. if (!index.is_valid())
  533. return false;
  534. return index.column() == Column::Name;
  535. }
  536. void FileSystemModel::set_data(const ModelIndex& index, const Variant& data)
  537. {
  538. VERIFY(is_editable(index));
  539. Node& node = const_cast<Node&>(this->node(index));
  540. auto dirname = LexicalPath(node.full_path()).dirname();
  541. auto new_full_path = String::formatted("{}/{}", dirname, data.to_string());
  542. int rc = rename(node.full_path().characters(), new_full_path.characters());
  543. if (rc < 0) {
  544. if (on_error)
  545. on_error(errno, strerror(errno));
  546. }
  547. }
  548. Vector<ModelIndex, 1> FileSystemModel::matches(const StringView& searching, unsigned flags, const ModelIndex& index)
  549. {
  550. Node& node = const_cast<Node&>(this->node(index));
  551. node.reify_if_needed();
  552. Vector<ModelIndex, 1> found_indices;
  553. for (auto& child : node.children) {
  554. if (string_matches(child.name, searching, flags)) {
  555. const_cast<Node&>(child).reify_if_needed();
  556. found_indices.append(child.index(Column::Name));
  557. if (flags & FirstMatchOnly)
  558. break;
  559. }
  560. }
  561. return found_indices;
  562. }
  563. }