FileSystemModel.cpp 17 KB

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