summaryrefslogtreecommitdiff
path: root/Userland/Applications/FileManager/PropertiesWindow.cpp
blob: afebbe3700a8b457d720e03ddf61f2816af6e12d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2022-2023, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "PropertiesWindow.h"
#include <AK/LexicalPath.h>
#include <AK/NumberFormat.h>
#include <Applications/FileManager/DirectoryView.h>
#include <Applications/FileManager/PropertiesWindowGeneralTabGML.h>
#include <LibCore/DeprecatedFile.h>
#include <LibCore/DirIterator.h>
#include <LibCore/System.h>
#include <LibDesktop/Launcher.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/CheckBox.h>
#include <LibGUI/FileIconProvider.h>
#include <LibGUI/FilePicker.h>
#include <LibGUI/IconView.h>
#include <LibGUI/LinkLabel.h>
#include <LibGUI/MessageBox.h>
#include <LibGUI/SeparatorWidget.h>
#include <LibGUI/TabWidget.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

ErrorOr<NonnullRefPtr<PropertiesWindow>> PropertiesWindow::try_create(DeprecatedString const& path, bool disable_rename, Window* parent)
{
    auto window = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) PropertiesWindow(path, parent)));
    window->set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/properties.png"sv)));
    TRY(window->create_widgets(disable_rename));
    return window;
}

PropertiesWindow::PropertiesWindow(DeprecatedString const& path, Window* parent_window)
    : Window(parent_window)
{
    auto lexical_path = LexicalPath(path);

    m_name = lexical_path.basename();
    m_path = lexical_path.string();
    m_parent_path = lexical_path.dirname();

    set_rect({ 0, 0, 360, 420 });
    set_resizable(false);
}

