FileSystemModel.cpp 18 KB

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