FilePicker.cpp 12 KB

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