GFileSystemModel.cpp 16 KB

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