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