FilePicker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/LexicalPath.h>
  28. #include <LibCore/File.h>
  29. #include <LibCore/StandardPaths.h>
  30. #include <LibGUI/Action.h>
  31. #include <LibGUI/BoxLayout.h>
  32. #include <LibGUI/Button.h>
  33. #include <LibGUI/FileIconProvider.h>
  34. #include <LibGUI/FilePicker.h>
  35. #include <LibGUI/FilePickerDialogGML.h>
  36. #include <LibGUI/FileSystemModel.h>
  37. #include <LibGUI/InputBox.h>
  38. #include <LibGUI/Menu.h>
  39. #include <LibGUI/MessageBox.h>
  40. #include <LibGUI/MultiView.h>
  41. #include <LibGUI/SortingProxyModel.h>
  42. #include <LibGUI/TextBox.h>
  43. #include <LibGUI/ToolBar.h>
  44. #include <LibGfx/FontDatabase.h>
  45. #include <LibGfx/Palette.h>
  46. #include <string.h>
  47. namespace GUI {
  48. Optional<String> FilePicker::get_open_filepath(Window* parent_window, const String& window_title)
  49. {
  50. auto picker = FilePicker::construct(parent_window, Mode::Open);
  51. if (!window_title.is_null())
  52. picker->set_title(window_title);
  53. if (picker->exec() == Dialog::ExecOK) {
  54. String file_path = picker->selected_file().string();
  55. if (file_path.is_null())
  56. return {};
  57. return file_path;
  58. }
  59. return {};
  60. }
  61. Optional<String> FilePicker::get_save_filepath(Window* parent_window, const String& title, const String& extension)
  62. {
  63. auto picker = FilePicker::construct(parent_window, Mode::Save, String::formatted("{}.{}", title, extension));
  64. if (picker->exec() == Dialog::ExecOK) {
  65. String file_path = picker->selected_file().string();
  66. if (file_path.is_null())
  67. return {};
  68. return file_path;
  69. }
  70. return {};
  71. }
  72. FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& file_name, const StringView& path)
  73. : Dialog(parent_window)
  74. , m_model(FileSystemModel::create())
  75. , m_mode(mode)
  76. {
  77. switch (m_mode) {
  78. case Mode::Open:
  79. case Mode::OpenMultiple:
  80. set_title("Open");
  81. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"));
  82. break;
  83. case Mode::Save:
  84. set_title("Save as");
  85. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"));
  86. break;
  87. }
  88. resize(560, 320);
  89. auto& widget = set_main_widget<GUI::Widget>();
  90. if (!widget.load_from_gml(file_picker_dialog_gml))
  91. VERIFY_NOT_REACHED();
  92. auto& toolbar = *widget.find_descendant_of_type_named<GUI::ToolBar>("toolbar");
  93. toolbar.set_has_frame(false);
  94. m_location_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("location_textbox");
  95. m_location_textbox->set_text(path);
  96. m_view = *widget.find_descendant_of_type_named<GUI::MultiView>("view");
  97. m_view->set_selection_mode(m_mode == Mode::OpenMultiple ? GUI::AbstractView::SelectionMode::MultiSelection : GUI::AbstractView::SelectionMode::SingleSelection);
  98. m_view->set_model(SortingProxyModel::create(*m_model));
  99. m_view->set_model_column(FileSystemModel::Column::Name);
  100. m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  101. m_view->set_column_visible(FileSystemModel::Column::Owner, true);
  102. m_view->set_column_visible(FileSystemModel::Column::Group, true);
  103. m_view->set_column_visible(FileSystemModel::Column::Permissions, true);
  104. m_view->set_column_visible(FileSystemModel::Column::Inode, true);
  105. m_view->set_column_visible(FileSystemModel::Column::SymlinkTarget, true);
  106. m_model->register_client(*this);
  107. m_location_textbox->on_return_pressed = [this] {
  108. set_path(m_location_textbox->text());
  109. };
  110. auto open_parent_directory_action = Action::create(
  111. "Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [this](const Action&) {
  112. set_path(String::formatted("{}/..", m_model->root_path()));
  113. },
  114. this);
  115. toolbar.add_action(*open_parent_directory_action);
  116. auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
  117. set_path(Core::StandardPaths::home_directory());
  118. },
  119. this);
  120. toolbar.add_action(go_home_action);
  121. toolbar.add_separator();
  122. auto mkdir_action = Action::create(
  123. "New directory...", Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this](const Action&) {
  124. String value;
  125. if (InputBox::show(this, value, "Enter name:", "New directory") == InputBox::ExecOK && !value.is_empty()) {
  126. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_model->root_path(), value));
  127. int rc = mkdir(new_dir_path.characters(), 0777);
  128. if (rc < 0) {
  129. MessageBox::show(this, String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(errno)), "Error", MessageBox::Type::Error);
  130. } else {
  131. m_model->update();
  132. }
  133. }
  134. },
  135. this);
  136. toolbar.add_action(*mkdir_action);
  137. toolbar.add_separator();
  138. toolbar.add_action(m_view->view_as_icons_action());
  139. toolbar.add_action(m_view->view_as_table_action());
  140. toolbar.add_action(m_view->view_as_columns_action());
  141. m_filename_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("filename_textbox");
  142. m_filename_textbox->set_focus(true);
  143. if (m_mode == Mode::Save) {
  144. m_filename_textbox->set_text(file_name);
  145. m_filename_textbox->select_all();
  146. }
  147. m_filename_textbox->on_return_pressed = [&] {
  148. on_file_return();
  149. };
  150. m_view->on_selection_change = [this] {
  151. auto index = m_view->selection().first();
  152. auto& filter_model = (SortingProxyModel&)*m_view->model();
  153. auto local_index = filter_model.map_to_source(index);
  154. const FileSystemModel::Node& node = m_model->node(local_index);
  155. LexicalPath path { node.full_path() };
  156. if (!node.is_directory())
  157. m_filename_textbox->set_text(node.name);
  158. };
  159. m_context_menu = GUI::Menu::construct();
  160. m_context_menu->add_action(GUI::Action::create_checkable("Show dotfiles", [&](auto& action) {
  161. m_model->set_should_show_dotfiles(action.is_checked());
  162. m_model->update();
  163. }));
  164. m_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  165. if (!index.is_valid()) {
  166. m_context_menu->popup(event.screen_position());
  167. }
  168. };
  169. auto& ok_button = *widget.find_descendant_of_type_named<GUI::Button>("ok_button");
  170. ok_button.set_text(ok_button_name(m_mode));
  171. ok_button.on_click = [this](auto) {
  172. on_file_return();
  173. };
  174. auto& cancel_button = *widget.find_descendant_of_type_named<GUI::Button>("cancel_button");
  175. cancel_button.set_text("Cancel");
  176. cancel_button.on_click = [this](auto) {
  177. done(ExecCancel);
  178. };
  179. m_view->on_activation = [this](auto& index) {
  180. auto& filter_model = (SortingProxyModel&)*m_view->model();
  181. auto local_index = filter_model.map_to_source(index);
  182. const FileSystemModel::Node& node = m_model->node(local_index);
  183. auto path = node.full_path();
  184. if (node.is_directory()) {
  185. set_path(path);
  186. // NOTE: 'node' is invalid from here on
  187. } else {
  188. on_file_return();
  189. }
  190. };
  191. auto& common_locations_frame = *widget.find_descendant_of_type_named<GUI::Frame>("common_locations_frame");
  192. auto add_common_location_button = [&](auto& name, String path) -> GUI::Button& {
  193. auto& button = common_locations_frame.add<GUI::Button>();
  194. button.set_button_style(Gfx::ButtonStyle::CoolBar);
  195. button.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  196. button.set_text(move(name));
  197. button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  198. button.set_fixed_height(22);
  199. button.set_checkable(true);
  200. button.set_exclusive(true);
  201. button.on_click = [this, path] {
  202. set_path(path);
  203. };
  204. return button;
  205. };
  206. auto& home_button = add_common_location_button("Home", Core::StandardPaths::home_directory());
  207. auto& desktop_button = add_common_location_button("Desktop", Core::StandardPaths::desktop_directory());
  208. auto& root_button = add_common_location_button("Root", "/");
  209. m_model->on_complete = [&] {
  210. if (m_model->root_path() == Core::StandardPaths::home_directory()) {
  211. home_button.set_checked(true);
  212. } else if (m_model->root_path() == Core::StandardPaths::desktop_directory()) {
  213. desktop_button.set_checked(true);
  214. } else if (m_model->root_path() == "/") {
  215. root_button.set_checked(true);
  216. } else {
  217. home_button.set_checked(false);
  218. desktop_button.set_checked(false);
  219. root_button.set_checked(false);
  220. }
  221. };
  222. set_path(path);
  223. }
  224. FilePicker::~FilePicker()
  225. {
  226. m_model->unregister_client(*this);
  227. }
  228. void FilePicker::model_did_update(unsigned)
  229. {
  230. m_location_textbox->set_text(m_model->root_path());
  231. }
  232. void FilePicker::on_file_return()
  233. {
  234. LexicalPath path(String::formatted("{}/{}", m_model->root_path(), m_filename_textbox->text()));
  235. if (Core::File::exists(path.string()) && m_mode == Mode::Save) {
  236. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  237. if (result == MessageBox::ExecCancel)
  238. return;
  239. }
  240. m_selected_file = path;
  241. done(ExecOK);
  242. }
  243. void FilePicker::set_path(const String& path)
  244. {
  245. auto new_path = LexicalPath(path).string();
  246. m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
  247. m_model->set_root_path(new_path);
  248. }
  249. }