FilePicker.cpp 10 KB

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