FilePicker.cpp 14 KB

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