GFileSystemModel.cpp 16 KB

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