DirectoryView.cpp 24 KB

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