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 <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_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(ExecCancel);
  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. auto& common_locations_frame = *widget.find_descendant_of_type_named<Frame>("common_locations_frame");
  187. common_locations_frame.set_background_role(Gfx::ColorRole::Tray);
  188. m_model->on_directory_change_error = [&](int, char const* error_string) {
  189. m_error_label->set_text(String::formatted("Could not open {}:\n{}", m_model->root_path(), error_string));
  190. m_view->set_active_widget(m_error_label);
  191. m_view->view_as_icons_action().set_enabled(false);
  192. m_view->view_as_table_action().set_enabled(false);
  193. m_view->view_as_columns_action().set_enabled(false);
  194. };
  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. location_button.button.set_checked(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. for (auto& location : CommonLocationsProvider::common_locations()) {
  204. String path = location.path;
  205. auto& button = common_locations_frame.add<GUI::Button>();
  206. button.set_button_style(Gfx::ButtonStyle::Tray);
  207. button.set_foreground_role(Gfx::ColorRole::TrayText);
  208. button.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  209. button.set_text(location.name);
  210. button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  211. button.set_fixed_height(22);
  212. button.set_checkable(true);
  213. button.set_exclusive(true);
  214. button.on_click = [this, path](auto) {
  215. set_path(path);
  216. };
  217. m_common_location_buttons.append({ path, button });
  218. }
  219. m_location_textbox->set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16));
  220. m_model->on_complete();
  221. }
  222. FilePicker::~FilePicker()
  223. {
  224. m_model->unregister_client(*this);
  225. }
  226. void FilePicker::model_did_update(unsigned)
  227. {
  228. m_location_textbox->set_text(m_model->root_path());
  229. }
  230. void FilePicker::on_file_return()
  231. {
  232. auto path = m_filename_textbox->text();
  233. if (!path.starts_with('/')) {
  234. path = LexicalPath::join(m_model->root_path(), path).string();
  235. }
  236. bool file_exists = Core::File::exists(path);
  237. if (!file_exists && (m_mode == Mode::Open || m_mode == Mode::OpenFolder)) {
  238. MessageBox::show(this, String::formatted("No such file or directory: {}", m_filename_textbox->text()), "File not found", MessageBox::Type::Error, MessageBox::InputType::OK);
  239. return;
  240. }
  241. if (file_exists && m_mode == Mode::Save) {
  242. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  243. if (result == MessageBox::ExecCancel)
  244. return;
  245. }
  246. m_selected_file = path;
  247. done(ExecOK);
  248. }
  249. void FilePicker::set_path(const String& path)
  250. {
  251. if (access(path.characters(), R_OK | X_OK) == -1) {
  252. GUI::MessageBox::show(this, String::formatted("Could not open '{}':\n{}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  253. for (auto location_button : m_common_location_buttons)
  254. location_button.button.set_checked(m_model->root_path() == location_button.path);
  255. return;
  256. }
  257. auto new_path = LexicalPath(path).string();
  258. m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
  259. m_model->set_root_path(new_path);
  260. }
  261. }