FilePicker.cpp 13 KB

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