FilePicker.cpp 16 KB

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