FilePicker.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 <LibGUI/Action.h>
  29. #include <LibGUI/BoxLayout.h>
  30. #include <LibGUI/Button.h>
  31. #include <LibGUI/FilePicker.h>
  32. #include <LibGUI/FileSystemModel.h>
  33. #include <LibGUI/InputBox.h>
  34. #include <LibGUI/Label.h>
  35. #include <LibGUI/MessageBox.h>
  36. #include <LibGUI/MultiView.h>
  37. #include <LibGUI/SortingProxyModel.h>
  38. #include <LibGUI/TextBox.h>
  39. #include <LibGUI/ToolBar.h>
  40. #include <string.h>
  41. namespace GUI {
  42. Optional<String> FilePicker::get_open_filepath(const String& window_title)
  43. {
  44. auto picker = FilePicker::construct(Mode::Open);
  45. if (!window_title.is_null())
  46. picker->set_title(window_title);
  47. if (picker->exec() == Dialog::ExecOK) {
  48. String file_path = picker->selected_file().string();
  49. if (file_path.is_null())
  50. return {};
  51. return file_path;
  52. }
  53. return {};
  54. }
  55. Optional<String> FilePicker::get_save_filepath(const String& title, const String& extension)
  56. {
  57. auto picker = FilePicker::construct(Mode::Save, String::format("%s.%s", title.characters(), extension.characters()));
  58. if (picker->exec() == Dialog::ExecOK) {
  59. String file_path = picker->selected_file().string();
  60. if (file_path.is_null())
  61. return {};
  62. return file_path;
  63. }
  64. return {};
  65. }
  66. FilePicker::FilePicker(Mode mode, const StringView& file_name, const StringView& path, Window* parent_window)
  67. : Dialog(parent_window)
  68. , m_model(FileSystemModel::create())
  69. , m_mode(mode)
  70. {
  71. set_title(m_mode == Mode::Open ? "Open File" : "Save File");
  72. set_rect(200, 200, 700, 400);
  73. auto& horizontal_container = set_main_widget<Widget>();
  74. horizontal_container.set_layout<HorizontalBoxLayout>();
  75. horizontal_container.layout()->set_margins({ 4, 4, 4, 4 });
  76. horizontal_container.set_fill_with_background_color(true);
  77. auto& vertical_container = horizontal_container.add<Widget>();
  78. vertical_container.set_layout<VerticalBoxLayout>();
  79. vertical_container.layout()->set_spacing(4);
  80. auto& upper_container = vertical_container.add<Widget>();
  81. upper_container.set_layout<HorizontalBoxLayout>();
  82. upper_container.layout()->set_spacing(4);
  83. upper_container.set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  84. upper_container.set_preferred_size(0, 26);
  85. auto& toolbar = upper_container.add<ToolBar>();
  86. toolbar.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  87. #ifdef MULTIVIEW_WITH_COLUMNSVIEW
  88. toolbar.set_preferred_size(165, 0);
  89. #else
  90. toolbar.set_preferred_size(140, 0);
  91. #endif
  92. toolbar.set_has_frame(false);
  93. auto& location_textbox = upper_container.add<TextBox>();
  94. location_textbox.set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  95. location_textbox.set_preferred_size(0, 20);
  96. location_textbox.set_text(path);
  97. m_view = vertical_container.add<MultiView>();
  98. m_view->set_model(SortingProxyModel::create(*m_model));
  99. m_view->set_model_column(FileSystemModel::Column::Name);
  100. m_view->model()->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  101. m_view->set_column_hidden(FileSystemModel::Column::Owner, true);
  102. m_view->set_column_hidden(FileSystemModel::Column::Group, true);
  103. m_view->set_column_hidden(FileSystemModel::Column::Permissions, true);
  104. m_view->set_column_hidden(FileSystemModel::Column::Inode, true);
  105. m_view->set_column_hidden(FileSystemModel::Column::SymlinkTarget, true);
  106. m_model->set_root_path(path);
  107. location_textbox.on_return_pressed = [&] {
  108. m_model->set_root_path(location_textbox.text());
  109. clear_preview();
  110. };
  111. 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&) {
  112. m_model->set_root_path(String::format("%s/..", m_model->root_path().characters()));
  113. clear_preview();
  114. });
  115. toolbar.add_action(*open_parent_directory_action);
  116. auto go_home_action = CommonActions::make_go_home_action([this](auto&) {
  117. m_model->set_root_path(Core::StandardPaths::home_directory());
  118. });
  119. toolbar.add_action(go_home_action);
  120. toolbar.add_separator();
  121. auto mkdir_action = Action::create("New directory...", Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this](const Action&) {
  122. auto& input_box = add<InputBox>("Enter name:", "New directory");
  123. if (input_box.exec() == InputBox::ExecOK && !input_box.text_value().is_empty()) {
  124. auto new_dir_path = LexicalPath(String::format("%s/%s",
  125. m_model->root_path().characters(),
  126. input_box.text_value().characters()))
  127. .string();
  128. int rc = mkdir(new_dir_path.characters(), 0777);
  129. if (rc < 0) {
  130. MessageBox::show(String::format("mkdir(\"%s\") failed: %s", new_dir_path.characters(), strerror(errno)), "Error", MessageBox::Type::Error, MessageBox::InputType::OK, this);
  131. } else {
  132. m_model->update();
  133. }
  134. }
  135. });
  136. toolbar.add_action(*mkdir_action);
  137. toolbar.add_separator();
  138. toolbar.add_action(m_view->view_as_icons_action());
  139. toolbar.add_action(m_view->view_as_table_action());
  140. #ifdef MULTIVIEW_WITH_COLUMNSVIEW
  141. m_view->view_as_columns_action().set_enabled(false);
  142. toolbar.add_action(m_view->view_as_columns_action());
  143. #endif
  144. auto& lower_container = vertical_container.add<Widget>();
  145. lower_container.set_layout<VerticalBoxLayout>();
  146. lower_container.layout()->set_spacing(4);
  147. lower_container.set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  148. lower_container.set_preferred_size(0, 60);
  149. auto& filename_container = lower_container.add<Widget>();
  150. filename_container.set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  151. filename_container.set_preferred_size(0, 20);
  152. filename_container.set_layout<HorizontalBoxLayout>();
  153. auto& filename_label = filename_container.add<Label>("File name:");
  154. filename_label.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  155. filename_label.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  156. filename_label.set_preferred_size(60, 0);
  157. m_filename_textbox = filename_container.add<TextBox>();
  158. if (m_mode == Mode::Save) {
  159. m_filename_textbox->set_text(file_name);
  160. m_filename_textbox->set_focus(true);
  161. m_filename_textbox->select_all();
  162. }
  163. m_filename_textbox->on_return_pressed = [&] {
  164. on_file_return();
  165. };
  166. m_view->on_selection_change = [this] {
  167. auto index = m_view->selection().first();
  168. auto& filter_model = (SortingProxyModel&)*m_view->model();
  169. auto local_index = filter_model.map_to_target(index);
  170. const FileSystemModel::Node& node = m_model->node(local_index);
  171. LexicalPath path { node.full_path(m_model) };
  172. clear_preview();
  173. if (!node.is_directory())
  174. m_filename_textbox->set_text(node.name);
  175. set_preview(path);
  176. };
  177. auto& button_container = lower_container.add<Widget>();
  178. button_container.set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  179. button_container.set_preferred_size(0, 20);
  180. button_container.set_layout<HorizontalBoxLayout>();
  181. button_container.layout()->set_spacing(4);
  182. button_container.layout()->add_spacer();
  183. auto& cancel_button = button_container.add<Button>();
  184. cancel_button.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  185. cancel_button.set_preferred_size(80, 0);
  186. cancel_button.set_text("Cancel");
  187. cancel_button.on_click = [this](auto) {
  188. done(ExecCancel);
  189. };
  190. auto& ok_button = button_container.add<Button>();
  191. ok_button.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  192. ok_button.set_preferred_size(80, 0);
  193. ok_button.set_text(ok_button_name(m_mode));
  194. ok_button.on_click = [this](auto) {
  195. on_file_return();
  196. };
  197. m_view->on_activation = [this](auto& index) {
  198. auto& filter_model = (SortingProxyModel&)*m_view->model();
  199. auto local_index = filter_model.map_to_target(index);
  200. const FileSystemModel::Node& node = m_model->node(local_index);
  201. auto path = node.full_path(m_model);
  202. if (node.is_directory()) {
  203. m_model->set_root_path(path);
  204. // NOTE: 'node' is invalid from here on
  205. } else {
  206. on_file_return();
  207. }
  208. };
  209. auto& preview_container = horizontal_container.add<Frame>();
  210. preview_container.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  211. preview_container.set_preferred_size(180, 0);
  212. preview_container.set_layout<VerticalBoxLayout>();
  213. preview_container.layout()->set_margins({ 8, 8, 8, 8 });
  214. m_preview_image = preview_container.add<Image>();
  215. m_preview_image->set_should_stretch(true);
  216. m_preview_image->set_auto_resize(false);
  217. m_preview_image->set_preferred_size(160, 160);
  218. m_preview_name_label = preview_container.add<Label>();
  219. m_preview_name_label->set_font(Gfx::Font::default_bold_font());
  220. m_preview_name_label->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  221. m_preview_name_label->set_preferred_size(0, m_preview_name_label->font().glyph_height());
  222. m_preview_geometry_label = preview_container.add<Label>();
  223. m_preview_geometry_label->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
  224. m_preview_geometry_label->set_preferred_size(0, m_preview_name_label->font().glyph_height());
  225. }
  226. FilePicker::~FilePicker()
  227. {
  228. }
  229. void FilePicker::set_preview(const LexicalPath& path)
  230. {
  231. if (Gfx::Bitmap::is_path_a_supported_image_format(path.string())) {
  232. auto bitmap = Gfx::Bitmap::load_from_file(path.string());
  233. if (!bitmap) {
  234. clear_preview();
  235. return;
  236. }
  237. bool should_stretch = bitmap->width() > m_preview_image->width() || bitmap->height() > m_preview_image->height();
  238. m_preview_name_label->set_text(path.basename());
  239. m_preview_geometry_label->set_text(bitmap->size().to_string());
  240. m_preview_image->set_should_stretch(should_stretch);
  241. m_preview_image->set_bitmap(move(bitmap));
  242. }
  243. }
  244. void FilePicker::clear_preview()
  245. {
  246. m_preview_image->set_bitmap(nullptr);
  247. m_preview_name_label->set_text(String::empty());
  248. m_preview_geometry_label->set_text(String::empty());
  249. }
  250. void FilePicker::on_file_return()
  251. {
  252. LexicalPath path(String::format("%s/%s", m_model->root_path().characters(), m_filename_textbox->text().characters()));
  253. if (FilePicker::file_exists(path.string()) && m_mode == Mode::Save) {
  254. auto result = MessageBox::show("File already exists, overwrite?", "Existing File", MessageBox::Type::Warning, MessageBox::InputType::OKCancel);
  255. if (result == MessageBox::ExecCancel)
  256. return;
  257. }
  258. m_selected_file = path;
  259. done(ExecOK);
  260. }
  261. bool FilePicker::file_exists(const StringView& path)
  262. {
  263. struct stat st;
  264. int rc = stat(path.to_string().characters(), &st);
  265. if (rc < 0) {
  266. if (errno == ENOENT)
  267. return false;
  268. }
  269. if (rc == 0) {
  270. return true;
  271. }
  272. return false;
  273. }
  274. }