DirectoryView.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 <AK/LexicalPath.h>
  29. #include <AK/NumberFormat.h>
  30. #include <AK/StringBuilder.h>
  31. #include <LibCore/MimeData.h>
  32. #include <LibCore/StandardPaths.h>
  33. #include <LibGUI/InputBox.h>
  34. #include <LibGUI/Label.h>
  35. #include <LibGUI/MessageBox.h>
  36. #include <LibGUI/ModelEditingDelegate.h>
  37. #include <LibGUI/SortingProxyModel.h>
  38. #include <serenity.h>
  39. #include <spawn.h>
  40. #include <stdio.h>
  41. #include <unistd.h>
  42. namespace FileManager {
  43. NonnullRefPtr<GUI::Action> LauncherHandler::create_launch_action(Function<void(const LauncherHandler&)> launch_handler)
  44. {
  45. RefPtr<Gfx::Bitmap> icon;
  46. auto icon_file = details().icons.get("16x16");
  47. if (icon_file.has_value())
  48. icon = Gfx::Bitmap::load_from_file(icon_file.value());
  49. return GUI::Action::create(details().name, move(icon), [this, launch_handler = move(launch_handler)](auto&) {
  50. launch_handler(*this);
  51. });
  52. }
  53. RefPtr<LauncherHandler> DirectoryView::get_default_launch_handler(const NonnullRefPtrVector<LauncherHandler>& handlers)
  54. {
  55. // If this is an application, pick it first
  56. for (size_t i = 0; i < handlers.size(); i++) {
  57. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::Application)
  58. return handlers[i];
  59. }
  60. // If there's a handler preferred by the user, pick this first
  61. for (size_t i = 0; i < handlers.size(); i++) {
  62. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserPreferred)
  63. return handlers[i];
  64. }
  65. // Otherwise, use the user's default, if available
  66. for (size_t i = 0; i < handlers.size(); i++) {
  67. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserDefault)
  68. return handlers[i];
  69. }
  70. // If still no match, use the first one we find
  71. if (!handlers.is_empty()) {
  72. return handlers[0];
  73. }
  74. return {};
  75. }
  76. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(const URL& url)
  77. {
  78. NonnullRefPtrVector<LauncherHandler> handlers;
  79. for (auto& h : Desktop::Launcher::get_handlers_with_details_for_url(url)) {
  80. handlers.append(adopt(*new LauncherHandler(h)));
  81. }
  82. return handlers;
  83. }
  84. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(const String& path)
  85. {
  86. return get_launch_handlers(URL::create_with_file_protocol(path));
  87. }
  88. void DirectoryView::handle_activation(const GUI::ModelIndex& index)
  89. {
  90. if (!index.is_valid())
  91. return;
  92. dbgln("on activation: {},{}, this={:p}, m_model={:p}", index.row(), index.column(), this, m_model.ptr());
  93. auto& node = this->node(index);
  94. auto path = node.full_path();
  95. struct stat st;
  96. if (stat(path.characters(), &st) < 0) {
  97. perror("stat");
  98. return;
  99. }
  100. if (S_ISDIR(st.st_mode)) {
  101. if (is_desktop()) {
  102. Desktop::Launcher::open(URL::create_with_file_protocol(path));
  103. return;
  104. }
  105. open(path);
  106. return;
  107. }
  108. auto url = URL::create_with_file_protocol(path);
  109. auto launcher_handlers = get_launch_handlers(url);
  110. auto default_launcher = get_default_launch_handler(launcher_handlers);
  111. if (default_launcher) {
  112. launch(url, *default_launcher);
  113. } else {
  114. auto error_message = String::format("Could not open %s", path.characters());
  115. GUI::MessageBox::show(window(), error_message, "File Manager", 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(GUI::SortingProxyModel::create(m_model))
  122. {
  123. set_active_widget(nullptr);
  124. set_content_margins({ 2, 2, 2, 2 });
  125. setup_actions();
  126. m_error_label = add<GUI::Label>();
  127. m_error_label->set_font(m_error_label->font().bold_family_font());
  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. const GUI::FileSystemModel::Node& DirectoryView::node(const GUI::ModelIndex& index) const
  137. {
  138. return model().node(m_sorting_model->map_to_source(index));
  139. }
  140. void DirectoryView::setup_model()
  141. {
  142. m_model->set_root_path(Core::StandardPaths::desktop_directory());
  143. m_model->on_error = [this](int, const char* error_string) {
  144. auto failed_path = m_model->root_path();
  145. auto error_message = String::formatted("Could not read {}:\n{}", failed_path, error_string);
  146. m_error_label->set_text(error_message);
  147. set_active_widget(m_error_label);
  148. m_mkdir_action->set_enabled(false);
  149. m_touch_action->set_enabled(false);
  150. add_path_to_history(model().root_path());
  151. if (on_path_change)
  152. on_path_change(failed_path, false);
  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(), 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. }
  172. void DirectoryView::setup_icon_view()
  173. {
  174. m_icon_view = add<GUI::IconView>();
  175. m_icon_view->set_editable(true);
  176. m_icon_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  177. m_icon_view->aid_create_editing_delegate = [](auto&) {
  178. return make<GUI::StringModelEditingDelegate>();
  179. };
  180. if (is_desktop()) {
  181. m_icon_view->set_frame_shape(Gfx::FrameShape::NoFrame);
  182. m_icon_view->set_scrollbars_enabled(false);
  183. m_icon_view->set_fill_with_background_color(false);
  184. }
  185. m_icon_view->set_model(m_sorting_model);
  186. m_icon_view->set_model_column(GUI::FileSystemModel::Column::Name);
  187. m_icon_view->on_activation = [&](auto& index) {
  188. handle_activation(index);
  189. };
  190. m_icon_view->on_selection_change = [this] {
  191. handle_selection_change();
  192. };
  193. m_icon_view->on_context_menu_request = [this](auto& index, auto& event) {
  194. if (on_context_menu_request)
  195. on_context_menu_request(index, event);
  196. };
  197. m_icon_view->on_drop = [this](auto& index, auto& event) {
  198. handle_drop(index, event);
  199. };
  200. }
  201. void DirectoryView::setup_columns_view()
  202. {
  203. m_columns_view = add<GUI::ColumnsView>();
  204. m_columns_view->set_editable(true);
  205. m_columns_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  206. m_columns_view->aid_create_editing_delegate = [](auto&) {
  207. return make<GUI::StringModelEditingDelegate>();
  208. };
  209. m_columns_view->set_model(m_sorting_model);
  210. m_columns_view->set_model_column(GUI::FileSystemModel::Column::Name);
  211. m_columns_view->on_activation = [&](auto& index) {
  212. handle_activation(index);
  213. };
  214. m_columns_view->on_selection_change = [this] {
  215. handle_selection_change();
  216. };
  217. m_columns_view->on_context_menu_request = [this](auto& index, auto& event) {
  218. if (on_context_menu_request)
  219. on_context_menu_request(index, event);
  220. };
  221. m_columns_view->on_drop = [this](auto& index, auto& event) {
  222. handle_drop(index, event);
  223. };
  224. }
  225. void DirectoryView::setup_table_view()
  226. {
  227. m_table_view = add<GUI::TableView>();
  228. m_table_view->set_editable(true);
  229. m_table_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed);
  230. m_table_view->aid_create_editing_delegate = [](auto&) {
  231. return make<GUI::StringModelEditingDelegate>();
  232. };
  233. m_table_view->set_model(m_sorting_model);
  234. m_table_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  235. m_table_view->on_activation = [&](auto& index) {
  236. handle_activation(index);
  237. };
  238. m_table_view->on_selection_change = [this] {
  239. handle_selection_change();
  240. };
  241. m_table_view->on_context_menu_request = [this](auto& index, auto& event) {
  242. if (on_context_menu_request)
  243. on_context_menu_request(index, event);
  244. };
  245. m_table_view->on_drop = [this](auto& index, auto& event) {
  246. handle_drop(index, event);
  247. };
  248. }
  249. DirectoryView::~DirectoryView()
  250. {
  251. m_model->unregister_client(*this);
  252. }
  253. void DirectoryView::model_did_update(unsigned flags)
  254. {
  255. if (flags & GUI::Model::UpdateFlag::InvalidateAllIndexes) {
  256. for_each_view_implementation([](auto& view) {
  257. view.selection().clear();
  258. });
  259. }
  260. update_statusbar();
  261. }
  262. void DirectoryView::set_view_mode(ViewMode mode)
  263. {
  264. if (m_view_mode == mode)
  265. return;
  266. m_view_mode = mode;
  267. update();
  268. if (mode == ViewMode::Table) {
  269. set_active_widget(m_table_view);
  270. return;
  271. }
  272. if (mode == ViewMode::Columns) {
  273. set_active_widget(m_columns_view);
  274. return;
  275. }
  276. if (mode == ViewMode::Icon) {
  277. set_active_widget(m_icon_view);
  278. return;
  279. }
  280. ASSERT_NOT_REACHED();
  281. }
  282. void DirectoryView::add_path_to_history(const StringView& path)
  283. {
  284. if (m_path_history.size() && m_path_history.at(m_path_history_position) == path)
  285. return;
  286. if (m_path_history_position < m_path_history.size())
  287. m_path_history.resize(m_path_history_position + 1);
  288. m_path_history.append(path);
  289. m_path_history_position = m_path_history.size() - 1;
  290. }
  291. void DirectoryView::open(const StringView& path)
  292. {
  293. if (model().root_path() == path) {
  294. model().update();
  295. return;
  296. }
  297. set_active_widget(&current_view());
  298. model().set_root_path(path);
  299. }
  300. void DirectoryView::set_status_message(const StringView& message)
  301. {
  302. if (on_status_message)
  303. on_status_message(message);
  304. }
  305. void DirectoryView::open_parent_directory()
  306. {
  307. auto path = String::formatted("{}/..", model().root_path());
  308. model().set_root_path(path);
  309. }
  310. void DirectoryView::refresh()
  311. {
  312. model().update();
  313. }
  314. void DirectoryView::open_previous_directory()
  315. {
  316. if (m_path_history_position > 0) {
  317. m_path_history_position--;
  318. model().set_root_path(m_path_history[m_path_history_position]);
  319. }
  320. }
  321. void DirectoryView::open_next_directory()
  322. {
  323. if (m_path_history_position < m_path_history.size() - 1) {
  324. m_path_history_position++;
  325. model().set_root_path(m_path_history[m_path_history_position]);
  326. }
  327. }
  328. void DirectoryView::update_statusbar()
  329. {
  330. size_t total_size = model().node({}).total_size;
  331. if (current_view().selection().is_empty()) {
  332. set_status_message(String::formatted("{} item(s) ({})",
  333. model().row_count(),
  334. human_readable_size(total_size)));
  335. return;
  336. }
  337. int selected_item_count = current_view().selection().size();
  338. size_t selected_byte_count = 0;
  339. current_view().selection().for_each_index([&](auto& index) {
  340. auto& model = *current_view().model();
  341. auto size_index = model.index(index.row(), GUI::FileSystemModel::Column::Size, model.parent_index(index));
  342. auto file_size = size_index.data().to_i32();
  343. selected_byte_count += file_size;
  344. });
  345. StringBuilder builder;
  346. builder.append(String::number(selected_item_count));
  347. builder.append(" item");
  348. if (selected_item_count != 1)
  349. builder.append('s');
  350. builder.append(" selected (");
  351. builder.append(human_readable_size(selected_byte_count).characters());
  352. builder.append(')');
  353. if (selected_item_count == 1) {
  354. auto& node = this->node(current_view().selection().first());
  355. if (!node.symlink_target.is_empty()) {
  356. builder.append(" -> ");
  357. builder.append(node.symlink_target);
  358. }
  359. }
  360. set_status_message(builder.to_string());
  361. }
  362. void DirectoryView::set_should_show_dotfiles(bool show_dotfiles)
  363. {
  364. m_model->set_should_show_dotfiles(show_dotfiles);
  365. }
  366. void DirectoryView::launch(const URL&, const LauncherHandler& launcher_handler)
  367. {
  368. pid_t child;
  369. if (launcher_handler.details().launcher_type == Desktop::Launcher::LauncherType::Application) {
  370. const char* argv[] = { launcher_handler.details().name.characters(), nullptr };
  371. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  372. if (disown(child) < 0)
  373. perror("disown");
  374. } else {
  375. for (auto& path : selected_file_paths()) {
  376. const char* argv[] = { launcher_handler.details().name.characters(), path.characters(), nullptr };
  377. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  378. if (disown(child) < 0)
  379. perror("disown");
  380. }
  381. }
  382. }
  383. Vector<String> DirectoryView::selected_file_paths() const
  384. {
  385. Vector<String> paths;
  386. auto& view = current_view();
  387. auto& model = *view.model();
  388. view.selection().for_each_index([&](const GUI::ModelIndex& index) {
  389. auto parent_index = model.parent_index(index);
  390. auto name_index = model.index(index.row(), GUI::FileSystemModel::Column::Name, parent_index);
  391. auto path = name_index.data(GUI::ModelRole::Custom).to_string();
  392. paths.append(path);
  393. });
  394. return paths;
  395. }
  396. void DirectoryView::do_delete(bool should_confirm)
  397. {
  398. auto paths = selected_file_paths();
  399. ASSERT(!paths.is_empty());
  400. FileUtils::delete_paths(paths, should_confirm, window());
  401. }
  402. void DirectoryView::handle_selection_change()
  403. {
  404. update_statusbar();
  405. bool can_delete = !current_view().selection().is_empty() && access(path().characters(), W_OK) == 0;
  406. m_delete_action->set_enabled(can_delete);
  407. m_force_delete_action->set_enabled(can_delete);
  408. if (on_selection_change)
  409. on_selection_change(*m_table_view);
  410. }
  411. void DirectoryView::setup_actions()
  412. {
  413. m_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&) {
  414. String value;
  415. if (GUI::InputBox::show(value, window(), "Enter name:", "New directory") == GUI::InputBox::ExecOK && !value.is_empty()) {
  416. auto new_dir_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", path(), value));
  417. int rc = mkdir(new_dir_path.characters(), 0777);
  418. if (rc < 0) {
  419. auto saved_errno = errno;
  420. GUI::MessageBox::show(window(), String::formatted("mkdir(\"{}\") failed: {}", new_dir_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  421. }
  422. }
  423. });
  424. m_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&) {
  425. String value;
  426. if (GUI::InputBox::show(value, window(), "Enter name:", "New file") == GUI::InputBox::ExecOK && !value.is_empty()) {
  427. auto new_file_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", path(), value));
  428. struct stat st;
  429. int rc = stat(new_file_path.characters(), &st);
  430. if ((rc < 0 && errno != ENOENT)) {
  431. auto saved_errno = errno;
  432. GUI::MessageBox::show(window(), String::formatted("stat(\"{}\") failed: {}", new_file_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  433. return;
  434. }
  435. if (rc == 0) {
  436. GUI::MessageBox::show(window(), String::formatted("{}: Already exists", new_file_path), "Error", GUI::MessageBox::Type::Error);
  437. return;
  438. }
  439. int fd = creat(new_file_path.characters(), 0666);
  440. if (fd < 0) {
  441. auto saved_errno = errno;
  442. GUI::MessageBox::show(window(), String::format("creat(\"{}\") failed: {}", new_file_path, strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  443. return;
  444. }
  445. rc = close(fd);
  446. ASSERT(rc >= 0);
  447. }
  448. });
  449. m_open_terminal_action = GUI::Action::create("Open Terminal here...", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"), [&](auto&) {
  450. posix_spawn_file_actions_t spawn_actions;
  451. posix_spawn_file_actions_init(&spawn_actions);
  452. posix_spawn_file_actions_addchdir(&spawn_actions, path().characters());
  453. pid_t pid;
  454. const char* argv[] = { "Terminal", nullptr };
  455. if ((errno = posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) {
  456. perror("posix_spawn");
  457. } else {
  458. if (disown(pid) < 0)
  459. perror("disown");
  460. }
  461. posix_spawn_file_actions_destroy(&spawn_actions);
  462. });
  463. m_delete_action = GUI::CommonActions::make_delete_action([this](auto&) { do_delete(true); }, window());
  464. m_force_delete_action = GUI::Action::create(
  465. "Delete without confirmation", { Mod_Shift, Key_Delete },
  466. [this](auto&) { do_delete(false); },
  467. window());
  468. }
  469. void DirectoryView::handle_drop(const GUI::ModelIndex& index, const GUI::DropEvent& event)
  470. {
  471. if (!event.mime_data().has_urls())
  472. return;
  473. auto urls = event.mime_data().urls();
  474. if (urls.is_empty()) {
  475. dbgln("No files to drop");
  476. return;
  477. }
  478. auto& target_node = node(index);
  479. if (!target_node.is_directory())
  480. return;
  481. for (auto& url_to_copy : urls) {
  482. if (!url_to_copy.is_valid() || url_to_copy.path() == target_node.full_path())
  483. continue;
  484. auto new_path = String::formatted("{}/{}", target_node.full_path(), LexicalPath(url_to_copy.path()).basename());
  485. if (url_to_copy.path() == new_path)
  486. continue;
  487. if (!FileUtils::copy_file_or_directory(url_to_copy.path(), new_path)) {
  488. auto error_message = String::formatted("Could not copy {} into {}.", url_to_copy.to_string(), new_path);
  489. GUI::MessageBox::show(window(), error_message, "File Manager", GUI::MessageBox::Type::Error);
  490. }
  491. }
  492. };
  493. }