FileSystemModel.cpp 17 KB

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