FilePicker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 <LibGfx/FontDatabase.h>
  27. #include <LibGfx/Palette.h>
  28. #include <string.h>
  29. #include <unistd.h>
  30. namespace GUI {
  31. Optional<String> FilePicker::get_open_filepath(Window* parent_window, const String& window_title, const StringView& path, bool folder, ScreenPosition screen_position)
  32. {
  33. auto picker = FilePicker::construct(parent_window, folder ? Mode::OpenFolder : Mode::Open, "", path, screen_position);
  34. if (!window_title.is_null())
  35. picker->set_title(window_title);
  36. if (picker->exec() == Dialog::ExecOK) {
  37. String file_path = picker->selected_file();
  38. if (file_path.is_null())
  39. return {};
  40. return file_path;
  41. }
  42. return {};
  43. }
  44. Optional<String> FilePicker::get_save_filepath(Window* parent_window, const String& title, const String& extension, const StringView& path, ScreenPosition screen_position)
  45. {
  46. auto picker = FilePicker::construct(parent_window, Mode::Save, String::formatted("{}.{}", title, extension), path, screen_position);
  47. if (picker->exec() == Dialog::ExecOK) {
  48. String file_path = picker->selected_file();
  49. if (file_path.is_null())
  50. return {};
  51. return file_path;
  52. }
  53. return {};
  54. }
  55. FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& filename, const StringView& path, ScreenPosition screen_position)
  56. : Dialog(parent_window, screen_position)
  57. , m_model(FileSystemModel::create(path))
  58. , m_mode(mode)
  59. {
  60. switch (m_mode) {
  61. case Mode::Open:
  62. case Mode::OpenMultiple:
  63. case Mode::OpenFolder:
  64. set_title("Open");
  65. set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open.png"));
  66. break;
  67. case Mode::Save:
  68. set_title("Save as");
  69. set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/save.png"));
  70. break;
  71. }
  72. resize(560, 320);
  73. auto& widget = set_main_widget<GUI::Widget>();
  74. if (!widget.load_from_gml(file_picker_dialog_gml))
  75. VERIFY_NOT_REACHED();
  76. auto& toolbar = *widget.find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  77. toolbar.set_has_frame(false);
  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(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"), [this](const Action&) {
  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"), [this](const Action&) {
  110. String value;
  111. if (InputBox::show(this, value, "Enter name:", "New directory") == InputBox::ExecOK && !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", 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_view->on_selection_change = [this] {
  137. auto index = m_view->selection().first();
  138. auto& filter_model = (SortingProxyModel&)*m_view->model();
  139. auto local_index = filter_model.map_to_source(index);
  140. const FileSystemModel::Node& node = m_model->node(local_index);
  141. LexicalPath path { node.full_path() };
  142. auto should_open_folder = m_mode == Mode::OpenFolder;
  143. if (should_open_folder == node.is_directory()) {
  144. m_filename_textbox->set_text(node.name);
  145. } else if (m_mode != Mode::Save) {
  146. m_filename_textbox->clear();
  147. }
  148. };
  149. m_context_menu = GUI::Menu::construct();
  150. m_context_menu->add_action(GUI::Action::create_checkable(
  151. "Show dotfiles", { Mod_Ctrl, Key_H }, [&](auto& action) {
  152. m_model->set_should_show_dotfiles(action.is_checked());
  153. m_model->invalidate();
  154. },
  155. this));
  156. m_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  157. if (!index.is_valid()) {
  158. m_context_menu->popup(event.screen_position());
  159. }
  160. };
  161. auto& ok_button = *widget.find_descendant_of_type_named<GUI::Button>("ok_button");
  162. ok_button.set_text(ok_button_name(m_mode));
  163. ok_button.on_click = [this](auto) {
  164. on_file_return();
  165. };
  166. auto& cancel_button = *widget.find_descendant_of_type_named<GUI::Button>("cancel_button");
  167. cancel_button.set_text("Cancel");
  168. cancel_button.on_click = [this](auto) {
  169. done(ExecCancel);
  170. };
  171. m_view->on_activation = [this](auto& index) {
  172. auto& filter_model = (SortingProxyModel&)*m_view->model();
  173. auto local_index = filter_model.map_to_source(index);
  174. const FileSystemModel::Node& node = m_model->node(local_index);
  175. auto path = node.full_path();
  176. if (node.is_directory() || node.is_symlink_to_directory()) {
  177. set_path(path);
  178. // NOTE: 'node' is invalid from here on
  179. } else {
  180. on_file_return();
  181. }
  182. };
  183. auto& common_locations_frame = *widget.find_descendant_of_type_named<Frame>("common_locations_frame");
  184. common_locations_frame.set_background_role(Gfx::ColorRole::Tray);
  185. m_model->on_directory_change_error = [&](int, char const* error_string) {
  186. m_error_label->set_text(String::formatted("Could not open {}:\n{}", m_model->root_path(), error_string));
  187. m_view->set_active_widget(m_error_label);
  188. m_view->view_as_icons_action().set_enabled(false);
  189. m_view->view_as_table_action().set_enabled(false);
  190. m_view->view_as_columns_action().set_enabled(false);
  191. };
  192. m_model->on_complete = [&] {
  193. m_view->set_active_widget(&m_view->current_view());
  194. for (auto location_button : m_common_location_buttons)
  195. location_button.button.set_checked(m_model->root_path() == location_button.path);
  196. m_view->view_as_icons_action().set_enabled(true);
  197. m_view->view_as_table_action().set_enabled(true);
  198. m_view->view_as_columns_action().set_enabled(true);
  199. };
  200. for (auto& location : CommonLocationsProvider::common_locations()) {
  201. String path = location.path;
  202. auto& button = common_locations_frame.add<GUI::Button>();
  203. button.set_button_style(Gfx::ButtonStyle::Tray);
  204. button.set_foreground_role(Gfx::ColorRole::TrayText);
  205. button.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  206. button.set_text(location.name);
  207. button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  208. button.set_fixed_height(22);
  209. button.set_checkable(true);
  210. button.set_exclusive(true);
  211. button.on_click = [this, path](auto) {
  212. set_path(path);
  213. };
  214. m_common_location_buttons.append({ path, button });
  215. }
  216. m_location_textbox->set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  217. m_model->on_complete();
  218. }
  219. FilePicker::~FilePicker()
  220. {
  221. m_model->unregister_client(*this);
  222. }
  223. void FilePicker::model_did_update(unsigned)
  224. {
  225. m_location_textbox->set_text(m_model->root_path());
  226. }
  227. void FilePicker::on_file_return()
  228. {
  229. auto path = m_filename_textbox->text();
  230. if (!path.starts_with('/')) {
  231. path = LexicalPath::join(m_model->root_path(), path).string();
  232. }
  233. bool file_exists = Core::File::exists(path);
  234. if (!file_exists && (m_mode == Mode::Open || m_mode == Mode::OpenFolder)) {
  235. MessageBox::show(this, String::formatted("No such file or directory: {}", m_filename_textbox->text()), "File not found", MessageBox::Type::Error, MessageBox::InputType::OK);
  236. return;
  237. }
  238. if (file_exists && m_mode == Mode::Save) {
  239. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  240. if (result == MessageBox::ExecCancel)
  241. return;
  242. }
  243. m_selected_file = path;
  244. done(ExecOK);
  245. }
  246. void FilePicker::set_path(const String& path)
  247. {
  248. if (access(path.characters(), R_OK | X_OK) == -1) {
  249. GUI::MessageBox::show(this, String::formatted("Could not open '{}':\n{}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  250. for (auto location_button : m_common_location_buttons)
  251. location_button.button.set_checked(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. }