FileSystemModel.cpp 17 KB

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