GFileSystemModel.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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/FileSystemPath.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibCore/CDirIterator.h>
  29. #include <LibDraw/GraphicsBitmap.h>
  30. #include <LibGUI/GFileSystemModel.h>
  31. #include <LibGUI/GPainter.h>
  32. #include <LibThread/BackgroundAction.h>
  33. #include <dirent.h>
  34. #include <grp.h>
  35. #include <pwd.h>
  36. #include <stdio.h>
  37. #include <sys/stat.h>
  38. #include <unistd.h>
  39. GModelIndex GFileSystemModel::Node::index(const GFileSystemModel& model, int column) const
  40. {
  41. if (!parent)
  42. return {};
  43. for (int row = 0; row < parent->children.size(); ++row) {
  44. if (&parent->children[row] == this)
  45. return model.create_index(row, column, const_cast<Node*>(this));
  46. }
  47. ASSERT_NOT_REACHED();
  48. }
  49. bool GFileSystemModel::Node::fetch_data(const String& full_path, bool is_root)
  50. {
  51. struct stat st;
  52. int rc;
  53. if (is_root)
  54. rc = stat(full_path.characters(), &st);
  55. else
  56. rc = lstat(full_path.characters(), &st);
  57. if (rc < 0) {
  58. perror("stat/lstat");
  59. return false;
  60. }
  61. size = st.st_size;
  62. mode = st.st_mode;
  63. uid = st.st_uid;
  64. gid = st.st_gid;
  65. inode = st.st_ino;
  66. mtime = st.st_mtime;
  67. return true;
  68. }
  69. void GFileSystemModel::Node::traverse_if_needed(const GFileSystemModel& model)
  70. {
  71. if (!is_directory() || has_traversed)
  72. return;
  73. has_traversed = true;
  74. total_size = 0;
  75. auto full_path = this->full_path(model);
  76. CDirIterator di(full_path, CDirIterator::SkipDots);
  77. if (di.has_error()) {
  78. fprintf(stderr, "CDirIterator: %s\n", di.error_string());
  79. return;
  80. }
  81. while (di.has_next()) {
  82. String name = di.next_path();
  83. String child_path = String::format("%s/%s", full_path.characters(), name.characters());
  84. NonnullOwnPtr<Node> child = make<Node>();
  85. bool ok = child->fetch_data(child_path, false);
  86. if (!ok)
  87. continue;
  88. if (model.m_mode == DirectoriesOnly && !S_ISDIR(child->mode))
  89. continue;
  90. child->name = name;
  91. child->parent = this;
  92. total_size += child->size;
  93. children.append(move(child));
  94. }
  95. if (m_watch_fd >= 0)
  96. return;
  97. m_watch_fd = watch_file(full_path.characters(), full_path.length());
  98. if (m_watch_fd < 0) {
  99. perror("watch_file");
  100. return;
  101. }
  102. fcntl(m_watch_fd, F_SETFD, FD_CLOEXEC);
  103. dbg() << "Watching " << full_path << " for changes, m_watch_fd = " << m_watch_fd;
  104. m_notifier = CNotifier::construct(m_watch_fd, CNotifier::Event::Read);
  105. m_notifier->on_ready_to_read = [this, &model] {
  106. char buffer[32];
  107. int rc = read(m_notifier->fd(), buffer, sizeof(buffer));
  108. ASSERT(rc >= 0);
  109. has_traversed = false;
  110. mode = 0;
  111. children.clear();
  112. reify_if_needed(model);
  113. const_cast<GFileSystemModel&>(model).did_update();
  114. };
  115. }
  116. void GFileSystemModel::Node::reify_if_needed(const GFileSystemModel& model)
  117. {
  118. traverse_if_needed(model);
  119. if (mode != 0)
  120. return;
  121. fetch_data(full_path(model), parent == nullptr);
  122. }
  123. String GFileSystemModel::Node::full_path(const GFileSystemModel& model) const
  124. {
  125. Vector<String, 32> lineage;
  126. for (auto* ancestor = parent; ancestor; ancestor = ancestor->parent) {
  127. lineage.append(ancestor->name);
  128. }
  129. StringBuilder builder;
  130. builder.append(model.root_path());
  131. for (int i = lineage.size() - 1; i >= 0; --i) {
  132. builder.append('/');
  133. builder.append(lineage[i]);
  134. }
  135. builder.append('/');
  136. builder.append(name);
  137. return canonicalized_path(builder.to_string());
  138. }
  139. GModelIndex GFileSystemModel::index(const StringView& path, int column) const
  140. {
  141. FileSystemPath canonical_path(path);
  142. const Node* node = m_root;
  143. if (canonical_path.string() == "/")
  144. return m_root->index(*this, column);
  145. for (int i = 0; i < canonical_path.parts().size(); ++i) {
  146. auto& part = canonical_path.parts()[i];
  147. bool found = false;
  148. for (auto& child : node->children) {
  149. if (child.name == part) {
  150. const_cast<Node&>(child).reify_if_needed(*this);
  151. node = &child;
  152. found = true;
  153. if (i == canonical_path.parts().size() - 1)
  154. return child.index(*this, column);
  155. break;
  156. }
  157. }
  158. if (!found)
  159. return {};
  160. }
  161. return {};
  162. }
  163. String GFileSystemModel::full_path(const GModelIndex& index) const
  164. {
  165. auto& node = this->node(index);
  166. const_cast<Node&>(node).reify_if_needed(*this);
  167. return node.full_path(*this);
  168. }
  169. GFileSystemModel::GFileSystemModel(const StringView& root_path, Mode mode)
  170. : m_root_path(canonicalized_path(root_path))
  171. , m_mode(mode)
  172. {
  173. m_directory_icon = GIcon::default_icon("filetype-folder");
  174. m_file_icon = GIcon::default_icon("filetype-unknown");
  175. m_symlink_icon = GIcon::default_icon("filetype-symlink");
  176. m_socket_icon = GIcon::default_icon("filetype-socket");
  177. m_executable_icon = GIcon::default_icon("filetype-executable");
  178. m_filetype_image_icon = GIcon::default_icon("filetype-image");
  179. m_filetype_sound_icon = GIcon::default_icon("filetype-sound");
  180. m_filetype_html_icon = GIcon::default_icon("filetype-html");
  181. setpwent();
  182. while (auto* passwd = getpwent())
  183. m_user_names.set(passwd->pw_uid, passwd->pw_name);
  184. endpwent();
  185. setgrent();
  186. while (auto* group = getgrent())
  187. m_group_names.set(group->gr_gid, group->gr_name);
  188. endgrent();
  189. update();
  190. }
  191. GFileSystemModel::~GFileSystemModel()
  192. {
  193. }
  194. String GFileSystemModel::name_for_uid(uid_t uid) const
  195. {
  196. auto it = m_user_names.find(uid);
  197. if (it == m_user_names.end())
  198. return String::number(uid);
  199. return (*it).value;
  200. }
  201. String GFileSystemModel::name_for_gid(uid_t gid) const
  202. {
  203. auto it = m_user_names.find(gid);
  204. if (it == m_user_names.end())
  205. return String::number(gid);
  206. return (*it).value;
  207. }
  208. static String permission_string(mode_t mode)
  209. {
  210. StringBuilder builder;
  211. if (S_ISDIR(mode))
  212. builder.append("d");
  213. else if (S_ISLNK(mode))
  214. builder.append("l");
  215. else if (S_ISBLK(mode))
  216. builder.append("b");
  217. else if (S_ISCHR(mode))
  218. builder.append("c");
  219. else if (S_ISFIFO(mode))
  220. builder.append("f");
  221. else if (S_ISSOCK(mode))
  222. builder.append("s");
  223. else if (S_ISREG(mode))
  224. builder.append("-");
  225. else
  226. builder.append("?");
  227. builder.appendf("%c%c%c%c%c%c%c%c",
  228. mode & S_IRUSR ? 'r' : '-',
  229. mode & S_IWUSR ? 'w' : '-',
  230. mode & S_ISUID ? 's' : (mode & S_IXUSR ? 'x' : '-'),
  231. mode & S_IRGRP ? 'r' : '-',
  232. mode & S_IWGRP ? 'w' : '-',
  233. mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'),
  234. mode & S_IROTH ? 'r' : '-',
  235. mode & S_IWOTH ? 'w' : '-');
  236. if (mode & S_ISVTX)
  237. builder.append("t");
  238. else
  239. builder.appendf("%c", mode & S_IXOTH ? 'x' : '-');
  240. return builder.to_string();
  241. }
  242. void GFileSystemModel::set_root_path(const StringView& root_path)
  243. {
  244. m_root_path = canonicalized_path(root_path);
  245. if (on_root_path_change)
  246. on_root_path_change();
  247. update();
  248. }
  249. void GFileSystemModel::update()
  250. {
  251. m_root = make<Node>();
  252. m_root->reify_if_needed(*this);
  253. did_update();
  254. }
  255. int GFileSystemModel::row_count(const GModelIndex& index) const
  256. {
  257. Node& node = const_cast<Node&>(this->node(index));
  258. node.reify_if_needed(*this);
  259. if (node.is_directory())
  260. return node.children.size();
  261. return 0;
  262. }
  263. const GFileSystemModel::Node& GFileSystemModel::node(const GModelIndex& index) const
  264. {
  265. if (!index.is_valid())
  266. return *m_root;
  267. return *(Node*)index.internal_data();
  268. }
  269. GModelIndex GFileSystemModel::index(int row, int column, const GModelIndex& parent) const
  270. {
  271. if (row < 0 || column < 0)
  272. return {};
  273. auto& node = this->node(parent);
  274. const_cast<Node&>(node).reify_if_needed(*this);
  275. if (row >= node.children.size())
  276. return {};
  277. return create_index(row, column, &node.children[row]);
  278. }
  279. GModelIndex GFileSystemModel::parent_index(const GModelIndex& index) const
  280. {
  281. if (!index.is_valid())
  282. return {};
  283. auto& node = this->node(index);
  284. if (!node.parent) {
  285. ASSERT(&node == m_root);
  286. return {};
  287. }
  288. return node.parent->index(*this, index.column());
  289. }
  290. GVariant GFileSystemModel::data(const GModelIndex& index, Role role) const
  291. {
  292. ASSERT(index.is_valid());
  293. auto& node = this->node(index);
  294. if (role == Role::Custom) {
  295. // For GFileSystemModel, custom role means the full path.
  296. ASSERT(index.column() == Column::Name);
  297. return node.full_path(*this);
  298. }
  299. if (role == Role::DragData) {
  300. if (index.column() == Column::Name) {
  301. StringBuilder builder;
  302. builder.append("file://");
  303. builder.append(node.full_path(*this));
  304. return builder.to_string();
  305. }
  306. return {};
  307. }
  308. if (role == Role::Sort) {
  309. switch (index.column()) {
  310. case Column::Icon:
  311. return node.is_directory() ? 0 : 1;
  312. case Column::Name:
  313. return node.name;
  314. case Column::Size:
  315. return (int)node.size;
  316. case Column::Owner:
  317. return name_for_uid(node.uid);
  318. case Column::Group:
  319. return name_for_gid(node.gid);
  320. case Column::Permissions:
  321. return permission_string(node.mode);
  322. case Column::ModificationTime:
  323. return node.mtime;
  324. case Column::Inode:
  325. return (int)node.inode;
  326. }
  327. ASSERT_NOT_REACHED();
  328. }
  329. if (role == Role::Display) {
  330. switch (index.column()) {
  331. case Column::Icon:
  332. return icon_for(node);
  333. case Column::Name:
  334. return node.name;
  335. case Column::Size:
  336. return (int)node.size;
  337. case Column::Owner:
  338. return name_for_uid(node.uid);
  339. case Column::Group:
  340. return name_for_gid(node.gid);
  341. case Column::Permissions:
  342. return permission_string(node.mode);
  343. case Column::ModificationTime:
  344. return timestamp_string(node.mtime);
  345. case Column::Inode:
  346. return (int)node.inode;
  347. }
  348. }
  349. if (role == Role::Icon) {
  350. return icon_for(node);
  351. }
  352. return {};
  353. }
  354. GIcon GFileSystemModel::icon_for_file(const mode_t mode, const String& name) const
  355. {
  356. if (S_ISDIR(mode))
  357. return m_directory_icon;
  358. if (S_ISLNK(mode))
  359. return m_symlink_icon;
  360. if (S_ISSOCK(mode))
  361. return m_socket_icon;
  362. if (mode & S_IXUSR)
  363. return m_executable_icon;
  364. if (name.to_lowercase().ends_with(".wav"))
  365. return m_filetype_sound_icon;
  366. if (name.to_lowercase().ends_with(".html"))
  367. return m_filetype_html_icon;
  368. if (name.to_lowercase().ends_with(".png"))
  369. return m_filetype_image_icon;
  370. return m_file_icon;
  371. }
  372. GIcon GFileSystemModel::icon_for(const Node& node) const
  373. {
  374. if (node.name.to_lowercase().ends_with(".png")) {
  375. if (!node.thumbnail) {
  376. if (!const_cast<GFileSystemModel*>(this)->fetch_thumbnail_for(node))
  377. return m_filetype_image_icon;
  378. }
  379. return GIcon(m_filetype_image_icon.bitmap_for_size(16), *node.thumbnail);
  380. }
  381. return icon_for_file(node.mode, node.name);
  382. }
  383. static HashMap<String, RefPtr<GraphicsBitmap>> s_thumbnail_cache;
  384. static RefPtr<GraphicsBitmap> render_thumbnail(const StringView& path)
  385. {
  386. auto png_bitmap = GraphicsBitmap::load_from_file(path);
  387. if (!png_bitmap)
  388. return nullptr;
  389. auto thumbnail = GraphicsBitmap::create(png_bitmap->format(), { 32, 32 });
  390. Painter painter(*thumbnail);
  391. painter.draw_scaled_bitmap(thumbnail->rect(), *png_bitmap, png_bitmap->rect());
  392. return thumbnail;
  393. }
  394. bool GFileSystemModel::fetch_thumbnail_for(const Node& node)
  395. {
  396. // See if we already have the thumbnail
  397. // we're looking for in the cache.
  398. auto path = node.full_path(*this);
  399. auto it = s_thumbnail_cache.find(path);
  400. if (it != s_thumbnail_cache.end()) {
  401. if (!(*it).value)
  402. return false;
  403. node.thumbnail = (*it).value;
  404. return true;
  405. }
  406. // Otherwise, arrange to render the thumbnail
  407. // in background and make it available later.
  408. s_thumbnail_cache.set(path, nullptr);
  409. m_thumbnail_progress_total++;
  410. auto weak_this = make_weak_ptr();
  411. LibThread::BackgroundAction<RefPtr<GraphicsBitmap>>::create(
  412. [path] {
  413. return render_thumbnail(path);
  414. },
  415. [this, path, weak_this](auto thumbnail) {
  416. s_thumbnail_cache.set(path, move(thumbnail));
  417. // The model was destroyed, no need to update
  418. // progress or call any event handlers.
  419. if (weak_this.is_null())
  420. return;
  421. m_thumbnail_progress++;
  422. if (on_thumbnail_progress)
  423. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  424. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  425. m_thumbnail_progress = 0;
  426. m_thumbnail_progress_total = 0;
  427. }
  428. did_update();
  429. });
  430. return false;
  431. }
  432. int GFileSystemModel::column_count(const GModelIndex&) const
  433. {
  434. return Column::__Count;
  435. }
  436. String GFileSystemModel::column_name(int column) const
  437. {
  438. switch (column) {
  439. case Column::Icon:
  440. return "";
  441. case Column::Name:
  442. return "Name";
  443. case Column::Size:
  444. return "Size";
  445. case Column::Owner:
  446. return "Owner";
  447. case Column::Group:
  448. return "Group";
  449. case Column::Permissions:
  450. return "Mode";
  451. case Column::ModificationTime:
  452. return "Modified";
  453. case Column::Inode:
  454. return "Inode";
  455. }
  456. ASSERT_NOT_REACHED();
  457. }
  458. GModel::ColumnMetadata GFileSystemModel::column_metadata(int column) const
  459. {
  460. switch (column) {
  461. case Column::Icon:
  462. return { 16, TextAlignment::Center, nullptr, GModel::ColumnMetadata::Sortable::False };
  463. case Column::Name:
  464. return { 120, TextAlignment::CenterLeft };
  465. case Column::Size:
  466. return { 80, TextAlignment::CenterRight };
  467. case Column::Owner:
  468. return { 50, TextAlignment::CenterLeft };
  469. case Column::Group:
  470. return { 50, TextAlignment::CenterLeft };
  471. case Column::ModificationTime:
  472. return { 110, TextAlignment::CenterLeft };
  473. case Column::Permissions:
  474. return { 65, TextAlignment::CenterLeft };
  475. case Column::Inode:
  476. return { 60, TextAlignment::CenterRight };
  477. }
  478. ASSERT_NOT_REACHED();
  479. }