ErrorOr<void> PropertiesWindow::create_widgets(bool disable_rename)
{
    auto main_widget = TRY(set_main_widget<GUI::Widget>());
    (void)TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>(4, 6));
    main_widget->set_fill_with_background_color(true);

    auto tab_widget = TRY(main_widget->try_add<GUI::TabWidget>());

    auto general_tab = TRY(tab_widget->try_add_tab<GUI::Widget>("General"));
    TRY(general_tab->load_from_gml(properties_window_general_tab_gml));

    m_icon = general_tab->find_descendant_of_type_named<GUI::ImageWidget>("icon");

    m_name_box = general_tab->find_descendant_of_type_named<GUI::TextBox>("name");
    m_name_box->set_text(m_name);
    m_name_box->set_mode(disable_rename ? GUI::TextBox::Mode::DisplayOnly : GUI::TextBox::Mode::Editable);
    m_name_box->on_change = [&]() {
        m_name_dirty = m_name != m_name_box->text();
        m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
    };

    auto* location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("location");
    location->set_text(m_path);
    location->on_click = [this] {
        Desktop::Launcher::open(URL::create_with_file_scheme(m_parent_path, m_name));
    };

    auto st = TRY(Core::System::lstat(m_path));

    DeprecatedString owner_name;
    DeprecatedString group_name;

    if (auto* pw = getpwuid(st.st_uid)) {
        owner_name = pw->pw_name;
    } else {
        owner_name = "n/a";
    }

    if (auto* gr = getgrgid(st.st_gid)) {
        group_name = gr->gr_name;
    } else {
        group_name = "n/a";
    }

    m_mode = st.st_mode;
    m_old_mode = st.st_mode;

    auto* type = general_tab->find_descendant_of_type_named<GUI::Label>("type");
    type->set_text(get_description(m_mode));

    if (S_ISLNK(m_mode)) {
        auto link_destination_or_error = Core::DeprecatedFile::read_link(m_path);
        if (link_destination_or_error.is_error()) {
            perror("readlink");
        } else {
            auto link_destination = link_destination_or_error.release_value();
            auto* link_location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("link_location");
            link_location->set_text(link_destination);
            link_location->on_click = [link_destination] {
                auto link_directory = LexicalPath(link_destination);
                Desktop::Launcher::open(URL::create_with_file_scheme(link_directory.dirname(), link_directory.basename()));
            };
        }
    } else {
        auto* link_location_widget = general_tab->find_descendant_of_type_named<GUI::Widget>("link_location_widget");
        general_tab->remove_child(*link_location_widget);
    }

    m_size_label = general_tab->find_descendant_of_type_named<GUI::Label>("size");
    m_size_label->set_text(S_ISDIR(st.st_mode) ? "Calculating..." : human_readable_size_long(st.st_size));

    auto* owner = general_tab->find_descendant_of_type_named<GUI::Label>("owner");
    owner->set_text(DeprecatedString::formatted("{} ({})", owner_name, st.st_uid));

    auto* group = general_tab->find_descendant_of_type_named<GUI::Label>("group");
    group->set_text(DeprecatedString::formatted("{} ({})", group_name, st.st_gid));

    auto* created_at = general_tab->find_descendant_of_type_named<GUI::Label>("created_at");
    created_at->set_text(GUI::FileSystemModel::timestamp_string(st.st_ctime));

    auto* last_modified = general_tab->find_descendant_of_type_named<GUI::Label>("last_modified");
    last_modified->set_text(GUI::FileSystemModel::timestamp_string(st.st_mtime));

    auto* owner_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_read");
    auto* owner_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_write");
    auto* owner_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_execute");
    TRY(setup_permission_checkboxes(*owner_read, *owner_write, *owner_execute, { S_IRUSR, S_IWUSR, S_IXUSR }, m_mode));

    auto* group_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_read");
    auto* group_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_write");
    auto* group_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_execute");
    TRY(setup_permission_checkboxes(*group_read, *group_write, *group_execute, { S_IRGRP, S_IWGRP, S_IXGRP }, m_mode));

    auto* others_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_read");
    auto* others_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_write");
    auto* others_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_execute");
    TRY(setup_permission_checkboxes(*others_read, *others_write, *others_execute, { S_IROTH, S_IWOTH, S_IXOTH }, m_mode));

    auto button_widget = TRY(main_widget->try_add<GUI::Widget>());
    (void)TRY(button_widget->try_set_layout<GUI::HorizontalBoxLayout>(GUI::Margins {}, 5));
    button_widget->set_fixed_height(22);

    TRY(button_widget->add_spacer());

    auto ok_button = TRY(make_button(String::from_utf8_short_string("OK"sv), button_widget));
    ok_button->on_click = [this](auto) {
        if (apply_changes())
            close();
    };
    auto cancel_button = TRY(make_button(String::from_utf8_short_string("Cancel"sv), button_widget));
    cancel_button->on_click = [this](auto) {
        close();
    };

    m_apply_button = TRY(make_button(String::from_utf8_short_string("Apply"sv), button_widget));
    m_apply_button->on_click = [this](auto) { apply_changes(); };
    m_apply_button->set_enabled(false);

    if (S_ISDIR(m_old_mode)) {
        m_directory_statistics_calculator = make_ref_counted<DirectoryStatisticsCalculator>(m_path);
        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) {
            origin_event_loop->deferred_invoke([=, weak_this = make_weak_ptr<PropertiesWindow>()] {
                if (auto strong_this = weak_this.strong_ref())
                    strong_this->m_size_label->set_text(DeprecatedString::formatted("{}\n{} files, {} subdirectories", human_readable_size_long(total_size_in_bytes), file_count, directory_count));
            });
        };
        m_directory_statistics_calculator->start();
    }

    update();
    return {};
}

void PropertiesWindow::update()
{
    m_icon->set_bitmap(GUI::FileIconProvider::icon_for_path(make_full_path(m_name), m_mode).bitmap_for_size(32));
    set_title(DeprecatedString::formatted("{} - Properties", m_name));
}

void PropertiesWindow::permission_changed(mode_t mask, bool set)
{
    if (set) {
        m_mode |= mask;
    } else {
        m_mode &= ~mask;
    }

    m_permissions_dirty = m_mode != m_old_mode;
    m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
}

DeprecatedString PropertiesWindow::make_full_path(DeprecatedString const& name)
{
    return DeprecatedString::formatted("{}/{}", m_parent_path, name);
}

