FilePicker.cpp 12 KB

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