FileSystemModel.cpp 18 KB

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