FileSystemModel.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. auto& node = this->node(index);
  312. if (role == Role::Custom) {
  313. // For GUI::FileSystemModel, custom role means the full path.
  314. ASSERT(index.column() == Column::Name);
  315. return node.full_path(*this);
  316. }
  317. if (role == Role::DragData) {
  318. if (index.column() == Column::Name) {
  319. StringBuilder builder;
  320. builder.append("file://");
  321. builder.append(node.full_path(*this));
  322. return builder.to_string();
  323. }
  324. return {};
  325. }
  326. if (role == Role::Sort) {
  327. switch (index.column()) {
  328. case Column::Icon:
  329. return node.is_directory() ? 0 : 1;
  330. case Column::Name:
  331. return node.name;
  332. case Column::Size:
  333. return (int)node.size;
  334. case Column::Owner:
  335. return name_for_uid(node.uid);
  336. case Column::Group:
  337. return name_for_gid(node.gid);
  338. case Column::Permissions:
  339. return permission_string(node.mode);
  340. case Column::ModificationTime:
  341. return node.mtime;
  342. case Column::Inode:
  343. return (int)node.inode;
  344. case Column::SymlinkTarget:
  345. return node.symlink_target;
  346. }
  347. ASSERT_NOT_REACHED();
  348. }
  349. if (role == Role::Display) {
  350. switch (index.column()) {
  351. case Column::Icon:
  352. return icon_for(node);
  353. case Column::Name:
  354. return node.name;
  355. case Column::Size:
  356. return (int)node.size;
  357. case Column::Owner:
  358. return name_for_uid(node.uid);
  359. case Column::Group:
  360. return name_for_gid(node.gid);
  361. case Column::Permissions:
  362. return permission_string(node.mode);
  363. case Column::ModificationTime:
  364. return timestamp_string(node.mtime);
  365. case Column::Inode:
  366. return (int)node.inode;
  367. case Column::SymlinkTarget:
  368. return node.symlink_target;
  369. }
  370. }
  371. if (role == Role::Icon) {
  372. return icon_for(node);
  373. }
  374. return {};
  375. }
  376. Icon FileSystemModel::icon_for_file(const mode_t mode, const String& name) const
  377. {
  378. if (S_ISDIR(mode))
  379. return m_directory_icon;
  380. if (S_ISLNK(mode))
  381. return m_symlink_icon;
  382. if (S_ISSOCK(mode))
  383. return m_socket_icon;
  384. if (mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  385. return m_executable_icon;
  386. #define __ENUMERATE_FILETYPE(filetype_name, filetype_extensions...) \
  387. for (auto& extension : Vector<String> { filetype_extensions }) { \
  388. if (name.to_lowercase().ends_with(extension)) \
  389. return m_filetype_##filetype_name##_icon; \
  390. }
  391. ENUMERATE_FILETYPES
  392. #undef __ENUMERATE_FILETYPE
  393. return m_file_icon;
  394. }
  395. Icon FileSystemModel::icon_for(const Node& node) const
  396. {
  397. if (node.name.to_lowercase().ends_with(".png") || node.name.to_lowercase().ends_with(".gif")) {
  398. if (!node.thumbnail) {
  399. if (!const_cast<FileSystemModel*>(this)->fetch_thumbnail_for(node))
  400. return m_filetype_image_icon;
  401. }
  402. return GUI::Icon(m_filetype_image_icon.bitmap_for_size(16), *node.thumbnail);
  403. }
  404. return icon_for_file(node.mode, node.name);
  405. }
  406. static HashMap<String, RefPtr<Gfx::Bitmap>> s_thumbnail_cache;
  407. static RefPtr<Gfx::Bitmap> render_thumbnail(const StringView& path)
  408. {
  409. auto png_bitmap = Gfx::Bitmap::load_from_file(path);
  410. if (!png_bitmap)
  411. return nullptr;
  412. double scale = min(32 / (double)png_bitmap->width(), 32 / (double)png_bitmap->height());
  413. auto thumbnail = Gfx::Bitmap::create(png_bitmap->format(), { 32, 32 });
  414. Gfx::Rect destination = Gfx::Rect(0, 0, (int)(png_bitmap->width() * scale), (int)(png_bitmap->height() * scale));
  415. destination.center_within(thumbnail->rect());
  416. Painter painter(*thumbnail);
  417. painter.draw_scaled_bitmap(destination, *png_bitmap, png_bitmap->rect());
  418. return thumbnail;
  419. }
  420. bool FileSystemModel::fetch_thumbnail_for(const Node& node)
  421. {
  422. // See if we already have the thumbnail
  423. // we're looking for in the cache.
  424. auto path = node.full_path(*this);
  425. auto it = s_thumbnail_cache.find(path);
  426. if (it != s_thumbnail_cache.end()) {
  427. if (!(*it).value)
  428. return false;
  429. node.thumbnail = (*it).value;
  430. return true;
  431. }
  432. // Otherwise, arrange to render the thumbnail
  433. // in background and make it available later.
  434. s_thumbnail_cache.set(path, nullptr);
  435. m_thumbnail_progress_total++;
  436. auto weak_this = make_weak_ptr();
  437. LibThread::BackgroundAction<RefPtr<Gfx::Bitmap>>::create(
  438. [path] {
  439. return render_thumbnail(path);
  440. },
  441. [this, path, weak_this](auto thumbnail) {
  442. s_thumbnail_cache.set(path, move(thumbnail));
  443. // The model was destroyed, no need to update
  444. // progress or call any event handlers.
  445. if (weak_this.is_null())
  446. return;
  447. m_thumbnail_progress++;
  448. if (on_thumbnail_progress)
  449. on_thumbnail_progress(m_thumbnail_progress, m_thumbnail_progress_total);
  450. if (m_thumbnail_progress == m_thumbnail_progress_total) {
  451. m_thumbnail_progress = 0;
  452. m_thumbnail_progress_total = 0;
  453. }
  454. did_update();
  455. });
  456. return false;
  457. }
  458. int FileSystemModel::column_count(const ModelIndex&) const
  459. {
  460. return Column::__Count;
  461. }
  462. String FileSystemModel::column_name(int column) const
  463. {
  464. switch (column) {
  465. case Column::Icon:
  466. return "";
  467. case Column::Name:
  468. return "Name";
  469. case Column::Size:
  470. return "Size";
  471. case Column::Owner:
  472. return "Owner";
  473. case Column::Group:
  474. return "Group";
  475. case Column::Permissions:
  476. return "Mode";
  477. case Column::ModificationTime:
  478. return "Modified";
  479. case Column::Inode:
  480. return "Inode";
  481. case Column::SymlinkTarget:
  482. return "Symlink target";
  483. }
  484. ASSERT_NOT_REACHED();
  485. }
  486. Model::ColumnMetadata FileSystemModel::column_metadata(int column) const
  487. {
  488. switch (column) {
  489. case Column::Icon:
  490. return { 16, Gfx::TextAlignment::Center, nullptr, Model::ColumnMetadata::Sortable::False };
  491. case Column::Name:
  492. return { 120, Gfx::TextAlignment::CenterLeft };
  493. case Column::Size:
  494. return { 80, Gfx::TextAlignment::CenterRight };
  495. case Column::Owner:
  496. return { 50, Gfx::TextAlignment::CenterLeft };
  497. case Column::Group:
  498. return { 50, Gfx::TextAlignment::CenterLeft };
  499. case Column::ModificationTime:
  500. return { 110, Gfx::TextAlignment::CenterLeft };
  501. case Column::Permissions:
  502. return { 65, Gfx::TextAlignment::CenterLeft };
  503. case Column::Inode:
  504. return { 60, Gfx::TextAlignment::CenterRight };
  505. case Column::SymlinkTarget:
  506. return { 120, Gfx::TextAlignment::CenterLeft };
  507. }
  508. ASSERT_NOT_REACHED();
  509. }
  510. bool FileSystemModel::accepts_drag(const ModelIndex& index, const StringView& data_type)
  511. {
  512. if (!index.is_valid())
  513. return false;
  514. if (data_type != "text/uri-list")
  515. return false;
  516. auto& node = this->node(index);
  517. return node.is_directory();
  518. }
  519. }