FilePicker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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, const StringView& path, bool folder)
  49. {
  50. auto picker = FilePicker::construct(parent_window, folder ? Mode::OpenFolder : Mode::Open, "", path);
  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, const StringView& path)
  62. {
  63. auto picker = FilePicker::construct(parent_window, Mode::Save, String::formatted("{}.{}", title, extension), path);
  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. case Mode::OpenFolder:
  81. set_title("Open");
  82. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"));
  83. break;
  84. case Mode::Save:
  85. set_title("Save as");
  86. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"));
  87. break;
  88. }
  89. resize(560, 320);
  90. auto& widget = set_main_widget<GUI::Widget>();
  91. if (!widget.load_from_gml(file_picker_dialog_gml))
  92. VERIFY_NOT_REACHED();
  93. auto& toolbar = *widget.find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  94. toolbar.set_has_frame(false);
  95. m_location_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("location_textbox");
  96. m_location_textbox->set_text(path);
  97. m_view = *widget.find_descendant_of_type_named<GUI::MultiView>("view");
  98. m_view->set_selection_mode(m_mode == Mode::OpenMultiple ? GUI::AbstractView::SelectionMode::MultiSelection : GUI::AbstractView::SelectionMode::SingleSelection);
  99. m_view->set_model(SortingProxyModel::create(*m_model));
  100. m_view->set_model_column(FileSystemModel::Column::Name);
  101. m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  102. m_view->set_column_visible(FileSystemModel::Column::Owner, true);
  103. m_view->set_column_visible(FileSystemModel::Column::Group, true);
  104. m_view->set_column_visible(FileSystemModel::Column::Permissions, true);
  105. m_view->set_column_visible(FileSystemModel::Column::Inode, true);
  106. m_view->set_column_visible(FileSystemModel::Column::SymlinkTarget, true);
  107. m_model->register_client(*this);
  108. m_location_textbox->on_return_pressed = [this] {
  109. set_path(m_location_textbox->text());
  110. };
  111. auto open_parent_directory_action = Action::create(
  112. "Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [this](const Action&) {
  113. set_path(String::formatted("{}/..", m_model->root_path()));
  114. },
  115. this);
  116. toolbar.add_action(*open_parent_directory_action);
  117. auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
  118. set_path(Core::StandardPaths::home_directory());
  119. },
  120. this);
  121. toolbar.add_action(go_home_action);
  122. toolbar.add_separator();
  123. auto mkdir_action = Action::create(
  124. "New directory...", Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this](const Action&) {
  125. String value;
  126. if (InputBox::show(this, value, "Enter name:", "New directory") == InputBox::ExecOK && !value.is_empty()) {
  127. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_model->root_path(), value));
  128. int rc = mkdir(new_dir_path.characters(), 0777);
  129. if (rc < 0) {
  130. MessageBox::show(this, String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(errno)), "Error", MessageBox::Type::Error);
  131. } else {
  132. m_model->update();
  133. }
  134. }
  135. },
  136. this);
  137. toolbar.add_action(*mkdir_action);
  138. toolbar.add_separator();
  139. toolbar.add_action(m_view->view_as_icons_action());
  140. toolbar.add_action(m_view->view_as_table_action());
  141. toolbar.add_action(m_view->view_as_columns_action());
  142. m_filename_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("filename_textbox");
  143. m_filename_textbox->set_focus(true);
  144. if (m_mode == Mode::Save) {
  145. m_filename_textbox->set_text(file_name);
  146. m_filename_textbox->select_all();
  147. }
  148. m_filename_textbox->on_return_pressed = [&] {
  149. on_file_return();
  150. };
  151. m_view->on_selection_change = [this] {
  152. auto index = m_view->selection().first();
  153. auto& filter_model = (SortingProxyModel&)*m_view->model();
  154. auto local_index = filter_model.map_to_source(index);
  155. const FileSystemModel::Node& node = m_model->node(local_index);
  156. LexicalPath path { node.full_path() };
  157. auto should_open_folder = m_mode == Mode::OpenFolder;
  158. if (should_open_folder == node.is_directory()) {
  159. m_filename_textbox->set_text(node.name);
  160. } else {
  161. m_filename_textbox->clear();
  162. }
  163. };
  164. m_context_menu = GUI::Menu::construct();
  165. m_context_menu->add_action(GUI::Action::create_checkable("Show dotfiles", [&](auto& action) {
  166. m_model->set_should_show_dotfiles(action.is_checked());
  167. m_model->update();
  168. }));
  169. m_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  170. if (!index.is_valid()) {
  171. m_context_menu->popup(event.screen_position());
  172. }
  173. };
  174. auto& ok_button = *widget.find_descendant_of_type_named<GUI::Button>("ok_button");
  175. ok_button.set_text(ok_button_name(m_mode));
  176. ok_button.on_click = [this](auto) {
  177. on_file_return();
  178. };
  179. auto& cancel_button = *widget.find_descendant_of_type_named<GUI::Button>("cancel_button");
  180. cancel_button.set_text("Cancel");
  181. cancel_button.on_click = [this](auto) {
  182. done(ExecCancel);
  183. };
  184. m_view->on_activation = [this](auto& index) {
  185. auto& filter_model = (SortingProxyModel&)*m_view->model();
  186. auto local_index = filter_model.map_to_source(index);
  187. const FileSystemModel::Node& node = m_model->node(local_index);
  188. auto path = node.full_path();
  189. if (node.is_directory() || node.is_symlink_to_directory()) {
  190. set_path(path);
  191. // NOTE: 'node' is invalid from here on
  192. } else {
  193. on_file_return();
  194. }
  195. };
  196. auto& common_locations_frame = *widget.find_descendant_of_type_named<GUI::Frame>("common_locations_frame");
  197. common_locations_frame.set_background_role(Gfx::ColorRole::Tray);
  198. auto add_common_location_button = [&](auto& name, String path) -> GUI::Button& {
  199. auto& button = common_locations_frame.add<GUI::Button>();
  200. button.set_button_style(Gfx::ButtonStyle::Tray);
  201. button.set_foreground_role(Gfx::ColorRole::TrayText);
  202. button.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  203. button.set_text(move(name));
  204. button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  205. button.set_fixed_height(22);
  206. button.set_checkable(true);
  207. button.set_exclusive(true);
  208. button.on_click = [this, path] {
  209. set_path(path);
  210. };
  211. return button;
  212. };
  213. auto& root_button = add_common_location_button("Root", "/");
  214. auto& home_button = add_common_location_button("Home", Core::StandardPaths::home_directory());
  215. auto& desktop_button = add_common_location_button("Desktop", Core::StandardPaths::desktop_directory());
  216. m_model->on_complete = [&] {
  217. if (m_model->root_path() == Core::StandardPaths::home_directory()) {
  218. home_button.set_checked(true);
  219. } else if (m_model->root_path() == Core::StandardPaths::desktop_directory()) {
  220. desktop_button.set_checked(true);
  221. } else if (m_model->root_path() == "/") {
  222. root_button.set_checked(true);
  223. } else {
  224. home_button.set_checked(false);
  225. desktop_button.set_checked(false);
  226. root_button.set_checked(false);
  227. }
  228. };
  229. set_path(path);
  230. }
  231. FilePicker::~FilePicker()
  232. {
  233. m_model->unregister_client(*this);
  234. }
  235. void FilePicker::model_did_update(unsigned)
  236. {
  237. m_location_textbox->set_text(m_model->root_path());
  238. }
  239. void FilePicker::on_file_return()
  240. {
  241. LexicalPath path(String::formatted("{}/{}", m_model->root_path(), m_filename_textbox->text()));
  242. if (Core::File::exists(path.string()) && m_mode == Mode::Save) {
  243. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  244. if (result == MessageBox::ExecCancel)
  245. return;
  246. }
  247. m_selected_file = path;
  248. done(ExecOK);
  249. }
  250. void FilePicker::set_path(const String& path)
  251. {
  252. auto new_path = LexicalPath(path).string();
  253. m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
  254. m_model->set_root_path(new_path);
  255. }
  256. }