FileSystemModel.cpp 17 KB

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