DirectoryView.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sam Atkins <atkinssj@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "DirectoryView.h"
  8. #include "FileUtils.h"
  9. #include <AK/LexicalPath.h>
  10. #include <AK/NumberFormat.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibCore/File.h>
  13. #include <LibCore/MimeData.h>
  14. #include <LibCore/StandardPaths.h>
  15. #include <LibGUI/FileIconProvider.h>
  16. #include <LibGUI/InputBox.h>
  17. #include <LibGUI/Label.h>
  18. #include <LibGUI/MessageBox.h>
  19. #include <LibGUI/ModelEditingDelegate.h>
  20. #include <LibGUI/SortingProxyModel.h>
  21. #include <serenity.h>
  22. #include <spawn.h>
  23. #include <stdio.h>
  24. #include <unistd.h>
  25. namespace FileManager {
  26. void spawn_terminal(String const& directory)
  27. {
  28. posix_spawn_file_actions_t spawn_actions;
  29. posix_spawn_file_actions_init(&spawn_actions);
  30. posix_spawn_file_actions_addchdir(&spawn_actions, directory.characters());
  31. pid_t pid;
  32. char const* argv[] = { "Terminal", nullptr };
  33. if ((errno = posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) {
  34. perror("posix_spawn");
  35. } else {
  36. if (disown(pid) < 0)
  37. perror("disown");
  38. }
  39. posix_spawn_file_actions_destroy(&spawn_actions);
  40. }
  41. NonnullRefPtr<GUI::Action> LauncherHandler::create_launch_action(Function<void(LauncherHandler const&)> launch_handler)
  42. {
  43. auto icon = GUI::FileIconProvider::icon_for_executable(details().executable).bitmap_for_size(16);
  44. return GUI::Action::create(details().name, move(icon), [this, launch_handler = move(launch_handler)](auto&) {
  45. launch_handler(*this);
  46. });
  47. }
  48. RefPtr<LauncherHandler> DirectoryView::get_default_launch_handler(NonnullRefPtrVector<LauncherHandler> const& handlers)
  49. {
  50. // If this is an application, pick it first
  51. for (size_t i = 0; i < handlers.size(); i++) {
  52. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::Application)
  53. return handlers[i];
  54. }
  55. // If there's a handler preferred by the user, pick this first
  56. for (size_t i = 0; i < handlers.size(); i++) {
  57. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserPreferred)
  58. return handlers[i];
  59. }
  60. // Otherwise, use the user's default, if available
  61. for (size_t i = 0; i < handlers.size(); i++) {
  62. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserDefault)
  63. return handlers[i];
  64. }
  65. // If still no match, use the first one we find
  66. if (!handlers.is_empty()) {
  67. return handlers[0];
  68. }
  69. return {};
  70. }
  71. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(URL const& url)
  72. {
  73. NonnullRefPtrVector<LauncherHandler> handlers;
  74. for (auto& h : Desktop::Launcher::get_handlers_with_details_for_url(url)) {
  75. handlers.append(adopt_ref(*new LauncherHandler(h)));
  76. }
  77. return handlers;
  78. }
  79. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(String const& path)
  80. {
  81. return get_launch_handlers(URL::create_with_file_protocol(path));
  82. }
  83. void DirectoryView::handle_activation(GUI::ModelIndex const& index)
  84. {
  85. if (!index.is_valid())
  86. return;
  87. dbgln("on activation: {},{}, this={:p}, m_model={:p}", index.row(), index.column(), this, m_model.ptr());
  88. auto& node = this->node(index);
  89. auto path = node.full_path();
  90. struct stat st;
  91. if (stat(path.characters(), &st) < 0) {
  92. perror("stat");
  93. return;
  94. }
  95. if (S_ISDIR(st.st_mode)) {
  96. if (is_desktop()) {
  97. Desktop::Launcher::open(URL::create_with_file_protocol(path));
  98. return;
  99. }
  100. open(path);
  101. return;
  102. }
  103. auto url = URL::create_with_file_protocol(path);
  104. auto launcher_handlers = get_launch_handlers(url);
  105. auto default_launcher = get_default_launch_handler(launcher_handlers);
  106. if (default_launcher) {
  107. auto launch_origin_rect = current_view().to_widget_rect(current_view().content_rect(index)).translated(current_view().screen_relative_rect().location());
  108. setenv("__libgui_launch_origin_rect", String::formatted("{},{},{},{}", launch_origin_rect.x(), launch_origin_rect.y(), launch_origin_rect.width(), launch_origin_rect.height()).characters(), 1);
  109. launch(url, *default_launcher);
  110. unsetenv("__libgui_launch_origin_rect");
  111. } else {
  112. auto error_message = String::formatted("Could not open {}", path);
  113. GUI::MessageBox::show(window(), error_message, "File Manager", GUI::MessageBox::Type::Error);
  114. }
  115. }
  116. DirectoryView::DirectoryView(Mode mode)
  117. : m_mode(mode)
  118. , m_model(GUI::FileSystemModel::create({}))
  119. , m_sorting_model(GUI::SortingProxyModel::create(m_model))
  120. {
  121. set_active_widget(nullptr);
  122. set_content_margins({ 2, 2, 2, 2 });
  123. setup_actions();
  124. m_error_label = add<GUI::Label>();
  125. m_error_label->set_font(m_error_label->font().bold_variant());
  126. setup_model();
  127. setup_icon_view();
  128. if (mode != Mode::Desktop) {
  129. setup_columns_view();
  130. setup_table_view();
  131. }
  132. set_view_mode(ViewMode::Icon);
  133. }
  134. GUI::FileSystemModel::Node const& DirectoryView::node(GUI::ModelIndex const& index) const
  135. {
  136. return model().node(m_sorting_model->map_to_source(index));
  137. }
  138. void DirectoryView::setup_model()
  139. {
  140. m_model->on_directory_change_error = [this](int, char const* error_string) {
  141. auto failed_path = m_model->root_path();
  142. auto error_message = String::formatted("Could not read {}:\n{}", failed_path, error_string);
  143. m_error_label->set_text(error_message);
  144. set_active_widget(m_error_label);
  145. m_mkdir_action->set_enabled(false);
  146. m_touch_action->set_enabled(false);
  147. add_path_to_history(model().root_path());
  148. if (on_path_change)
  149. on_path_change(failed_path, false, false);
  150. };
  151. m_model->on_rename_error = [this](int, char const* error_string) {
  152. GUI::MessageBox::show_error(window(), String::formatted("Unable to rename file: {}", error_string));
  153. };
  154. m_model->on_complete = [this] {
  155. if (m_table_view)
  156. m_table_view->selection().clear();
  157. if (m_icon_view)
  158. m_icon_view->selection().clear();
  159. add_path_to_history(model().root_path());
  160. bool can_write_in_path = access(model().root_path().characters(), W_OK) == 0;
  161. m_mkdir_action->set_enabled(can_write_in_path);
  162. m_touch_action->set_enabled(can_write_in_path);
  163. if (on_path_change)
  164. on_path_change(model().root_path(), true, can_write_in_path);
  165. };
  166. m_model->register_client(*this);
  167. m_model->on_thumbnail_progress = [this](int done, int total) {
  168. if (on_thumbnail_progress)
  169. on_thumbnail_progress(done, total);
  170. };
  171. if (is_desktop())
  172. m_model->set_root_path(Core::StandardPaths::desktop_directory());
  173. }
  174. void DirectoryView::setup_icon_view()
  175. {
  176. m_icon_view = add<GUI::IconView>();
  177. m_icon_view->set_should_hide_unnecessary_scrollbars(true);
  178. m_icon_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  179. m_icon_view->set_editable(true);
  180. m_icon_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  181. m_icon_view->aid_create_editing_delegate = [](auto&) {
  182. return make<GUI::StringModelEditingDelegate>();
  183. };
  184. if (is_desktop()) {
  185. m_icon_view->set_frame_shape(Gfx::FrameShape::NoFrame);
  186. m_icon_view->set_frame_thickness(0);
  187. m_icon_view->set_scrollbars_enabled(false);
  188. m_icon_view->set_fill_with_background_color(false);
  189. m_icon_view->set_draw_item_text_with_shadow(true);
  190. m_icon_view->set_flow_direction(GUI::IconView::FlowDirection::TopToBottom);
  191. }
  192. m_icon_view->set_model(m_sorting_model);
  193. m_icon_view->set_model_column(GUI::FileSystemModel::Column::Name);
  194. m_icon_view->on_activation = [&](auto& index) {
  195. handle_activation(index);
  196. };
  197. m_icon_view->on_selection_change = [this] {
  198. handle_selection_change();
  199. };
  200. m_icon_view->on_context_menu_request = [this](auto& index, auto& event) {
  201. if (on_context_menu_request)
  202. on_context_menu_request(index, event);
  203. };
  204. m_icon_view->on_drop = [this](auto& index, auto& event) {
  205. handle_drop(index, event);
  206. };
  207. }
  208. void DirectoryView::setup_columns_view()
  209. {
  210. m_columns_view = add<GUI::ColumnsView>();
  211. m_columns_view->set_should_hide_unnecessary_scrollbars(true);
  212. m_columns_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  213. m_columns_view->set_editable(true);
  214. m_columns_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  215. m_columns_view->aid_create_editing_delegate = [](auto&) {
  216. return make<GUI::StringModelEditingDelegate>();
  217. };
  218. m_columns_view->set_model(m_sorting_model);
  219. m_columns_view->set_model_column(GUI::FileSystemModel::Column::Name);
  220. m_columns_view->on_activation = [&](auto& index) {
  221. handle_activation(index);
  222. };
  223. m_columns_view->on_selection_change = [this] {
  224. handle_selection_change();
  225. };
  226. m_columns_view->on_context_menu_request = [this](auto& index, auto& event) {
  227. if (on_context_menu_request)
  228. on_context_menu_request(index, event);
  229. };
  230. m_columns_view->on_drop = [this](auto& index, auto& event) {
  231. handle_drop(index, event);
  232. };
  233. }
  234. void DirectoryView::setup_table_view()
  235. {
  236. m_table_view = add<GUI::TableView>();
  237. m_table_view->set_should_hide_unnecessary_scrollbars(true);
  238. m_table_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  239. m_table_view->set_editable(true);
  240. m_table_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  241. m_table_view->aid_create_editing_delegate = [](auto&) {
  242. return make<GUI::StringModelEditingDelegate>();
  243. };
  244. m_table_view->set_model(m_sorting_model);
  245. m_table_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  246. m_table_view->on_activation = [&](auto& index) {
  247. handle_activation(index);
  248. };
  249. m_table_view->on_selection_change = [this] {
  250. handle_selection_change();
  251. };
  252. m_table_view->on_context_menu_request = [this](auto& index, auto& event) {
  253. if (on_context_menu_request)
  254. on_context_menu_request(index, event);
  255. };
  256. m_table_view->on_drop = [this](auto& index, auto& event) {
  257. handle_drop(index, event);
  258. };
  259. }
  260. DirectoryView::~DirectoryView()
  261. {
  262. m_model->unregister_client(*this);
  263. }
  264. void DirectoryView::model_did_update(unsigned flags)
  265. {
  266. if (flags & GUI::Model::UpdateFlag::InvalidateAllIndices) {
  267. for_each_view_implementation([](auto& view) {
  268. view.selection().clear();
  269. });
  270. }
  271. update_statusbar();
  272. }
  273. void DirectoryView::set_view_mode(ViewMode mode)
  274. {
  275. if (m_view_mode == mode)
  276. return;
  277. m_view_mode = mode;
  278. update();
  279. if (mode == ViewMode::Table) {
  280. set_active_widget(m_table_view);
  281. return;
  282. }
  283. if (mode == ViewMode::Columns) {
  284. set_active_widget(m_columns_view);
  285. return;
  286. }
  287. if (mode == ViewMode::Icon) {
  288. set_active_widget(m_icon_view);
  289. return;
  290. }
  291. VERIFY_NOT_REACHED();
  292. }
  293. void DirectoryView::add_path_to_history(String path)
  294. {
  295. if (m_path_history.size() && m_path_history.at(m_path_history_position) == path)
  296. return;
  297. if (m_path_history_position < m_path_history.size())
  298. m_path_history.resize(m_path_history_position + 1);
  299. m_path_history.append(move(path));
  300. m_path_history_position = m_path_history.size() - 1;
  301. }
  302. void DirectoryView::open(String const& path)
  303. {
  304. auto real_path = Core::File::real_path_for(path);
  305. if (model().root_path() == real_path) {
  306. model().invalidate();
  307. return;
  308. }
  309. set_active_widget(&current_view());
  310. model().set_root_path(real_path);
  311. }
  312. void DirectoryView::set_status_message(StringView const& message)
  313. {
  314. if (on_status_message)
  315. on_status_message(message);
  316. }
  317. void DirectoryView::open_parent_directory()
  318. {
  319. auto path = String::formatted("{}/..", model().root_path());
  320. model().set_root_path(path);
  321. }
  322. void DirectoryView::refresh()
  323. {
  324. model().invalidate();
  325. }
  326. void DirectoryView::open_previous_directory()
  327. {
  328. if (m_path_history_position > 0) {
  329. set_active_widget(&current_view());
  330. m_path_history_position--;
  331. model().set_root_path(m_path_history[m_path_history_position]);
  332. }
  333. }
  334. void DirectoryView::open_next_directory()
  335. {
  336. if (m_path_history_position < m_path_history.size() - 1) {
  337. set_active_widget(&current_view());
  338. m_path_history_position++;
  339. model().set_root_path(m_path_history[m_path_history_position]);
  340. }
  341. }
  342. void DirectoryView::update_statusbar()
  343. {
  344. // If we're triggered during widget construction, just ignore it.
  345. if (m_view_mode == ViewMode::Invalid)
  346. return;
  347. StringBuilder builder;
  348. if (current_view().selection().is_empty()) {
  349. int total_item_count = model().row_count();
  350. size_t total_size = model().node({}).total_size;
  351. builder.appendff("{} item{} ({})", total_item_count, total_item_count != 1 ? "s" : "", human_readable_size(total_size));
  352. set_status_message(builder.string_view());
  353. return;
  354. }
  355. int selected_item_count = current_view().selection().size();
  356. size_t selected_byte_count = 0;
  357. current_view().selection().for_each_index([&](auto& index) {
  358. auto const& node = this->node(index);
  359. selected_byte_count += node.size;
  360. });
  361. builder.appendff("{} item{} selected ({})", selected_item_count, selected_item_count != 1 ? "s" : "", human_readable_size(selected_byte_count));
  362. if (selected_item_count == 1) {
  363. auto& node = this->node(current_view().selection().first());
  364. if (!node.symlink_target.is_empty()) {
  365. builder.append(" -> ");
  366. builder.append(node.symlink_target);
  367. }
  368. }
  369. set_status_message(builder.string_view());
  370. }
  371. void DirectoryView::set_should_show_dotfiles(bool show_dotfiles)
  372. {
  373. m_model->set_should_show_dotfiles(show_dotfiles);
  374. }
  375. void DirectoryView::launch(URL const&, LauncherHandler const& launcher_handler) const
  376. {
  377. pid_t child;
  378. if (launcher_handler.details().launcher_type == Desktop::Launcher::LauncherType::Application) {
  379. posix_spawn_file_actions_t spawn_actions;
  380. posix_spawn_file_actions_init(&spawn_actions);
  381. posix_spawn_file_actions_addchdir(&spawn_actions, path().characters());
  382. char const* argv[] = { launcher_handler.details().name.characters(), nullptr };
  383. posix_spawn(&child, launcher_handler.details().executable.characters(), &spawn_actions, nullptr, const_cast<char**>(argv), environ);
  384. if (disown(child) < 0)
  385. perror("disown");
  386. posix_spawn_file_actions_destroy(&spawn_actions);
  387. } else {
  388. for (auto& path : selected_file_paths()) {
  389. char const* argv[] = { launcher_handler.details().name.characters(), path.characters(), nullptr };
  390. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  391. if (disown(child) < 0)
  392. perror("disown");
  393. }
  394. }
  395. }
  396. Vector<String> DirectoryView::selected_file_paths() const
  397. {
  398. Vector<String> paths;
  399. auto& view = current_view();
  400. auto& model = *view.model();
  401. view.selection().for_each_index([&](GUI::ModelIndex const& index) {
  402. auto parent_index = model.parent_index(index);
  403. auto name_index = model.index(index.row(), GUI::FileSystemModel::Column::Name, parent_index);
  404. auto path = name_index.data(GUI::ModelRole::Custom).to_string();
  405. paths.append(path);
  406. });
  407. return paths;
  408. }
  409. void DirectoryView::do_delete(bool should_confirm)
  410. {
  411. auto paths = selected_file_paths();
  412. VERIFY(!paths.is_empty());
  413. delete_paths(paths, should_confirm, window());
  414. }
  415. void DirectoryView::handle_selection_change()
  416. {
  417. update_statusbar();
  418. bool can_modify = !current_view().selection().is_empty() && access(path().characters(), W_OK) == 0;
  419. m_delete_action->set_enabled(can_modify);
  420. m_force_delete_action->set_enabled(can_modify);
  421. m_rename_action->set_enabled(can_modify);
  422. if (on_selection_change)
  423. on_selection_change(current_view());
  424. }
  425. void DirectoryView::setup_actions()
  426. {
  427. m_mkdir_action = GUI::Action::create("&New Directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/mkdir.png"), [&](GUI::Action const&) {
  428. String value;
  429. if (GUI::InputBox::show(window(), value, "Enter name:", "New directory") == GUI::InputBox::ExecOK && !value.is_empty()) {
  430. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", path(), value));
  431. int rc = mkdir(new_dir_path.characters(), 0777);
  432. if (rc < 0) {
  433. auto saved_errno = errno;
  434. GUI::MessageBox::show(window(), String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  435. }
  436. }
  437. });
  438. m_touch_action = GUI::Action::create("New &File...", { Mod_Ctrl | Mod_Shift, Key_F }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png"), [&](GUI::Action const&) {
  439. String value;
  440. if (GUI::InputBox::show(window(), value, "Enter name:", "New file") == GUI::InputBox::ExecOK && !value.is_empty()) {
  441. auto new_file_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", path(), value));
  442. struct stat st;
  443. int rc = stat(new_file_path.characters(), &st);
  444. if ((rc < 0 && errno != ENOENT)) {
  445. auto saved_errno = errno;
  446. GUI::MessageBox::show(window(), String::formatted("stat(\"{}\") failed: {}", new_file_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  447. return;
  448. }
  449. if (rc == 0) {
  450. GUI::MessageBox::show(window(), String::formatted("{}: Already exists", new_file_path), "Error", GUI::MessageBox::Type::Error);
  451. return;
  452. }
  453. int fd = creat(new_file_path.characters(), 0666);
  454. if (fd < 0) {
  455. auto saved_errno = errno;
  456. GUI::MessageBox::show(window(), String::formatted("creat(\"{}\") failed: {}", new_file_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  457. return;
  458. }
  459. rc = close(fd);
  460. VERIFY(rc >= 0);
  461. }
  462. });
  463. m_open_terminal_action = GUI::Action::create("Open &Terminal Here", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-terminal.png"), [&](auto&) {
  464. spawn_terminal(path());
  465. });
  466. m_delete_action = GUI::CommonActions::make_delete_action([this](auto&) { do_delete(true); }, window());
  467. m_rename_action = GUI::CommonActions::make_rename_action([this](auto&) {
  468. current_view().begin_editing(current_view().cursor_index());
  469. },
  470. window());
  471. m_force_delete_action = GUI::Action::create(
  472. "Delete Without Confirmation", { Mod_Shift, Key_Delete },
  473. [this](auto&) { do_delete(false); },
  474. window());
  475. }
  476. void DirectoryView::handle_drop(GUI::ModelIndex const& index, GUI::DropEvent const& event)
  477. {
  478. if (!event.mime_data().has_urls())
  479. return;
  480. auto urls = event.mime_data().urls();
  481. if (urls.is_empty()) {
  482. dbgln("No files to drop");
  483. return;
  484. }
  485. auto& target_node = node(index);
  486. if (!target_node.is_directory())
  487. return;
  488. bool had_accepted_drop = false;
  489. Vector<String> paths_to_copy;
  490. for (auto& url_to_copy : urls) {
  491. if (!url_to_copy.is_valid() || url_to_copy.path() == target_node.full_path())
  492. continue;
  493. auto new_path = String::formatted("{}/{}", target_node.full_path(), LexicalPath::basename(url_to_copy.path()));
  494. if (url_to_copy.path() == new_path)
  495. continue;
  496. paths_to_copy.append(url_to_copy.path());
  497. had_accepted_drop = true;
  498. }
  499. if (!paths_to_copy.is_empty())
  500. run_file_operation(FileOperation::Copy, paths_to_copy, target_node.full_path(), window());
  501. if (had_accepted_drop && on_accepted_drop)
  502. on_accepted_drop();
  503. }
  504. }