bool PropertiesWindow::apply_changes()
{
    if (m_name_dirty) {
        DeprecatedString new_name = m_name_box->text();
        DeprecatedString new_file = make_full_path(new_name).characters();

        if (Core::DeprecatedFile::exists(new_file)) {
            GUI::MessageBox::show(this, DeprecatedString::formatted("A file \"{}\" already exists!", new_name), "Error"sv, GUI::MessageBox::Type::Error);
            return false;
        }

        if (rename(make_full_path(m_name).characters(), new_file.characters())) {
            GUI::MessageBox::show(this, DeprecatedString::formatted("Could not rename file: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
            return false;
        }

        m_name = new_name;
        m_name_dirty = false;
        update();
    }

    if (m_permissions_dirty) {
        if (chmod(make_full_path(m_name).characters(), m_mode)) {
            GUI::MessageBox::show(this, DeprecatedString::formatted("Could not update permissions: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
            return false;
        }

        m_old_mode = m_mode;
        m_permissions_dirty = false;
    }

    auto directory_view = parent()->find_descendant_of_type_named<FileManager::DirectoryView>("directory_view");
    directory_view->refresh();

    update();
    m_apply_button->set_enabled(false);
    return true;
}

ErrorOr<void> PropertiesWindow::setup_permission_checkboxes(GUI::CheckBox& box_read, GUI::CheckBox& box_write, GUI::CheckBox& box_execute, PermissionMasks masks, mode_t mode)
{
    auto st = TRY(Core::System::lstat(m_path));

    auto can_edit_checkboxes = st.st_uid == getuid();

    box_read.set_checked(mode & masks.read);
    box_read.on_checked = [&, masks](bool checked) { permission_changed(masks.read, checked); };
    box_read.set_enabled(can_edit_checkboxes);

    box_write.set_checked(mode & masks.write);
    box_write.on_checked = [&, masks](bool checked) { permission_changed(masks.write, checked); };
    box_write.set_enabled(can_edit_checkboxes);

    box_execute.set_checked(mode & masks.execute);
    box_execute.on_checked = [&, masks](bool checked) { permission_changed(masks.execute, checked); };
    box_execute.set_enabled(can_edit_checkboxes);

    return {};
}

ErrorOr<NonnullRefPtr<GUI::Button>> PropertiesWindow::make_button(String text, GUI::Widget& parent)
{
    auto button = TRY(parent.try_add<GUI::Button>(text));
    button->set_fixed_size(70, 22);
    return button;
}

void PropertiesWindow::close()
{
    GUI::Window::close();
    if (m_directory_statistics_calculator)
        m_directory_statistics_calculator->stop();
}

PropertiesWindow::DirectoryStatisticsCalculator::DirectoryStatisticsCalculator(DeprecatedString path)
{
    m_work_queue.enqueue(path);
}

void PropertiesWindow::DirectoryStatisticsCalculator::start()
{
    using namespace AK::TimeLiterals;
    VERIFY(!m_background_action);

    m_background_action = Threading::BackgroundAction<int>::construct(
        [this, strong_this = NonnullRefPtr(*this)](auto& task) {
            auto timer = Core::ElapsedTimer();
            while (!m_work_queue.is_empty()) {
                auto base_directory = m_work_queue.dequeue();
                Core::DirIterator di(base_directory, Core::DirIterator::SkipParentAndBaseDir);
                while (di.has_next()) {
                    if (task.is_cancelled())
                        return ECANCELED;

                    auto path = di.next_path();
                    struct stat st = {};
                    if (fstatat(di.fd(), path.characters(), &st, AT_SYMLINK_NOFOLLOW) < 0) {
                        perror("fstatat");
                        continue;
                    }

                    if (S_ISDIR(st.st_mode)) {
                        auto full_path = LexicalPath::join("/"sv, base_directory, path).string();
                        m_directory_count++;
                        m_work_queue.enqueue(full_path);
                    } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
                        m_file_count++;
                        m_total_size_in_bytes += st.st_size;
                    }

                    // Show the first update, then show any subsequent updates every 100ms.
                    if (!task.is_cancelled() && on_update && (!timer.is_valid() || timer.elapsed_time() > 100_ms)) {
                        timer.start();
                        on_update(m_total_size_in_bytes, m_file_count, m_directory_count);
                    }
                }
            }
            return ESUCCESS;
        },
        [this](auto result) -> ErrorOr<void> {
            if (on_update && result == ESUCCESS)
                on_update(m_total_size_in_bytes, m_file_count, m_directory_count);

            return {};
        });
}

void PropertiesWindow::DirectoryStatisticsCalculator::stop()
{
    VERIFY(m_background_action);
    m_background_action->cancel();
}