Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2022-2023, the SerenityOS developers.
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include "PropertiesWindow.h"
9#include <AK/LexicalPath.h>
10#include <AK/NumberFormat.h>
11#include <Applications/FileManager/DirectoryView.h>
12#include <Applications/FileManager/PropertiesWindowGeneralTabGML.h>
13#include <LibCore/DeprecatedFile.h>
14#include <LibCore/Directory.h>
15#include <LibCore/System.h>
16#include <LibDesktop/Launcher.h>
17#include <LibGUI/BoxLayout.h>
18#include <LibGUI/CheckBox.h>
19#include <LibGUI/FileIconProvider.h>
20#include <LibGUI/FilePicker.h>
21#include <LibGUI/IconView.h>
22#include <LibGUI/LinkLabel.h>
23#include <LibGUI/MessageBox.h>
24#include <LibGUI/SeparatorWidget.h>
25#include <LibGUI/TabWidget.h>
26#include <grp.h>
27#include <pwd.h>
28#include <stdio.h>
29#include <string.h>
30#include <unistd.h>
31
32ErrorOr<NonnullRefPtr<PropertiesWindow>> PropertiesWindow::try_create(DeprecatedString const& path, bool disable_rename, Window* parent)
33{
34 auto window = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) PropertiesWindow(path, parent)));
35 window->set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/properties.png"sv)));
36 TRY(window->create_widgets(disable_rename));
37 return window;
38}
39
40PropertiesWindow::PropertiesWindow(DeprecatedString const& path, Window* parent_window)
41 : Window(parent_window)
42{
43 auto lexical_path = LexicalPath(path);
44
45 m_name = lexical_path.basename();
46 m_path = lexical_path.string();
47 m_parent_path = lexical_path.dirname();
48
49 set_rect({ 0, 0, 360, 420 });
50 set_resizable(false);
51}
52
53ErrorOr<void> PropertiesWindow::create_widgets(bool disable_rename)
54{
55 auto main_widget = TRY(set_main_widget<GUI::Widget>());
56 TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>(4, 6));
57 main_widget->set_fill_with_background_color(true);
58
59 auto tab_widget = TRY(main_widget->try_add<GUI::TabWidget>());
60
61 auto general_tab = TRY(tab_widget->try_add_tab<GUI::Widget>("General"));
62 TRY(general_tab->load_from_gml(properties_window_general_tab_gml));
63
64 m_icon = general_tab->find_descendant_of_type_named<GUI::ImageWidget>("icon");
65
66 m_name_box = general_tab->find_descendant_of_type_named<GUI::TextBox>("name");
67 m_name_box->set_text(m_name);
68 m_name_box->set_mode(disable_rename ? GUI::TextBox::Mode::DisplayOnly : GUI::TextBox::Mode::Editable);
69 m_name_box->on_change = [&]() {
70 m_name_dirty = m_name != m_name_box->text();
71 m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
72 };
73
74 auto* location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("location");
75 location->set_text(m_path);
76 location->on_click = [this] {
77 Desktop::Launcher::open(URL::create_with_file_scheme(m_parent_path, m_name));
78 };
79
80 auto st = TRY(Core::System::lstat(m_path));
81
82 DeprecatedString owner_name;
83 DeprecatedString group_name;
84
85 if (auto* pw = getpwuid(st.st_uid)) {
86 owner_name = pw->pw_name;
87 } else {
88 owner_name = "n/a";
89 }
90
91 if (auto* gr = getgrgid(st.st_gid)) {
92 group_name = gr->gr_name;
93 } else {
94 group_name = "n/a";
95 }
96
97 m_mode = st.st_mode;
98 m_old_mode = st.st_mode;
99
100 auto* type = general_tab->find_descendant_of_type_named<GUI::Label>("type");
101 type->set_text(get_description(m_mode));
102
103 if (S_ISLNK(m_mode)) {
104 auto link_destination_or_error = Core::DeprecatedFile::read_link(m_path);
105 if (link_destination_or_error.is_error()) {
106 perror("readlink");
107 } else {
108 auto link_destination = link_destination_or_error.release_value();
109 auto* link_location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("link_location");
110 link_location->set_text(link_destination);
111 link_location->on_click = [link_destination] {
112 auto link_directory = LexicalPath(link_destination);
113 Desktop::Launcher::open(URL::create_with_file_scheme(link_directory.dirname(), link_directory.basename()));
114 };
115 }
116 } else {
117 auto* link_location_widget = general_tab->find_descendant_of_type_named<GUI::Widget>("link_location_widget");
118 general_tab->remove_child(*link_location_widget);
119 }
120
121 m_size_label = general_tab->find_descendant_of_type_named<GUI::Label>("size");
122 m_size_label->set_text(S_ISDIR(st.st_mode) ? "Calculating..." : human_readable_size_long(st.st_size));
123
124 auto* owner = general_tab->find_descendant_of_type_named<GUI::Label>("owner");
125 owner->set_text(DeprecatedString::formatted("{} ({})", owner_name, st.st_uid));
126
127 auto* group = general_tab->find_descendant_of_type_named<GUI::Label>("group");
128 group->set_text(DeprecatedString::formatted("{} ({})", group_name, st.st_gid));
129
130 auto* created_at = general_tab->find_descendant_of_type_named<GUI::Label>("created_at");
131 created_at->set_text(GUI::FileSystemModel::timestamp_string(st.st_ctime));
132
133 auto* last_modified = general_tab->find_descendant_of_type_named<GUI::Label>("last_modified");
134 last_modified->set_text(GUI::FileSystemModel::timestamp_string(st.st_mtime));
135
136 auto* owner_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_read");
137 auto* owner_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_write");
138 auto* owner_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_execute");
139 TRY(setup_permission_checkboxes(*owner_read, *owner_write, *owner_execute, { S_IRUSR, S_IWUSR, S_IXUSR }, m_mode));
140
141 auto* group_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_read");
142 auto* group_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_write");
143 auto* group_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_execute");
144 TRY(setup_permission_checkboxes(*group_read, *group_write, *group_execute, { S_IRGRP, S_IWGRP, S_IXGRP }, m_mode));
145
146 auto* others_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_read");
147 auto* others_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_write");
148 auto* others_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_execute");
149 TRY(setup_permission_checkboxes(*others_read, *others_write, *others_execute, { S_IROTH, S_IWOTH, S_IXOTH }, m_mode));
150
151 auto button_widget = TRY(main_widget->try_add<GUI::Widget>());
152 TRY(button_widget->try_set_layout<GUI::HorizontalBoxLayout>(GUI::Margins {}, 5));
153 button_widget->set_fixed_height(22);
154
155 TRY(button_widget->add_spacer());
156
157 auto ok_button = TRY(make_button("OK"_short_string, button_widget));
158 ok_button->on_click = [this](auto) {
159 if (apply_changes())
160 close();
161 };
162 auto cancel_button = TRY(make_button("Cancel"_short_string, button_widget));
163 cancel_button->on_click = [this](auto) {
164 close();
165 };
166
167 m_apply_button = TRY(make_button("Apply"_short_string, button_widget));
168 m_apply_button->on_click = [this](auto) { apply_changes(); };
169 m_apply_button->set_enabled(false);
170
171 if (S_ISDIR(m_old_mode)) {
172 m_directory_statistics_calculator = make_ref_counted<DirectoryStatisticsCalculator>(m_path);
173 m_directory_statistics_calculator->on_update = [this, origin_event_loop = &Core::EventLoop::current()](off_t total_size_in_bytes, size_t file_count, size_t directory_count) {
174 origin_event_loop->deferred_invoke([=, weak_this = make_weak_ptr<PropertiesWindow>()] {
175 if (auto strong_this = weak_this.strong_ref())
176 strong_this->m_size_label->set_text(DeprecatedString::formatted("{}\n{} files, {} subdirectories", human_readable_size_long(total_size_in_bytes), file_count, directory_count));
177 });
178 };
179 m_directory_statistics_calculator->start();
180 }
181
182 update();
183 return {};
184}
185
186void PropertiesWindow::update()
187{
188 m_icon->set_bitmap(GUI::FileIconProvider::icon_for_path(make_full_path(m_name), m_mode).bitmap_for_size(32));
189 set_title(DeprecatedString::formatted("{} - Properties", m_name));
190}
191
192void PropertiesWindow::permission_changed(mode_t mask, bool set)
193{
194 if (set) {
195 m_mode |= mask;
196 } else {
197 m_mode &= ~mask;
198 }
199
200 m_permissions_dirty = m_mode != m_old_mode;
201 m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
202}
203
204DeprecatedString PropertiesWindow::make_full_path(DeprecatedString const& name)
205{
206 return DeprecatedString::formatted("{}/{}", m_parent_path, name);
207}
208
209bool PropertiesWindow::apply_changes()
210{
211 if (m_name_dirty) {
212 DeprecatedString new_name = m_name_box->text();
213 DeprecatedString new_file = make_full_path(new_name).characters();
214
215 if (Core::DeprecatedFile::exists(new_file)) {
216 GUI::MessageBox::show(this, DeprecatedString::formatted("A file \"{}\" already exists!", new_name), "Error"sv, GUI::MessageBox::Type::Error);
217 return false;
218 }
219
220 if (rename(make_full_path(m_name).characters(), new_file.characters())) {
221 GUI::MessageBox::show(this, DeprecatedString::formatted("Could not rename file: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
222 return false;
223 }
224
225 m_name = new_name;
226 m_name_dirty = false;
227 update();
228 }
229
230 if (m_permissions_dirty) {
231 if (chmod(make_full_path(m_name).characters(), m_mode)) {
232 GUI::MessageBox::show(this, DeprecatedString::formatted("Could not update permissions: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
233 return false;
234 }
235
236 m_old_mode = m_mode;
237 m_permissions_dirty = false;
238 }
239
240 auto directory_view = parent()->find_descendant_of_type_named<FileManager::DirectoryView>("directory_view");
241 directory_view->refresh();
242
243 update();
244 m_apply_button->set_enabled(false);
245 return true;
246}
247
248ErrorOr<void> PropertiesWindow::setup_permission_checkboxes(GUI::CheckBox& box_read, GUI::CheckBox& box_write, GUI::CheckBox& box_execute, PermissionMasks masks, mode_t mode)
249{
250 auto st = TRY(Core::System::lstat(m_path));
251
252 auto can_edit_checkboxes = st.st_uid == getuid();
253
254 box_read.set_checked(mode & masks.read);
255 box_read.on_checked = [&, masks](bool checked) { permission_changed(masks.read, checked); };
256 box_read.set_enabled(can_edit_checkboxes);
257
258 box_write.set_checked(mode & masks.write);
259 box_write.on_checked = [&, masks](bool checked) { permission_changed(masks.write, checked); };
260 box_write.set_enabled(can_edit_checkboxes);
261
262 box_execute.set_checked(mode & masks.execute);
263 box_execute.on_checked = [&, masks](bool checked) { permission_changed(masks.execute, checked); };
264 box_execute.set_enabled(can_edit_checkboxes);
265
266 return {};
267}
268
269ErrorOr<NonnullRefPtr<GUI::Button>> PropertiesWindow::make_button(String text, GUI::Widget& parent)
270{
271 auto button = TRY(parent.try_add<GUI::Button>(text));
272 button->set_fixed_size(70, 22);
273 return button;
274}
275
276void PropertiesWindow::close()
277{
278 GUI::Window::close();
279 if (m_directory_statistics_calculator)
280 m_directory_statistics_calculator->stop();
281}
282
283PropertiesWindow::DirectoryStatisticsCalculator::DirectoryStatisticsCalculator(DeprecatedString path)
284{
285 m_work_queue.enqueue(path);
286}
287
288void PropertiesWindow::DirectoryStatisticsCalculator::start()
289{
290 using namespace AK::TimeLiterals;
291 VERIFY(!m_background_action);
292
293 m_background_action = Threading::BackgroundAction<int>::construct(
294 [this, strong_this = NonnullRefPtr(*this)](auto& task) -> ErrorOr<int> {
295 auto timer = Core::ElapsedTimer();
296 while (!m_work_queue.is_empty()) {
297 auto base_directory = m_work_queue.dequeue();
298 auto result = Core::Directory::for_each_entry(base_directory, Core::DirIterator::SkipParentAndBaseDir, [&](auto const& entry, auto const& directory) -> ErrorOr<IterationDecision> {
299 if (task.is_canceled())
300 return Error::from_errno(ECANCELED);
301
302 struct stat st = {};
303 if (fstatat(directory.fd(), entry.name.characters(), &st, AT_SYMLINK_NOFOLLOW) < 0) {
304 perror("fstatat");
305 return IterationDecision::Continue;
306 }
307
308 if (S_ISDIR(st.st_mode)) {
309 auto full_path = LexicalPath::join(directory.path().string(), entry.name).string();
310 m_directory_count++;
311 m_work_queue.enqueue(full_path);
312 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
313 m_file_count++;
314 m_total_size_in_bytes += st.st_size;
315 }
316
317 // Show the first update, then show any subsequent updates every 100ms.
318 if (!task.is_canceled() && on_update && (!timer.is_valid() || timer.elapsed_time() > 100_ms)) {
319 timer.start();
320 on_update(m_total_size_in_bytes, m_file_count, m_directory_count);
321 }
322
323 return IterationDecision::Continue;
324 });
325 if (result.is_error() && result.error().code() == ECANCELED)
326 return Error::from_errno(ECANCELED);
327 }
328 return 0;
329 },
330 [this](auto) -> ErrorOr<void> {
331 if (on_update)
332 on_update(m_total_size_in_bytes, m_file_count, m_directory_count);
333
334 return {};
335 },
336 [](auto) {
337 // Ignore the error.
338 });
339}
340
341void PropertiesWindow::DirectoryStatisticsCalculator::stop()
342{
343 VERIFY(m_background_action);
344 m_background_action->cancel();
345}