DirectoryView.cpp 24 KB

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