FilePicker.cpp 12 KB

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