Serenity Operating System
1/*
2 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Function.h>
8#include <AK/LexicalPath.h>
9#include <LibConfig/Client.h>
10#include <LibCore/DeprecatedFile.h>
11#include <LibCore/StandardPaths.h>
12#include <LibGUI/Action.h>
13#include <LibGUI/BoxLayout.h>
14#include <LibGUI/Button.h>
15#include <LibGUI/CommonLocationsProvider.h>
16#include <LibGUI/FileIconProvider.h>
17#include <LibGUI/FilePicker.h>
18#include <LibGUI/FilePickerDialogGML.h>
19#include <LibGUI/FileSystemModel.h>
20#include <LibGUI/FileTypeFilter.h>
21#include <LibGUI/InputBox.h>
22#include <LibGUI/ItemListModel.h>
23#include <LibGUI/Label.h>
24#include <LibGUI/Menu.h>
25#include <LibGUI/MessageBox.h>
26#include <LibGUI/MultiView.h>
27#include <LibGUI/SortingProxyModel.h>
28#include <LibGUI/TextBox.h>
29#include <LibGUI/Toolbar.h>
30#include <LibGUI/Tray.h>
31#include <LibGUI/Widget.h>
32#include <LibGfx/Font/FontDatabase.h>
33#include <LibGfx/Palette.h>
34#include <string.h>
35#include <unistd.h>
36
37namespace GUI {
38
39Optional<DeprecatedString> FilePicker::get_open_filepath(Window* parent_window, DeprecatedString const& window_title, StringView path, bool folder, ScreenPosition screen_position, Optional<Vector<FileTypeFilter>> allowed_file_types)
40{
41 auto picker = FilePicker::construct(parent_window, folder ? Mode::OpenFolder : Mode::Open, ""sv, path, screen_position, move(allowed_file_types));
42
43 if (!window_title.is_null())
44 picker->set_title(window_title);
45
46 if (picker->exec() == ExecResult::OK) {
47 DeprecatedString file_path = picker->selected_file();
48
49 if (file_path.is_null())
50 return {};
51
52 return file_path;
53 }
54 return {};
55}
56
57Optional<DeprecatedString> FilePicker::get_save_filepath(Window* parent_window, DeprecatedString const& title, DeprecatedString const& extension, StringView path, ScreenPosition screen_position)
58{
59 auto picker = FilePicker::construct(parent_window, Mode::Save, DeprecatedString::formatted("{}.{}", title, extension), path, screen_position);
60
61 if (picker->exec() == ExecResult::OK) {
62 DeprecatedString file_path = picker->selected_file();
63
64 if (file_path.is_null())
65 return {};
66
67 return file_path;
68 }
69 return {};
70}
71
72FilePicker::FilePicker(Window* parent_window, Mode mode, StringView filename, StringView path, ScreenPosition screen_position, Optional<Vector<FileTypeFilter>> allowed_file_types)
73 : Dialog(parent_window, screen_position)
74 , m_model(FileSystemModel::create(path))
75 , m_allowed_file_types(move(allowed_file_types))
76 , m_mode(mode)
77{
78 switch (m_mode) {
79 case Mode::Open:
80 case Mode::OpenMultiple:
81 case Mode::OpenFolder:
82 set_title("Open");
83 set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"sv).release_value_but_fixme_should_propagate_errors());
84 break;
85 case Mode::Save:
86 set_title("Save as");
87 set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/save-as.png"sv).release_value_but_fixme_should_propagate_errors());
88 break;
89 }
90 resize(560, 320);
91
92 auto widget = set_main_widget<GUI::Widget>().release_value_but_fixme_should_propagate_errors();
93 widget->load_from_gml(file_picker_dialog_gml).release_value_but_fixme_should_propagate_errors();
94
95 auto& toolbar = *widget->find_descendant_of_type_named<GUI::Toolbar>("toolbar");
96
97 m_location_textbox = *widget->find_descendant_of_type_named<GUI::TextBox>("location_textbox");
98 m_location_textbox->set_text(path);
99
100 m_view = *widget->find_descendant_of_type_named<GUI::MultiView>("view");
101 m_view->set_selection_mode(m_mode == Mode::OpenMultiple ? GUI::AbstractView::SelectionMode::MultiSelection : GUI::AbstractView::SelectionMode::SingleSelection);
102 m_view->set_model(MUST(SortingProxyModel::create(*m_model)));
103 m_view->set_model_column(FileSystemModel::Column::Name);
104 m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
105 m_view->set_column_visible(FileSystemModel::Column::User, true);
106 m_view->set_column_visible(FileSystemModel::Column::Group, true);
107 m_view->set_column_visible(FileSystemModel::Column::Permissions, true);
108 m_view->set_column_visible(FileSystemModel::Column::Inode, true);
109 m_view->set_column_visible(FileSystemModel::Column::SymlinkTarget, true);
110
111 m_model->register_client(*this);
112
113 m_error_label = m_view->add<GUI::Label>();
114 m_error_label->set_font(m_error_label->font().bold_variant());
115
116 m_location_textbox->on_return_pressed = [this] {
117 set_path(m_location_textbox->text());
118 };
119
120 auto* file_types_filters_combo = widget->find_descendant_of_type_named<GUI::ComboBox>("allowed_file_type_filters_combo");
121
122 if (m_allowed_file_types.has_value()) {
123 for (auto& filter : *m_allowed_file_types) {
124 if (!filter.extensions.has_value()) {
125 m_allowed_file_types_names.append(filter.name);
126 continue;
127 }
128
129 StringBuilder extension_list;
130 extension_list.join("; "sv, *filter.extensions);
131 m_allowed_file_types_names.append(DeprecatedString::formatted("{} ({})", filter.name, extension_list.to_deprecated_string()));
132 }
133
134 file_types_filters_combo->set_model(*GUI::ItemListModel<DeprecatedString, Vector<DeprecatedString>>::create(m_allowed_file_types_names));
135 file_types_filters_combo->on_change = [this](DeprecatedString const&, GUI::ModelIndex const& index) {
136 m_model->set_allowed_file_extensions((*m_allowed_file_types)[index.row()].extensions);
137 };
138 file_types_filters_combo->set_selected_index(0);
139 } else {
140 auto* file_types_filter_label = widget->find_descendant_of_type_named<GUI::Label>("allowed_file_types_label");
141 auto& spacer = file_types_filter_label->parent_widget()->add<GUI::Widget>();
142 spacer.set_fixed_height(22);
143 file_types_filter_label->remove_from_parent();
144
145 file_types_filters_combo->parent_widget()->insert_child_before(GUI::Widget::construct(), *file_types_filters_combo);
146
147 file_types_filters_combo->remove_from_parent();
148 }
149
150 auto open_parent_directory_action = Action::create(
151 "Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"sv).release_value_but_fixme_should_propagate_errors(), [this](Action const&) {
152 set_path(DeprecatedString::formatted("{}/..", m_model->root_path()));
153 },
154 this);
155 toolbar.add_action(*open_parent_directory_action);
156
157 auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
158 set_path(Core::StandardPaths::home_directory());
159 },
160 this);
161 toolbar.add_action(go_home_action);
162 toolbar.add_separator();
163
164 auto mkdir_action = Action::create(
165 "New directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"sv).release_value_but_fixme_should_propagate_errors(), [this](Action const&) {
166 DeprecatedString value;
167 if (InputBox::show(this, value, "Enter name:"sv, "New directory"sv, GUI::InputType::NonemptyText) == InputBox::ExecResult::OK) {
168 auto new_dir_path = LexicalPath::canonicalized_path(DeprecatedString::formatted("{}/{}", m_model->root_path(), value));
169 int rc = mkdir(new_dir_path.characters(), 0777);
170 if (rc < 0) {
171 MessageBox::show(this, DeprecatedString::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(errno)), "Error"sv, MessageBox::Type::Error);
172 } else {
173 m_model->invalidate();
174 }
175 }
176 },
177 this);
178
179 toolbar.add_action(*mkdir_action);
180
181 toolbar.add_separator();
182
183 toolbar.add_action(m_view->view_as_icons_action());
184 toolbar.add_action(m_view->view_as_table_action());
185 toolbar.add_action(m_view->view_as_columns_action());
186
187 m_filename_textbox = *widget->find_descendant_of_type_named<GUI::TextBox>("filename_textbox");
188 m_filename_textbox->set_focus(true);
189 if (m_mode == Mode::Save) {
190 LexicalPath lexical_filename { filename };
191 m_filename_textbox->set_text(filename);
192
193 if (auto extension = lexical_filename.extension(); !extension.is_empty()) {
194 TextPosition start_of_filename { 0, 0 };
195 TextPosition end_of_filename { 0, filename.length() - extension.length() - 1 };
196
197 m_filename_textbox->set_selection({ end_of_filename, start_of_filename });
198 } else {
199 m_filename_textbox->select_all();
200 }
201 }
202 m_filename_textbox->on_return_pressed = [&] {
203 on_file_return();
204 };
205
206 m_context_menu = GUI::Menu::construct();
207
208 m_context_menu->add_action(mkdir_action);
209 m_context_menu->add_separator();
210
211 auto show_dotfiles = GUI::Action::create_checkable(
212 "Show dotfiles", { Mod_Ctrl, Key_H }, [&](auto& action) {
213 m_model->set_should_show_dotfiles(action.is_checked());
214 m_model->invalidate();
215 },
216 this);
217 auto show_dotfiles_preset = Config::read_bool("FileManager"sv, "DirectoryView"sv, "ShowDotFiles"sv, false);
218 if (show_dotfiles_preset)
219 show_dotfiles->activate();
220
221 m_context_menu->add_action(show_dotfiles);
222
223 m_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
224 if (!index.is_valid()) {
225 m_context_menu->popup(event.screen_position());
226 }
227 };
228
229 auto& ok_button = *widget->find_descendant_of_type_named<GUI::Button>("ok_button");
230 ok_button.set_text(ok_button_name(m_mode));
231 ok_button.on_click = [this](auto) {
232 on_file_return();
233 };
234 ok_button.set_enabled(m_mode == Mode::OpenFolder || !m_filename_textbox->text().is_empty());
235
236 auto& cancel_button = *widget->find_descendant_of_type_named<GUI::Button>("cancel_button");
237 cancel_button.set_text("Cancel"_short_string);
238 cancel_button.on_click = [this](auto) {
239 done(ExecResult::Cancel);
240 };
241
242 m_filename_textbox->on_change = [&] {
243 ok_button.set_enabled(m_mode == Mode::OpenFolder || !m_filename_textbox->text().is_empty());
244 };
245
246 m_view->on_selection_change = [this] {
247 auto index = m_view->selection().first();
248 auto& filter_model = (SortingProxyModel&)*m_view->model();
249 auto local_index = filter_model.map_to_source(index);
250 const FileSystemModel::Node& node = m_model->node(local_index);
251
252 auto should_open_folder = m_mode == Mode::OpenFolder;
253 if (should_open_folder == node.is_directory()) {
254 m_filename_textbox->set_text(node.name);
255 } else if (m_mode != Mode::Save) {
256 m_filename_textbox->clear();
257 }
258 };
259
260 m_view->on_activation = [this](auto& index) {
261 auto& filter_model = (SortingProxyModel&)*m_view->model();
262 auto local_index = filter_model.map_to_source(index);
263 const FileSystemModel::Node& node = m_model->node(local_index);
264 auto path = node.full_path();
265
266 if (node.is_directory() || node.is_symlink_to_directory()) {
267 set_path(path);
268 // NOTE: 'node' is invalid from here on
269 } else {
270 on_file_return();
271 }
272 };
273
274 m_model->on_directory_change_error = [&](int, char const* error_string) {
275 m_error_label->set_text(DeprecatedString::formatted("Could not open {}:\n{}", m_model->root_path(), error_string));
276 m_view->set_active_widget(m_error_label);
277
278 m_view->view_as_icons_action().set_enabled(false);
279 m_view->view_as_table_action().set_enabled(false);
280 m_view->view_as_columns_action().set_enabled(false);
281 };
282
283 auto& common_locations_tray = *widget->find_descendant_of_type_named<GUI::Tray>("common_locations_tray");
284 m_model->on_complete = [&] {
285 m_view->set_active_widget(&m_view->current_view());
286 for (auto& location_button : m_common_location_buttons)
287 common_locations_tray.set_item_checked(location_button.tray_item_index, m_model->root_path() == location_button.path);
288
289 m_view->view_as_icons_action().set_enabled(true);
290 m_view->view_as_table_action().set_enabled(true);
291 m_view->view_as_columns_action().set_enabled(true);
292 };
293
294 common_locations_tray.on_item_activation = [this](DeprecatedString const& path) {
295 set_path(path);
296 };
297 for (auto& location : CommonLocationsProvider::common_locations()) {
298 auto index = common_locations_tray.add_item(location.name, FileIconProvider::icon_for_path(location.path).bitmap_for_size(16), location.path);
299 m_common_location_buttons.append({ location.path, index });
300 }
301
302 m_location_textbox->set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
303 m_model->on_complete();
304}
305
306FilePicker::~FilePicker()
307{
308 m_model->unregister_client(*this);
309}
310
311void FilePicker::model_did_update(unsigned)
312{
313 m_location_textbox->set_text(m_model->root_path());
314}
315
316void FilePicker::on_file_return()
317{
318 auto path = m_filename_textbox->text();
319 if (!path.starts_with('/')) {
320 path = LexicalPath::join(m_model->root_path(), path).string();
321 }
322
323 bool file_exists = Core::DeprecatedFile::exists(path);
324
325 if (!file_exists && (m_mode == Mode::Open || m_mode == Mode::OpenFolder)) {
326 MessageBox::show(this, DeprecatedString::formatted("No such file or directory: {}", m_filename_textbox->text()), "File not found"sv, MessageBox::Type::Error, MessageBox::InputType::OK);
327 return;
328 }
329
330 if (file_exists && m_mode == Mode::Save) {
331 auto result = MessageBox::show(this, "File already exists. Overwrite?"sv, "Existing File"sv, MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
332 if (result == MessageBox::ExecResult::Cancel)
333 return;
334 }
335
336 m_selected_file = path;
337 done(ExecResult::OK);
338}
339
340void FilePicker::set_path(DeprecatedString const& path)
341{
342 if (access(path.characters(), R_OK | X_OK) == -1) {
343 GUI::MessageBox::show(this, DeprecatedString::formatted("Could not open '{}':\n{}", path, strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
344 auto& common_locations_tray = *find_descendant_of_type_named<GUI::Tray>("common_locations_tray");
345 for (auto& location_button : m_common_location_buttons)
346 common_locations_tray.set_item_checked(location_button.tray_item_index, m_model->root_path() == location_button.path);
347 return;
348 }
349
350 auto new_path = LexicalPath(path).string();
351 m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
352 m_model->set_root_path(new_path);
353}
354
355}