FileSystemModel.cpp 18 KB

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