FilePicker.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/LexicalPath.h>
  28. #include <LibCore/StandardPaths.h>
  29. #include <LibGUI/Action.h>
  30. #include <LibGUI/BoxLayout.h>
  31. #include <LibGUI/Button.h>
  32. #include <LibGUI/FileIconProvider.h>
  33. #include <LibGUI/FilePicker.h>
  34. #include <LibGUI/FileSystemModel.h>
  35. #include <LibGUI/InputBox.h>
  36. #include <LibGUI/Label.h>
  37. #include <LibGUI/MessageBox.h>
  38. #include <LibGUI/MultiView.h>
  39. #include <LibGUI/SortingProxyModel.h>
  40. #include <LibGUI/TextBox.h>
  41. #include <LibGUI/ToolBar.h>
  42. #include <LibGfx/FontDatabase.h>
  43. #include <string.h>
  44. namespace GUI {
  45. Optional<String> FilePicker::get_open_filepath(Window* parent_window, const String& window_title, Options options)
  46. {
  47. auto picker = FilePicker::construct(parent_window, Mode::Open, options);
  48. if (!window_title.is_null())
  49. picker->set_title(window_title);
  50. if (picker->exec() == Dialog::ExecOK) {
  51. String file_path = picker->selected_file().string();
  52. if (file_path.is_null())
  53. return {};
  54. return file_path;
  55. }
  56. return {};
  57. }
  58. Optional<String> FilePicker::get_save_filepath(Window* parent_window, const String& title, const String& extension, Options options)
  59. {
  60. auto picker = FilePicker::construct(parent_window, Mode::Save, options, String::formatted("{}.{}", title, extension));
  61. if (picker->exec() == Dialog::ExecOK) {
  62. String file_path = picker->selected_file().string();
  63. if (file_path.is_null())
  64. return {};
  65. return file_path;
  66. }
  67. return {};
  68. }
  69. FilePicker::FilePicker(Window* parent_window, Mode mode, Options options, const StringView& file_name, const StringView& path)
  70. : Dialog(parent_window)
  71. , m_model(FileSystemModel::create())
  72. , m_mode(mode)
  73. {
  74. switch (m_mode) {
  75. case Mode::Open:
  76. case Mode::OpenMultiple:
  77. set_title("Open");
  78. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"));
  79. break;
  80. case Mode::Save:
  81. set_title("Save as");
  82. set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"));
  83. break;
  84. }
  85. resize(560, 320);
  86. auto& horizontal_container = set_main_widget<Widget>();
  87. horizontal_container.set_layout<HorizontalBoxLayout>();
  88. horizontal_container.layout()->set_margins({ 4, 4, 4, 4 });
  89. horizontal_container.set_fill_with_background_color(true);
  90. auto& vertical_container = horizontal_container.add<Widget>();
  91. vertical_container.set_layout<VerticalBoxLayout>();
  92. vertical_container.layout()->set_spacing(4);
  93. auto& upper_container = vertical_container.add<Widget>();
  94. upper_container.set_layout<HorizontalBoxLayout>();
  95. upper_container.layout()->set_spacing(2);
  96. upper_container.set_fixed_height(26);
  97. auto& toolbar = upper_container.add<ToolBar>();
  98. toolbar.set_fixed_width(165);
  99. toolbar.set_has_frame(false);
  100. m_location_textbox = upper_container.add<TextBox>();
  101. m_location_textbox->set_text(path);
  102. m_view = vertical_container.add<MultiView>();
  103. m_view->set_selection_mode(m_mode == Mode::OpenMultiple ? GUI::AbstractView::SelectionMode::MultiSelection : GUI::AbstractView::SelectionMode::SingleSelection);
  104. m_view->set_model(SortingProxyModel::create(*m_model));
  105. m_view->set_model_column(FileSystemModel::Column::Name);
  106. m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  107. m_view->set_column_hidden(FileSystemModel::Column::Owner, true);
  108. m_view->set_column_hidden(FileSystemModel::Column::Group, true);
  109. m_view->set_column_hidden(FileSystemModel::Column::Permissions, true);
  110. m_view->set_column_hidden(FileSystemModel::Column::Inode, true);
  111. m_view->set_column_hidden(FileSystemModel::Column::SymlinkTarget, true);
  112. set_path(path);
  113. m_model->register_client(*this);
  114. m_location_textbox->on_return_pressed = [this] {
  115. set_path(m_location_textbox->text());
  116. };
  117. auto open_parent_directory_action = Action::create("Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [this](const Action&) {
  118. set_path(String::formatted("{}/..", m_model->root_path()));
  119. });
  120. toolbar.add_action(*open_parent_directory_action);
  121. auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
  122. set_path(Core::StandardPaths::home_directory());
  123. });
  124. toolbar.add_action(go_home_action);
  125. toolbar.add_separator();
  126. auto mkdir_action = Action::create("New directory...", Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this](const Action&) {
  127. String value;
  128. if (InputBox::show(value, this, "Enter name:", "New directory") == InputBox::ExecOK && !value.is_empty()) {
  129. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_model->root_path(), value));
  130. int rc = mkdir(new_dir_path.characters(), 0777);
  131. if (rc < 0) {
  132. MessageBox::show(this, String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(errno)), "Error", MessageBox::Type::Error);
  133. } else {
  134. m_model->update();
  135. }
  136. }
  137. });
  138. toolbar.add_action(*mkdir_action);
  139. toolbar.add_separator();
  140. toolbar.add_action(m_view->view_as_icons_action());
  141. toolbar.add_action(m_view->view_as_table_action());
  142. toolbar.add_action(m_view->view_as_columns_action());
  143. auto& lower_container = vertical_container.add<Widget>();
  144. lower_container.set_layout<VerticalBoxLayout>();
  145. lower_container.layout()->set_spacing(4);
  146. lower_container.set_fixed_height(48);
  147. auto& filename_container = lower_container.add<Widget>();
  148. filename_container.set_fixed_height(22);
  149. filename_container.set_layout<HorizontalBoxLayout>();
  150. auto& filename_label = filename_container.add<Label>("File name:");
  151. filename_label.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  152. filename_label.set_fixed_width(60);
  153. m_filename_textbox = filename_container.add<TextBox>();
  154. m_filename_textbox->set_focus(true);
  155. if (m_mode == Mode::Save) {
  156. m_filename_textbox->set_text(file_name);
  157. m_filename_textbox->select_all();
  158. }
  159. m_filename_textbox->on_return_pressed = [&] {
  160. on_file_return();
  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. LexicalPath path { node.full_path() };
  168. if (have_preview())
  169. clear_preview();
  170. if (!node.is_directory())
  171. m_filename_textbox->set_text(node.name);
  172. if (have_preview())
  173. set_preview(path);
  174. };
  175. auto& button_container = lower_container.add<Widget>();
  176. button_container.set_fixed_height(22);
  177. button_container.set_layout<HorizontalBoxLayout>();
  178. button_container.layout()->set_spacing(4);
  179. button_container.layout()->add_spacer();
  180. auto& cancel_button = button_container.add<Button>();
  181. cancel_button.set_fixed_width(80);
  182. cancel_button.set_text("Cancel");
  183. cancel_button.on_click = [this](auto) {
  184. done(ExecCancel);
  185. };
  186. auto& ok_button = button_container.add<Button>();
  187. ok_button.set_fixed_width(80);
  188. ok_button.set_text(ok_button_name(m_mode));
  189. ok_button.on_click = [this](auto) {
  190. on_file_return();
  191. };
  192. m_view->on_activation = [this](auto& index) {
  193. auto& filter_model = (SortingProxyModel&)*m_view->model();
  194. auto local_index = filter_model.map_to_source(index);
  195. const FileSystemModel::Node& node = m_model->node(local_index);
  196. auto path = node.full_path();
  197. if (node.is_directory()) {
  198. set_path(path);
  199. // NOTE: 'node' is invalid from here on
  200. } else {
  201. on_file_return();
  202. }
  203. };
  204. if (!((unsigned)options & (unsigned)Options::DisablePreview)) {
  205. m_preview_container = horizontal_container.add<Frame>();
  206. m_preview_container->set_visible(false);
  207. m_preview_container->set_fixed_width(180);
  208. m_preview_container->set_layout<VerticalBoxLayout>();
  209. m_preview_container->layout()->set_margins({ 8, 8, 8, 8 });
  210. m_preview_image = m_preview_container->add<ImageWidget>();
  211. m_preview_image->set_should_stretch(true);
  212. m_preview_image->set_auto_resize(false);
  213. m_preview_image->set_fixed_size(160, 160);
  214. m_preview_name_label = m_preview_container->add<Label>();
  215. m_preview_name_label->set_font(Gfx::FontDatabase::default_bold_font());
  216. m_preview_name_label->set_fixed_height(m_preview_name_label->font().glyph_height());
  217. m_preview_geometry_label = m_preview_container->add<Label>();
  218. m_preview_geometry_label->set_fixed_height(m_preview_name_label->font().glyph_height());
  219. }
  220. }
  221. FilePicker::~FilePicker()
  222. {
  223. m_model->unregister_client(*this);
  224. }
  225. void FilePicker::model_did_update(unsigned)
  226. {
  227. m_location_textbox->set_text(m_model->root_path());
  228. if (have_preview())
  229. clear_preview();
  230. }
  231. void FilePicker::set_preview(const LexicalPath& path)
  232. {
  233. if (Gfx::Bitmap::is_path_a_supported_image_format(path.string())) {
  234. auto bitmap = Gfx::Bitmap::load_from_file(path.string());
  235. if (!bitmap) {
  236. clear_preview();
  237. return;
  238. }
  239. bool should_stretch = bitmap->width() > m_preview_image->width() || bitmap->height() > m_preview_image->height();
  240. m_preview_name_label->set_text(path.basename());
  241. m_preview_geometry_label->set_text(bitmap->size().to_string());
  242. m_preview_image->set_should_stretch(should_stretch);
  243. m_preview_image->set_bitmap(move(bitmap));
  244. m_preview_container->set_visible(true);
  245. }
  246. }
  247. void FilePicker::clear_preview()
  248. {
  249. m_preview_image->set_bitmap(nullptr);
  250. m_preview_name_label->set_text(String::empty());
  251. m_preview_geometry_label->set_text(String::empty());
  252. m_preview_container->set_visible(false);
  253. }
  254. void FilePicker::on_file_return()
  255. {
  256. LexicalPath path(String::formatted("{}/{}", m_model->root_path(), m_filename_textbox->text()));
  257. if (FilePicker::file_exists(path.string()) && m_mode == Mode::Save) {
  258. auto result = MessageBox::show(this, "File already exists. Overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  259. if (result == MessageBox::ExecCancel)
  260. return;
  261. }
  262. m_selected_file = path;
  263. done(ExecOK);
  264. }
  265. bool FilePicker::file_exists(const StringView& path)
  266. {
  267. struct stat st;
  268. int rc = stat(path.to_string().characters(), &st);
  269. if (rc < 0) {
  270. if (errno == ENOENT)
  271. return false;
  272. }
  273. if (rc == 0) {
  274. return true;
  275. }
  276. return false;
  277. }
  278. void FilePicker::set_path(const String& path)
  279. {
  280. auto new_path = LexicalPath(path).string();
  281. m_location_textbox->set_icon(FileIconProvider::icon_for_path(new_path).bitmap_for_size(16));
  282. m_model->set_root_path(new_path);
  283. }
  284. }