main.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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 "DirectoryView.h"
  27. #include "FileUtils.h"
  28. #include "PropertiesDialog.h"
  29. #include <AK/LexicalPath.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/URL.h>
  32. #include <LibCore/ConfigFile.h>
  33. #include <LibCore/MimeData.h>
  34. #include <LibCore/StandardPaths.h>
  35. #include <LibDesktop/Launcher.h>
  36. #include <LibGUI/AboutDialog.h>
  37. #include <LibGUI/Action.h>
  38. #include <LibGUI/ActionGroup.h>
  39. #include <LibGUI/Application.h>
  40. #include <LibGUI/BoxLayout.h>
  41. #include <LibGUI/Clipboard.h>
  42. #include <LibGUI/FileSystemModel.h>
  43. #include <LibGUI/InputBox.h>
  44. #include <LibGUI/Label.h>
  45. #include <LibGUI/Menu.h>
  46. #include <LibGUI/MenuBar.h>
  47. #include <LibGUI/MessageBox.h>
  48. #include <LibGUI/Painter.h>
  49. #include <LibGUI/ProgressBar.h>
  50. #include <LibGUI/Splitter.h>
  51. #include <LibGUI/StatusBar.h>
  52. #include <LibGUI/TextEditor.h>
  53. #include <LibGUI/ToolBar.h>
  54. #include <LibGUI/ToolBarContainer.h>
  55. #include <LibGUI/TreeView.h>
  56. #include <LibGUI/Widget.h>
  57. #include <LibGUI/Window.h>
  58. #include <LibGfx/Palette.h>
  59. #include <signal.h>
  60. #include <spawn.h>
  61. #include <stdio.h>
  62. #include <string.h>
  63. #include <unistd.h>
  64. static int run_in_desktop_mode(RefPtr<Core::ConfigFile>, String initial_location);
  65. static int run_in_windowed_mode(RefPtr<Core::ConfigFile>, String initial_location);
  66. int main(int argc, char** argv)
  67. {
  68. if (pledge("stdio thread shared_buffer accept unix cpath rpath wpath fattr proc exec sigaction", nullptr) < 0) {
  69. perror("pledge");
  70. return 1;
  71. }
  72. struct sigaction act;
  73. memset(&act, 0, sizeof(act));
  74. act.sa_flags = SA_NOCLDWAIT;
  75. act.sa_handler = SIG_IGN;
  76. int rc = sigaction(SIGCHLD, &act, nullptr);
  77. if (rc < 0) {
  78. perror("sigaction");
  79. return 1;
  80. }
  81. RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("FileManager");
  82. auto app = GUI::Application::construct(argc, argv);
  83. if (pledge("stdio thread shared_buffer accept cpath rpath wpath fattr proc exec unix", nullptr) < 0) {
  84. perror("pledge");
  85. return 1;
  86. }
  87. if (app->args().contains_slow("--desktop") || app->args().contains_slow("-d"))
  88. return run_in_desktop_mode(move(config), Core::StandardPaths::desktop_directory());
  89. // our initial location is defined as, in order of precedence:
  90. // 1. the first command-line argument (e.g. FileManager /bin)
  91. // 2. the user's home directory
  92. // 3. the root directory
  93. String initial_location;
  94. if (argc >= 2) {
  95. char* buffer = realpath(argv[1], nullptr);
  96. initial_location = buffer;
  97. free(buffer);
  98. }
  99. if (initial_location.is_empty())
  100. initial_location = Core::StandardPaths::home_directory();
  101. if (initial_location.is_empty())
  102. initial_location = "/";
  103. return run_in_windowed_mode(move(config), initial_location);
  104. }
  105. class DesktopWidget final : public GUI::Widget {
  106. C_OBJECT(DesktopWidget);
  107. private:
  108. virtual void paint_event(GUI::PaintEvent& event) override
  109. {
  110. GUI::Painter painter(*this);
  111. painter.add_clip_rect(event.rect());
  112. painter.clear_rect(event.rect(), Color(0, 0, 0, 0));
  113. }
  114. DesktopWidget()
  115. {
  116. }
  117. };
  118. int run_in_desktop_mode(RefPtr<Core::ConfigFile> config, String initial_location)
  119. {
  120. (void)config;
  121. (void)initial_location;
  122. auto window = GUI::Window::construct();
  123. window->set_title("Desktop Manager");
  124. window->set_window_type(GUI::WindowType::Desktop);
  125. window->set_has_alpha_channel(true);
  126. auto& desktop_widget = window->set_main_widget<DesktopWidget>();
  127. desktop_widget.set_layout<GUI::VerticalBoxLayout>();
  128. auto& icon_view = desktop_widget.add<GUI::IconView>();
  129. icon_view.set_frame_thickness(0);
  130. icon_view.set_scrollbars_enabled(false);
  131. icon_view.set_fill_with_background_color(false);
  132. auto model = GUI::FileSystemModel::create(initial_location);
  133. icon_view.set_model(model);
  134. icon_view.set_model_column(GUI::FileSystemModel::Column::Name);
  135. icon_view.on_activation = [&](auto& index) {
  136. if (!index.is_valid())
  137. return;
  138. auto& node = model->node(index);
  139. auto path = node.full_path(model);
  140. Desktop::Launcher::open(URL::create_with_file_protocol(path));
  141. };
  142. auto desktop_view_context_menu = GUI::Menu::construct("Directory View");
  143. auto mkdir_action = GUI::Action::create("New directory...", {}, Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [&](const GUI::Action&) {
  144. String value;
  145. if (GUI::InputBox::show(value, window, "Enter name:", "New directory") == GUI::InputBox::ExecOK && !value.is_empty()) {
  146. auto new_dir_path = LexicalPath::canonicalized_path(
  147. String::format("%s/%s",
  148. model->root_path().characters(),
  149. value.characters()));
  150. int rc = mkdir(new_dir_path.characters(), 0777);
  151. if (rc < 0) {
  152. GUI::MessageBox::show(window, String::format("mkdir(\"%s\") failed: %s", new_dir_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  153. }
  154. }
  155. });
  156. auto touch_action = GUI::Action::create("New file...", {}, Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"), [&](const GUI::Action&) {
  157. String value;
  158. if (GUI::InputBox::show(value, window, "Enter name:", "New file") == GUI::InputBox::ExecOK && !value.is_empty()) {
  159. auto new_file_path = LexicalPath::canonicalized_path(
  160. String::format("%s/%s",
  161. model->root_path().characters(),
  162. value.characters()));
  163. struct stat st;
  164. int rc = stat(new_file_path.characters(), &st);
  165. if ((rc < 0 && errno != ENOENT)) {
  166. GUI::MessageBox::show(window, String::format("stat(\"%s\") failed: %s", new_file_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  167. return;
  168. }
  169. if (rc == 0) {
  170. GUI::MessageBox::show(window, String::format("%s: Already exists", new_file_path.characters()), "Error", GUI::MessageBox::Type::Error);
  171. return;
  172. }
  173. int fd = creat(new_file_path.characters(), 0666);
  174. if (fd < 0) {
  175. GUI::MessageBox::show(window, String::format("creat(\"%s\") failed: %s", new_file_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  176. return;
  177. }
  178. rc = close(fd);
  179. assert(rc >= 0);
  180. }
  181. });
  182. auto file_manager_action = GUI::Action::create("Show in FileManager...", {}, Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-folder.png"), [&](const GUI::Action&) {
  183. Desktop::Launcher::open(URL::create_with_file_protocol(model->root_path()));
  184. });
  185. auto display_properties_action = GUI::Action::create("Display settings...", {}, Gfx::Bitmap::load_from_file("/res/icons/16x16/app-display-settings.png"), [&](const GUI::Action&) {
  186. Desktop::Launcher::open(URL::create_with_file_protocol("/bin/DisplaySettings"));
  187. });
  188. desktop_view_context_menu->add_action(mkdir_action);
  189. desktop_view_context_menu->add_action(touch_action);
  190. desktop_view_context_menu->add_separator();
  191. desktop_view_context_menu->add_action(file_manager_action);
  192. desktop_view_context_menu->add_separator();
  193. desktop_view_context_menu->add_action(display_properties_action);
  194. icon_view.on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  195. if (!index.is_valid())
  196. desktop_view_context_menu->popup(event.screen_position());
  197. };
  198. window->show();
  199. return GUI::Application::the()->exec();
  200. }
  201. int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_location)
  202. {
  203. auto window = GUI::Window::construct();
  204. window->set_title("File Manager");
  205. auto left = config->read_num_entry("Window", "Left", 150);
  206. auto top = config->read_num_entry("Window", "Top", 75);
  207. auto width = config->read_num_entry("Window", "Width", 640);
  208. auto heigth = config->read_num_entry("Window", "Heigth", 480);
  209. window->set_rect({ left, top, width, heigth });
  210. auto& widget = window->set_main_widget<GUI::Widget>();
  211. widget.set_layout<GUI::VerticalBoxLayout>();
  212. widget.set_fill_with_background_color(true);
  213. widget.layout()->set_spacing(2);
  214. auto& toolbar_container = widget.add<GUI::ToolBarContainer>();
  215. auto& main_toolbar = toolbar_container.add<GUI::ToolBar>();
  216. auto& location_toolbar = toolbar_container.add<GUI::ToolBar>();
  217. location_toolbar.layout()->set_margins({ 6, 3, 6, 3 });
  218. auto& location_label = location_toolbar.add<GUI::Label>("Location: ");
  219. location_label.size_to_fit();
  220. auto& location_textbox = location_toolbar.add<GUI::TextBox>();
  221. location_textbox.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  222. location_textbox.set_preferred_size(0, 22);
  223. location_textbox.set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-folder.png"));
  224. auto& splitter = widget.add<GUI::HorizontalSplitter>();
  225. auto& tree_view = splitter.add<GUI::TreeView>();
  226. auto directories_model = GUI::FileSystemModel::create("/", GUI::FileSystemModel::Mode::DirectoriesOnly);
  227. tree_view.set_model(directories_model);
  228. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Icon, true);
  229. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Size, true);
  230. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Owner, true);
  231. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Group, true);
  232. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Permissions, true);
  233. tree_view.set_column_hidden(GUI::FileSystemModel::Column::ModificationTime, true);
  234. tree_view.set_column_hidden(GUI::FileSystemModel::Column::Inode, true);
  235. tree_view.set_column_hidden(GUI::FileSystemModel::Column::SymlinkTarget, true);
  236. tree_view.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  237. tree_view.set_preferred_size(150, 0);
  238. auto& directory_view = splitter.add<DirectoryView>();
  239. auto& statusbar = widget.add<GUI::StatusBar>();
  240. auto& progressbar = statusbar.add<GUI::ProgressBar>();
  241. progressbar.set_caption("Generating thumbnails: ");
  242. progressbar.set_format(GUI::ProgressBar::Format::ValueSlashMax);
  243. progressbar.set_visible(false);
  244. progressbar.set_frame_shape(Gfx::FrameShape::Panel);
  245. progressbar.set_frame_shadow(Gfx::FrameShadow::Sunken);
  246. progressbar.set_frame_thickness(1);
  247. location_textbox.on_return_pressed = [&] {
  248. directory_view.open(location_textbox.text());
  249. };
  250. auto refresh_tree_view = [&] {
  251. directories_model->update();
  252. auto current_path = directory_view.path();
  253. struct stat st;
  254. // If the directory no longer exists, we find a parent that does.
  255. while (stat(current_path.characters(), &st) != 0) {
  256. directory_view.open_parent_directory();
  257. current_path = directory_view.path();
  258. if (current_path == directories_model->root_path()) {
  259. break;
  260. }
  261. }
  262. // Reselect the existing folder in the tree.
  263. auto new_index = directories_model->index(current_path, GUI::FileSystemModel::Column::Name);
  264. tree_view.selection().set(new_index);
  265. tree_view.scroll_into_view(new_index, Orientation::Vertical);
  266. tree_view.update();
  267. directory_view.refresh();
  268. };
  269. auto directory_context_menu = GUI::Menu::construct("Directory View Directory");
  270. auto directory_view_context_menu = GUI::Menu::construct("Directory View");
  271. auto tree_view_directory_context_menu = GUI::Menu::construct("Tree View Directory");
  272. auto tree_view_context_menu = GUI::Menu::construct("Tree View");
  273. auto open_parent_directory_action = GUI::Action::create("Open parent directory", { Mod_Alt, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [&](const GUI::Action&) {
  274. directory_view.open_parent_directory();
  275. });
  276. auto mkdir_action = GUI::Action::create("New directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"), [&](const GUI::Action&) {
  277. String value;
  278. if (GUI::InputBox::show(value, window, "Enter name:", "New directory") == GUI::InputBox::ExecOK && !value.is_empty()) {
  279. auto new_dir_path = LexicalPath::canonicalized_path(
  280. String::format("%s/%s",
  281. directory_view.path().characters(),
  282. value.characters()));
  283. int rc = mkdir(new_dir_path.characters(), 0777);
  284. if (rc < 0) {
  285. GUI::MessageBox::show(window, String::format("mkdir(\"%s\") failed: %s", new_dir_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  286. } else {
  287. refresh_tree_view();
  288. }
  289. }
  290. });
  291. auto touch_action = GUI::Action::create("New file...", { Mod_Ctrl | Mod_Shift, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"), [&](const GUI::Action&) {
  292. String value;
  293. if (GUI::InputBox::show(value, window, "Enter name:", "New file") == GUI::InputBox::ExecOK && !value.is_empty()) {
  294. auto new_file_path = LexicalPath::canonicalized_path(
  295. String::format("%s/%s",
  296. directory_view.path().characters(),
  297. value.characters()));
  298. struct stat st;
  299. int rc = stat(new_file_path.characters(), &st);
  300. if ((rc < 0 && errno != ENOENT)) {
  301. GUI::MessageBox::show(window, String::format("stat(\"%s\") failed: %s", new_file_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  302. return;
  303. }
  304. if (rc == 0) {
  305. GUI::MessageBox::show(window, String::format("%s: Already exists", new_file_path.characters()), "Error", GUI::MessageBox::Type::Error);
  306. return;
  307. }
  308. int fd = creat(new_file_path.characters(), 0666);
  309. if (fd < 0) {
  310. GUI::MessageBox::show(window, String::format("creat(\"%s\") failed: %s", new_file_path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  311. return;
  312. }
  313. rc = close(fd);
  314. assert(rc >= 0);
  315. refresh_tree_view();
  316. }
  317. });
  318. auto open_terminal_action = GUI::Action::create("Open Terminal here...", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"), [&](const GUI::Action&) {
  319. posix_spawn_file_actions_t spawn_actions;
  320. posix_spawn_file_actions_init(&spawn_actions);
  321. posix_spawn_file_actions_addchdir(&spawn_actions, directory_view.path().characters());
  322. pid_t pid;
  323. const char* argv[] = { "Terminal", nullptr };
  324. posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ);
  325. posix_spawn_file_actions_destroy(&spawn_actions);
  326. });
  327. RefPtr<GUI::Action> view_as_table_action;
  328. RefPtr<GUI::Action> view_as_icons_action;
  329. RefPtr<GUI::Action> view_as_columns_action;
  330. view_as_icons_action = GUI::Action::create_checkable(
  331. "Icon view", { Mod_Ctrl, KeyCode::Key_1 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/icon-view.png"), [&](const GUI::Action&) {
  332. directory_view.set_view_mode(DirectoryView::ViewMode::Icon);
  333. config->write_entry("DirectoryView", "ViewMode", "Icon");
  334. config->sync();
  335. },
  336. window);
  337. view_as_table_action = GUI::Action::create_checkable(
  338. "Table view", { Mod_Ctrl, KeyCode::Key_2 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/table-view.png"), [&](const GUI::Action&) {
  339. directory_view.set_view_mode(DirectoryView::ViewMode::Table);
  340. config->write_entry("DirectoryView", "ViewMode", "Table");
  341. config->sync();
  342. },
  343. window);
  344. view_as_columns_action = GUI::Action::create_checkable(
  345. "Columns view", { Mod_Ctrl, KeyCode::Key_3 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/columns-view.png"), [&](const GUI::Action&) {
  346. directory_view.set_view_mode(DirectoryView::ViewMode::Columns);
  347. config->write_entry("DirectoryView", "ViewMode", "Columns");
  348. config->sync();
  349. },
  350. window);
  351. auto view_type_action_group = make<GUI::ActionGroup>();
  352. view_type_action_group->set_exclusive(true);
  353. view_type_action_group->add_action(*view_as_icons_action);
  354. view_type_action_group->add_action(*view_as_table_action);
  355. view_type_action_group->add_action(*view_as_columns_action);
  356. auto selected_file_paths = [&] {
  357. Vector<String> paths;
  358. auto& view = directory_view.current_view();
  359. auto& model = *view.model();
  360. view.selection().for_each_index([&](const GUI::ModelIndex& index) {
  361. auto parent_index = model.parent_index(index);
  362. auto name_index = model.index(index.row(), GUI::FileSystemModel::Column::Name, parent_index);
  363. auto path = model.data(name_index, GUI::Model::Role::Custom).to_string();
  364. paths.append(path);
  365. });
  366. return paths;
  367. };
  368. auto tree_view_selected_file_paths = [&] {
  369. Vector<String> paths;
  370. auto& view = tree_view;
  371. view.selection().for_each_index([&](const GUI::ModelIndex& index) {
  372. paths.append(directories_model->full_path(index));
  373. });
  374. return paths;
  375. };
  376. auto select_all_action = GUI::Action::create("Select all", { Mod_Ctrl, KeyCode::Key_A }, [&](const GUI::Action&) {
  377. directory_view.current_view().select_all();
  378. });
  379. auto copy_action = GUI::CommonActions::make_copy_action(
  380. [&](const GUI::Action&) {
  381. Vector<String> paths = selected_file_paths();
  382. if (!paths.size())
  383. paths = tree_view_selected_file_paths();
  384. if (paths.is_empty())
  385. ASSERT_NOT_REACHED();
  386. StringBuilder copy_text;
  387. for (auto& path : paths) {
  388. auto url = URL::create_with_file_protocol(path);
  389. copy_text.appendf("%s\n", url.to_string().characters());
  390. }
  391. GUI::Clipboard::the().set_data(copy_text.build(), "text/uri-list");
  392. },
  393. window);
  394. copy_action->set_enabled(false);
  395. auto properties_action
  396. = GUI::Action::create(
  397. "Properties...", { Mod_Alt, Key_Return }, Gfx::Bitmap::load_from_file("/res/icons/16x16/properties.png"), [&](const GUI::Action& action) {
  398. auto& model = directory_view.model();
  399. String container_dir_path;
  400. String path;
  401. Vector<String> selected;
  402. if (action.activator() == directory_context_menu || directory_view.active_widget()->is_focused()) {
  403. path = directory_view.path();
  404. container_dir_path = path;
  405. selected = selected_file_paths();
  406. } else {
  407. path = directories_model->full_path(tree_view.selection().first());
  408. container_dir_path = LexicalPath(path).basename();
  409. selected = tree_view_selected_file_paths();
  410. }
  411. RefPtr<PropertiesDialog> properties;
  412. if (selected.is_empty()) {
  413. properties = window->add<PropertiesDialog>(model, path, true);
  414. } else {
  415. properties = window->add<PropertiesDialog>(model, selected.first(), access(container_dir_path.characters(), W_OK) != 0);
  416. }
  417. properties->exec();
  418. },
  419. window);
  420. enum class ConfirmBeforeDelete {
  421. No,
  422. Yes
  423. };
  424. auto do_paste = [&](const GUI::Action& action) {
  425. auto data_and_type = GUI::Clipboard::the().data_and_type();
  426. if (data_and_type.type != "text/uri-list") {
  427. dbg() << "Cannot paste clipboard type " << data_and_type.type;
  428. return;
  429. }
  430. auto copied_lines = data_and_type.data.split('\n');
  431. if (copied_lines.is_empty()) {
  432. dbg() << "No files to paste";
  433. return;
  434. }
  435. AK::String target_directory;
  436. if (action.activator() == directory_context_menu)
  437. target_directory = selected_file_paths()[0];
  438. else
  439. target_directory = directory_view.path();
  440. for (auto& uri_as_string : copied_lines) {
  441. if (uri_as_string.is_empty())
  442. continue;
  443. URL url = uri_as_string;
  444. if (!url.is_valid() || url.protocol() != "file") {
  445. dbg() << "Cannot paste URI " << uri_as_string;
  446. continue;
  447. }
  448. auto new_path = String::format("%s/%s", target_directory.characters(), url.basename().characters());
  449. if (!FileUtils::copy_file_or_directory(url.path(), new_path)) {
  450. auto error_message = String::format("Could not paste %s.", url.path().characters());
  451. GUI::MessageBox::show(window, error_message, "File Manager", GUI::MessageBox::Type::Error);
  452. } else {
  453. refresh_tree_view();
  454. }
  455. }
  456. };
  457. auto do_delete = [&](ConfirmBeforeDelete confirm, const GUI::Action&) {
  458. Vector<String> paths = selected_file_paths();
  459. if (!paths.size())
  460. paths = tree_view_selected_file_paths();
  461. if (paths.is_empty())
  462. ASSERT_NOT_REACHED();
  463. String message;
  464. if (paths.size() == 1) {
  465. message = String::format("Really delete %s?", LexicalPath(paths[0]).basename().characters());
  466. } else {
  467. message = String::format("Really delete %d files?", paths.size());
  468. }
  469. if (confirm == ConfirmBeforeDelete::Yes) {
  470. auto result = GUI::MessageBox::show(window,
  471. message,
  472. "Confirm deletion",
  473. GUI::MessageBox::Type::Warning,
  474. GUI::MessageBox::InputType::OKCancel);
  475. if (result == GUI::MessageBox::ExecCancel)
  476. return;
  477. }
  478. for (auto& path : paths) {
  479. struct stat st;
  480. if (lstat(path.characters(), &st)) {
  481. GUI::MessageBox::show(window,
  482. String::format("lstat(%s) failed: %s", path.characters(), strerror(errno)),
  483. "Delete failed",
  484. GUI::MessageBox::Type::Error);
  485. break;
  486. } else {
  487. refresh_tree_view();
  488. }
  489. if (S_ISDIR(st.st_mode)) {
  490. String error_path;
  491. int error = FileUtils::delete_directory(path, error_path);
  492. if (error) {
  493. GUI::MessageBox::show(window,
  494. String::format("Failed to delete directory \"%s\": %s", error_path.characters(), strerror(error)),
  495. "Delete failed",
  496. GUI::MessageBox::Type::Error);
  497. break;
  498. } else {
  499. refresh_tree_view();
  500. }
  501. } else if (unlink(path.characters()) < 0) {
  502. int saved_errno = errno;
  503. GUI::MessageBox::show(window,
  504. String::format("unlink(%s) failed: %s", path.characters(), strerror(saved_errno)),
  505. "Delete failed",
  506. GUI::MessageBox::Type::Error);
  507. break;
  508. }
  509. }
  510. };
  511. auto paste_action = GUI::CommonActions::make_paste_action(
  512. [&](const GUI::Action& action) {
  513. do_paste(action);
  514. },
  515. window);
  516. auto folder_specific_paste_action = GUI::CommonActions::make_paste_action(
  517. [&](const GUI::Action& action) {
  518. do_paste(action);
  519. },
  520. window);
  521. auto force_delete_action = GUI::Action::create(
  522. "Delete without confirmation", { Mod_Shift, Key_Delete }, [&](const GUI::Action& action) {
  523. do_delete(ConfirmBeforeDelete::No, action);
  524. },
  525. window);
  526. auto delete_action = GUI::CommonActions::make_delete_action(
  527. [&](const GUI::Action& action) {
  528. do_delete(ConfirmBeforeDelete::Yes, action);
  529. },
  530. window);
  531. delete_action->set_enabled(false);
  532. auto go_back_action = GUI::CommonActions::make_go_back_action(
  533. [&](auto&) {
  534. directory_view.open_previous_directory();
  535. },
  536. window);
  537. auto go_forward_action = GUI::CommonActions::make_go_forward_action(
  538. [&](auto&) {
  539. directory_view.open_next_directory();
  540. },
  541. window);
  542. auto go_home_action = GUI::CommonActions::make_go_home_action(
  543. [&](auto&) {
  544. directory_view.open(Core::StandardPaths::home_directory());
  545. },
  546. window);
  547. GUI::Clipboard::the().on_change = [&](const String& data_type) {
  548. auto current_location = directory_view.path();
  549. paste_action->set_enabled(data_type == "text/uri-list" && access(current_location.characters(), W_OK) == 0);
  550. };
  551. auto menubar = GUI::MenuBar::construct();
  552. auto& app_menu = menubar->add_menu("File Manager");
  553. app_menu.add_action(mkdir_action);
  554. app_menu.add_action(touch_action);
  555. app_menu.add_action(copy_action);
  556. app_menu.add_action(paste_action);
  557. app_menu.add_action(delete_action);
  558. app_menu.add_action(open_terminal_action);
  559. app_menu.add_separator();
  560. app_menu.add_action(properties_action);
  561. app_menu.add_separator();
  562. app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  563. GUI::Application::the()->quit();
  564. }));
  565. auto& view_menu = menubar->add_menu("View");
  566. view_menu.add_action(*view_as_icons_action);
  567. view_menu.add_action(*view_as_table_action);
  568. view_menu.add_action(*view_as_columns_action);
  569. view_menu.add_separator();
  570. view_menu.add_action(GUI::Action::create_checkable("Show dotfiles", { Mod_Ctrl, Key_H }, [&](auto& action) {
  571. directory_view.model().set_should_show_dotfiles(action.is_checked());
  572. }));
  573. auto& go_menu = menubar->add_menu("Go");
  574. go_menu.add_action(go_back_action);
  575. go_menu.add_action(go_forward_action);
  576. go_menu.add_action(open_parent_directory_action);
  577. go_menu.add_action(go_home_action);
  578. go_menu.add_action(GUI::Action::create(
  579. "Go to location...", { Mod_Ctrl, Key_L }, [&](auto&) {
  580. location_textbox.select_all();
  581. location_textbox.set_focus(true);
  582. }));
  583. auto& help_menu = menubar->add_menu("Help");
  584. help_menu.add_action(GUI::Action::create("About", [&](auto&) {
  585. GUI::AboutDialog::show("File Manager", Gfx::Bitmap::load_from_file("/res/icons/32x32/filetype-folder.png"), window);
  586. }));
  587. GUI::Application::the()->set_menubar(move(menubar));
  588. main_toolbar.add_action(go_back_action);
  589. main_toolbar.add_action(go_forward_action);
  590. main_toolbar.add_action(open_parent_directory_action);
  591. main_toolbar.add_action(go_home_action);
  592. main_toolbar.add_separator();
  593. main_toolbar.add_action(mkdir_action);
  594. main_toolbar.add_action(touch_action);
  595. main_toolbar.add_action(copy_action);
  596. main_toolbar.add_action(paste_action);
  597. main_toolbar.add_action(delete_action);
  598. main_toolbar.add_action(open_terminal_action);
  599. main_toolbar.add_separator();
  600. main_toolbar.add_action(*view_as_icons_action);
  601. main_toolbar.add_action(*view_as_table_action);
  602. main_toolbar.add_action(*view_as_columns_action);
  603. directory_view.on_path_change = [&](const String& new_path) {
  604. window->set_title(String::format("%s - File Manager", new_path.characters()));
  605. location_textbox.set_text(new_path);
  606. auto new_index = directories_model->index(new_path, GUI::FileSystemModel::Column::Name);
  607. if (new_index.is_valid()) {
  608. tree_view.selection().set(new_index);
  609. tree_view.scroll_into_view(new_index, Orientation::Vertical);
  610. tree_view.update();
  611. }
  612. struct stat st;
  613. if (lstat(new_path.characters(), &st)) {
  614. perror("stat");
  615. return;
  616. }
  617. auto can_write_in_path = access(new_path.characters(), W_OK) == 0;
  618. mkdir_action->set_enabled(can_write_in_path);
  619. touch_action->set_enabled(can_write_in_path);
  620. paste_action->set_enabled(can_write_in_path && GUI::Clipboard::the().type() == "text/uri-list");
  621. go_forward_action->set_enabled(directory_view.path_history_position() < directory_view.path_history_size() - 1);
  622. go_back_action->set_enabled(directory_view.path_history_position() > 0);
  623. open_parent_directory_action->set_enabled(new_path != "/");
  624. };
  625. directory_view.on_error = [&](int, const char* error_string, bool quit) {
  626. auto error_message = String::format("Could not read directory: %s", error_string);
  627. GUI::MessageBox::show(window, error_message, "File Manager", GUI::MessageBox::Type::Error);
  628. if (quit)
  629. exit(1);
  630. };
  631. directory_view.on_status_message = [&](const StringView& message) {
  632. statusbar.set_text(message);
  633. };
  634. directory_view.on_thumbnail_progress = [&](int done, int total) {
  635. if (done == total) {
  636. progressbar.set_visible(false);
  637. return;
  638. }
  639. progressbar.set_range(0, total);
  640. progressbar.set_value(done);
  641. progressbar.set_visible(true);
  642. };
  643. directory_view.on_selection_change = [&](GUI::AbstractView& view) {
  644. // FIXME: Figure out how we can enable/disable the paste action, based on clipboard contents.
  645. auto selection = view.selection();
  646. delete_action->set_enabled(!selection.is_empty() && access(directory_view.path().characters(), W_OK) == 0);
  647. copy_action->set_enabled(!selection.is_empty());
  648. };
  649. directory_context_menu->add_action(copy_action);
  650. directory_context_menu->add_action(folder_specific_paste_action);
  651. directory_context_menu->add_action(delete_action);
  652. directory_context_menu->add_separator();
  653. directory_context_menu->add_action(properties_action);
  654. directory_view_context_menu->add_action(mkdir_action);
  655. directory_view_context_menu->add_action(touch_action);
  656. directory_view_context_menu->add_action(paste_action);
  657. directory_view_context_menu->add_action(open_terminal_action);
  658. directory_view_context_menu->add_separator();
  659. directory_view_context_menu->add_action(properties_action);
  660. tree_view_directory_context_menu->add_action(copy_action);
  661. tree_view_directory_context_menu->add_action(paste_action);
  662. tree_view_directory_context_menu->add_action(delete_action);
  663. tree_view_directory_context_menu->add_separator();
  664. tree_view_directory_context_menu->add_action(properties_action);
  665. tree_view_directory_context_menu->add_separator();
  666. tree_view_directory_context_menu->add_action(mkdir_action);
  667. tree_view_directory_context_menu->add_action(touch_action);
  668. RefPtr<GUI::Menu> file_context_menu;
  669. NonnullRefPtrVector<LauncherHandler> current_file_handlers;
  670. RefPtr<GUI::Action> file_context_menu_action_default_action;
  671. directory_view.on_launch = [&](const AK::URL&, const LauncherHandler& launcher_handler) {
  672. pid_t child;
  673. if (launcher_handler.details().launcher_type == Desktop::Launcher::LauncherType::Application) {
  674. const char* argv[] = { launcher_handler.details().name.characters(), nullptr };
  675. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  676. } else {
  677. for (auto& path : selected_file_paths()) {
  678. const char* argv[] = { launcher_handler.details().name.characters(), path.characters(), nullptr };
  679. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  680. }
  681. }
  682. };
  683. directory_view.on_context_menu_request = [&](const GUI::AbstractView&, const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  684. if (index.is_valid()) {
  685. auto& node = directory_view.model().node(index);
  686. if (node.is_directory()) {
  687. auto should_get_enabled = access(node.full_path(directory_view.model()).characters(), W_OK) == 0 && GUI::Clipboard::the().type() == "text/uri-list";
  688. folder_specific_paste_action->set_enabled(should_get_enabled);
  689. directory_context_menu->popup(event.screen_position());
  690. } else {
  691. auto full_path = node.full_path(directory_view.model());
  692. current_file_handlers = directory_view.get_launch_handlers(full_path);
  693. file_context_menu = GUI::Menu::construct("Directory View File");
  694. file_context_menu->add_action(copy_action);
  695. file_context_menu->add_action(paste_action);
  696. file_context_menu->add_action(delete_action);
  697. file_context_menu->add_separator();
  698. bool added_open_menu_items = false;
  699. auto default_file_handler = directory_view.get_default_launch_handler(current_file_handlers);
  700. if (default_file_handler) {
  701. auto file_open_action = default_file_handler->create_launch_action([&, full_path = move(full_path)](auto& launcher_handler) {
  702. directory_view.on_launch(URL::create_with_file_protocol(full_path), launcher_handler);
  703. });
  704. if (default_file_handler->details().launcher_type == Desktop::Launcher::LauncherType::Application)
  705. file_open_action->set_text(String::format("Run %s", file_open_action->text().characters()));
  706. else
  707. file_open_action->set_text(String::format("Open in %s", file_open_action->text().characters()));
  708. file_context_menu_action_default_action = file_open_action;
  709. file_context_menu->add_action(move(file_open_action));
  710. added_open_menu_items = true;
  711. } else {
  712. file_context_menu_action_default_action.clear();
  713. }
  714. if (current_file_handlers.size() > 1) {
  715. added_open_menu_items = true;
  716. auto& file_open_with_menu = file_context_menu->add_submenu("Open with");
  717. for (auto& handler : current_file_handlers) {
  718. if (&handler == default_file_handler.ptr())
  719. continue;
  720. file_open_with_menu.add_action(handler.create_launch_action([&, full_path = move(full_path)](auto& launcher_handler) {
  721. directory_view.on_launch(URL::create_with_file_protocol(full_path), launcher_handler);
  722. }));
  723. }
  724. }
  725. if (added_open_menu_items)
  726. file_context_menu->add_separator();
  727. file_context_menu->add_action(properties_action);
  728. file_context_menu->popup(event.screen_position(), file_context_menu_action_default_action);
  729. }
  730. } else {
  731. directory_view_context_menu->popup(event.screen_position());
  732. }
  733. };
  734. directory_view.on_drop = [&](const GUI::AbstractView&, const GUI::ModelIndex& index, const GUI::DropEvent& event) {
  735. if (!event.mime_data().has_urls())
  736. return;
  737. auto urls = event.mime_data().urls();
  738. if (urls.is_empty()) {
  739. dbg() << "No files to drop";
  740. return;
  741. }
  742. auto& target_node = directory_view.model().node(index);
  743. if (!target_node.is_directory())
  744. return;
  745. for (auto& url_to_copy : urls) {
  746. if (!url_to_copy.is_valid() || url_to_copy.path() == target_node.full_path(directory_view.model()))
  747. continue;
  748. auto new_path = String::format("%s/%s",
  749. target_node.full_path(directory_view.model()).characters(),
  750. LexicalPath(url_to_copy.path()).basename().characters());
  751. if (url_to_copy.path() == new_path)
  752. continue;
  753. if (!FileUtils::copy_file_or_directory(url_to_copy.path(), new_path)) {
  754. auto error_message = String::format("Could not copy %s into %s.",
  755. url_to_copy.to_string().characters(),
  756. new_path.characters());
  757. GUI::MessageBox::show(window, error_message, "File Manager", GUI::MessageBox::Type::Error);
  758. } else {
  759. refresh_tree_view();
  760. }
  761. }
  762. };
  763. tree_view.on_selection = [&](const GUI::ModelIndex& index) {
  764. if (directories_model->m_previously_selected_index.is_valid())
  765. directories_model->update_node_on_selection(directories_model->m_previously_selected_index, false);
  766. directories_model->update_node_on_selection(index, true);
  767. directories_model->m_previously_selected_index = index;
  768. };
  769. tree_view.on_selection_change = [&] {
  770. if (tree_view.selection().is_empty())
  771. return;
  772. auto path = directories_model->full_path(tree_view.selection().first());
  773. if (directory_view.path() == path)
  774. return;
  775. directory_view.open(path);
  776. copy_action->set_enabled(!tree_view.selection().is_empty());
  777. delete_action->set_enabled(!tree_view.selection().is_empty());
  778. };
  779. tree_view.on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  780. if (index.is_valid()) {
  781. tree_view_directory_context_menu->popup(event.screen_position());
  782. }
  783. };
  784. directory_view.open(initial_location);
  785. directory_view.set_focus(true);
  786. paste_action->set_enabled(GUI::Clipboard::the().type() == "text/uri-list" && access(initial_location.characters(), W_OK) == 0);
  787. window->show();
  788. window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-folder.png"));
  789. // Read direcory read mode from config.
  790. auto dir_view_mode = config->read_entry("DirectoryView", "ViewMode", "Icon");
  791. if (dir_view_mode.contains("Table")) {
  792. directory_view.set_view_mode(DirectoryView::ViewMode::Table);
  793. view_as_table_action->set_checked(true);
  794. } else if (dir_view_mode.contains("Columns")) {
  795. directory_view.set_view_mode(DirectoryView::ViewMode::Columns);
  796. view_as_columns_action->set_checked(true);
  797. } else {
  798. directory_view.set_view_mode(DirectoryView::ViewMode::Icon);
  799. view_as_icons_action->set_checked(true);
  800. }
  801. // Write window position to config file on close request.
  802. window->on_close_request = [&] {
  803. config->write_num_entry("Window", "Left", window->x());
  804. config->write_num_entry("Window", "Top", window->y());
  805. config->write_num_entry("Window", "Width", window->width());
  806. config->write_num_entry("Window", "Heigth", window->height());
  807. config->sync();
  808. return GUI::Window::CloseRequestDecision::Close;
  809. };
  810. return GUI::Application::the()->exec();
  811. }