FilePicker.cpp 16 KB

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