FileSystemModel.cpp 18 KB

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