FilePicker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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/InputBox.h>
  19. #include <LibGUI/Label.h>
  20. #include <LibGUI/Menu.h>
  21. #include <LibGUI/MessageBox.h>
  22. #include <LibGUI/MultiView.h>
  23. #include <LibGUI/SortingProxyModel.h>
  24. #include <LibGUI/TextBox.h>
  25. #include <LibGUI/Toolbar.h>
  26. #include <LibGfx/FontDatabase.h>
  27. #include <LibGfx/Palette.h>
  28. #include <string.h>
  29. namespace GUI {
  30. Optional<String> FilePicker::get_open_filepath(Window* parent_window, const String& window_title, const StringView& path, bool folder, ScreenPosition screen_position)
  31. {
  32. auto picker = FilePicker::construct(parent_window, folder ? Mode::OpenFolder : Mode::Open, "", path, screen_position);
  33. if (!window_title.is_null())
  34. picker->set_title(window_title);
  35. if (picker->exec() == Dialog::ExecOK) {
  36. String file_path = picker->selected_file();
  37. if (file_path.is_null())
  38. return {};
  39. return file_path;
  40. }
  41. return {};
  42. }
  43. Optional<String> FilePicker::get_save_filepath(Window* parent_window, const String& title, const String& extension, const StringView& path, ScreenPosition screen_position)
  44. {
  45. auto picker = FilePicker::construct(parent_window, Mode::Save, String::formatted("{}.{}", title, extension), path, screen_position);
  46. if (picker->exec() == Dialog::ExecOK) {
  47. String file_path = picker->selected_file();
  48. if (file_path.is_null())
  49. return {};
  50. return file_path;
  51. }
  52. return {};
  53. }
  54. FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& filename, const StringView& path, ScreenPosition screen_position)
  55. : Dialog(parent_window, screen_position)
  56. , m_model(FileSystemModel::create(path))
  57. , m_mode(mode)
  58. {
  59. switch (m_mode) {
  60. case Mode::Open:
  61. case Mode::OpenMultiple:
  62. case Mode::OpenFolder:
  63. set_title("Open");
  64. set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open.png"));
  65. break;
  66. case Mode::Save:
  67. set_title("Save as");
  68. set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/save.png"));
  69. break;
  70. }
  71. resize(560, 320);
  72. auto& widget = set_main_widget<GUI::Widget>();
  73. if (!widget.load_from_gml(file_picker_dialog_gml))
  74. VERIFY_NOT_REACHED();
  75. auto& toolbar = *widget.find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  76. toolbar.set_has_frame(false);
  77. m_location_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("location_textbox");
  78. m_location_textbox->set_text(path);
  79. m_view = *widget.find_descendant_of_type_named<GUI::MultiView>("view");
  80. m_view->set_selection_mode(m_mode == Mode::OpenMultiple ? GUI::AbstractView::SelectionMode::MultiSelection : GUI::AbstractView::SelectionMode::SingleSelection);
  81. m_view->set_model(SortingProxyModel::create(*m_model));
  82. m_view->set_model_column(FileSystemModel::Column::Name);
  83. m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  84. m_view->set_column_visible(FileSystemModel::Column::Owner, true);
  85. m_view->set_column_visible(FileSystemModel::Column::Group, true);
  86. m_view->set_column_visible(FileSystemModel::Column::Permissions, true);
  87. m_view->set_column_visible(FileSystemModel::Column::Inode, true);
  88. m_view->set_column_visible(FileSystemModel::Column::SymlinkTarget, true);
  89. m_model->register_client(*this);
  90. m_error_label = m_view->add<GUI::Label>();
  91. m_error_label->set_font(m_error_label->font().bold_variant());
  92. m_location_textbox->on_return_pressed = [this] {
  93. set_path(m_location_textbox->text());
  94. };
  95. auto open_parent_directory_action = Action::create(
  96. "Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open-parent-directory.png"), [this](const Action&) {
  97. set_path(String::formatted("{}/..", m_model->root_path()));
  98. },
  99. this);
  100. toolbar.add_action(*open_parent_directory_action);
  101. auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
  102. set_path(Core::StandardPaths::home_directory());
  103. },
  104. this);
  105. toolbar.add_action(go_home_action);
  106. toolbar.add_separator();
  107. auto mkdir_action = Action::create(
  108. "New directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/mkdir.png"), [this](const Action&) {
  109. String value;
  110. if (InputBox::show(this, value, "Enter name:", "New directory") == InputBox::ExecOK && !value.is_empty()) {
  111. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_model->root_path(), value));
  112. int rc = mkdir(new_dir_path.characters(), 0777);
  113. if (rc < 0) {
  114. MessageBox::show(this, String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(errno)), "Error", MessageBox::Type::Error);
  115. } else {
  116. m_model->invalidate();
  117. }
  118. }
  119. },
  120. this);
  121. toolbar.add_action(*mkdir_action);
  122. toolbar.add_separator();
  123. toolbar.add_action(m_view->view_as_icons_action());
  124. toolbar.add_action(m_view->view_as_table_action());
  125. toolbar.add_action(m_view->view_as_columns_action());
  126. m_filename_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("filename_textbox");
  127. m_filename_textbox->set_focus(true);
  128. if (m_mode == Mode::Save) {
  129. m_filename_textbox->set_text(filename);
  130. m_filename_textbox->select_all();
  131. }
  132. m_filename_textbox->on_return_pressed = [&] {
  133. on_file_return();
  134. };
  135. m_view->on_selection_change = [this] {
  136. auto index = m_view->selection().first();
  137. auto& filter_model = (SortingProxyModel&)*m_view->model();
  138. auto local_index = filter_model.map_to_source(index);
  139. const FileSystemModel::Node& node = m_model->node(local_index);
  140. LexicalPath path { node.full_path() };
  141. auto should_open_folder = m_mode == Mode::OpenFolder;
  142. if (should_open_folder == node.is_directory()) {
  143. m_filename_textbox->set_text(node.name);
  144. } else if (m_mode != Mode::Save) {
  145. m_filename_textbox->clear();
  146. }
  147. };
  148. m_context_menu = GUI::Menu::construct();
  149. m_context_menu->add_action(GUI::Action::create_checkable(
  150. "Show dotfiles", { Mod_Ctrl, Key_H }, [&](auto& action) {
  151. m_model->set_should_show_dotfiles(action.is_checked());
  152. m_model->invalidate();
  153. },
  154. this));
  155. m_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  156. if (!index.is_valid()) {
  157. m_context_menu->popup(event.screen_position());
  158. }
  159. };
  160. auto& ok_button = *widget.find_descendant_of_type_named<GUI::Button>("ok_button");
  161. ok_button.set_text(ok_button_name(m_mode));
  162. ok_button.on_click = [this](auto) {
  163. on_file_return();
  164. };
  165. auto& cancel_button = *widget.find_descendant_of_type_named<GUI::Button>("cancel_button");
  166. cancel_button.set_text("Cancel");
  167. cancel_button.on_click = [this](auto) {
  168. done(ExecCancel);
  169. };
  170. m_view->on_activation = [this](auto& index) {
  171. auto& filter_model = (SortingProxyModel&)*m_view->model();
  172. auto local_index = filter_model.map_to_source(index);
  173. const FileSystemModel::Node& node = m_model->node(local_index);
  174. auto path = node.full_path();
  175. if (node.is_directory() || node.is_symlink_to_directory()) {
  176. set_path(path);
  177. // NOTE: 'node' is invalid from here on
  178. } else {
  179. on_file_return();
  180. }
  181. };
  182. auto& common_locations_frame = *widget.find_descendant_of_type_named<Frame>("common_locations_frame");
  183. common_locations_frame.set_background_role(Gfx::ColorRole::Tray);
  184. m_model->on_directory_change_error = [&](int, char const* error_string) {
  185. m_error_label->set_text(String::formatted("Could not open {}:\n{}", m_model->root_path(), error_string));
  186. m_view->set_active_widget(m_error_label);
  187. m_view->view_as_icons_action().set_enabled(false);
  188. m_view->view_as_table_action().set_enabled(false);
  189. m_view->view_as_columns_action().set_enabled(false);
  190. };
  191. m_model->on_complete = [&] {
  192. m_view->set_active_widget(&m_view->current_view());
  193. for (auto location_button : m_common_location_buttons)
  194. location_button.button.set_checked(m_model->root_path() == location_button.path);
  195. m_view->view_as_icons_action().set_enabled(true);
  196. m_view->view_as_table_action().set_enabled(true);
  197. m_view->view_as_columns_action().set_enabled(true);
  198. };
  199. for (auto& location : CommonLocationsProvider::common_locations()) {
  200. String path = location.path;
  201. auto& button = common_locations_frame.add<GUI::Button>();
  202. button.set_button_style(Gfx::ButtonStyle::Tray);
  203. button.set_foreground_role(Gfx::ColorRole::TrayText);
  204. button.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  205. button.set_text(location.name);
  206. button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  207. button.set_fixed_height(22);
  208. button.set_checkable(true);
  209. button.set_exclusive(true);
  210. button.on_click = [this, path](auto) {
  211. set_path(path);
  212. };
  213. m_common_location_buttons.append({ path, button });
  214. }
  215. m_location_textbox->set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  216. }
  217. FilePicker::~FilePicker()
  218. {
  219. m_model->unregister_client(*this);
  220. }
  221. void FilePicker::model_did_update(unsigned)
  222. {
  223. m_location_textbox->set_text(m_model->root_path());
  224. }
  225. void FilePicker::on_file_return()
  226. {
  227. auto path = m_filename_textbox->text();
  228. if (!path.starts_with('/')) {
  229. path = LexicalPath::join(m_model->root_path(), path).string();
  230. }
  231. bool file_exists = Core::File::exists(path);
  232. if (!file_exists && (m_mode == Mode::Open || m_mode == Mode::OpenFolder)) {
  233. MessageBox::show(this, String::formatted("No such file or directory: {}", m_filename_textbox->text()), "File not found", MessageBox::Type::Error, MessageBox::InputType::OK);
  234. return;
  235. }
  236. if (file_exists && m_mode == Mode::Save) {
  237. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  238. if (result == MessageBox::ExecCancel)
  239. return;
  240. }
  241. m_selected_file = path;
  242. done(ExecOK);
  243. }
  244. void FilePicker::set_path(const String& path)
  245. {
  246. auto new_path = LexicalPath(path).string();
  247. m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
  248. m_model->set_root_path(new_path);
  249. }
  250. }