FileSystemModel.cpp 17 KB

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