FileSystemModel.cpp 19 KB

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