DirectoryView.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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/StandardPaths.h>
  32. #include <LibGUI/InputBox.h>
  33. #include <LibGUI/MessageBox.h>
  34. #include <LibGUI/SortingProxyModel.h>
  35. #include <serenity.h>
  36. #include <spawn.h>
  37. #include <stdio.h>
  38. #include <unistd.h>
  39. NonnullRefPtr<GUI::Action> LauncherHandler::create_launch_action(Function<void(const LauncherHandler&)> launch_handler)
  40. {
  41. RefPtr<Gfx::Bitmap> icon;
  42. auto icon_file = details().icons.get("16x16");
  43. if (icon_file.has_value())
  44. icon = Gfx::Bitmap::load_from_file(icon_file.value());
  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(const NonnullRefPtrVector<LauncherHandler>& 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(const URL& url)
  73. {
  74. NonnullRefPtrVector<LauncherHandler> handlers;
  75. for (auto& h : Desktop::Launcher::get_handlers_with_details_for_url(url)) {
  76. handlers.append(adopt(*new LauncherHandler(h)));
  77. }
  78. return handlers;
  79. }
  80. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(const String& path)
  81. {
  82. return get_launch_handlers(URL::create_with_file_protocol(path));
  83. }
  84. void DirectoryView::handle_activation(const GUI::ModelIndex& index)
  85. {
  86. if (!index.is_valid())
  87. return;
  88. dbgprintf("on activation: %d,%d, this=%p, m_model=%p\n", index.row(), index.column(), this, m_model.ptr());
  89. auto& node = this->node(index);
  90. auto path = node.full_path();
  91. struct stat st;
  92. if (stat(path.characters(), &st) < 0) {
  93. perror("stat");
  94. return;
  95. }
  96. if (S_ISDIR(st.st_mode)) {
  97. if (is_desktop()) {
  98. Desktop::Launcher::open(URL::create_with_file_protocol(path));
  99. return;
  100. }
  101. open(path);
  102. return;
  103. }
  104. auto url = URL::create_with_file_protocol(path);
  105. auto launcher_handlers = get_launch_handlers(url);
  106. auto default_launcher = get_default_launch_handler(launcher_handlers);
  107. if (default_launcher) {
  108. launch(url, *default_launcher);
  109. } else {
  110. auto error_message = String::format("Could not open %s", path.characters());
  111. GUI::MessageBox::show(window(), error_message, "File Manager", GUI::MessageBox::Type::Error);
  112. }
  113. }
  114. DirectoryView::DirectoryView(Mode mode)
  115. : m_mode(mode)
  116. , m_model(GUI::FileSystemModel::create())
  117. , m_sorting_model(GUI::SortingProxyModel::create(m_model))
  118. {
  119. set_active_widget(nullptr);
  120. set_content_margins({ 2, 2, 2, 2 });
  121. setup_actions();
  122. setup_model();
  123. setup_icon_view();
  124. if (mode != Mode::Desktop) {
  125. setup_columns_view();
  126. setup_table_view();
  127. }
  128. set_view_mode(ViewMode::Icon);
  129. }
  130. const GUI::FileSystemModel::Node& DirectoryView::node(const GUI::ModelIndex& index) const
  131. {
  132. return model().node(m_sorting_model->map_to_source(index));
  133. }
  134. void DirectoryView::setup_model()
  135. {
  136. m_model->set_root_path(Core::StandardPaths::desktop_directory());
  137. m_model->on_error = [this](int error, const char* error_string) {
  138. bool quit = false;
  139. if (m_path_history.size())
  140. open(m_path_history.at(m_path_history_position));
  141. else
  142. quit = true;
  143. if (on_error)
  144. on_error(error, error_string, quit);
  145. };
  146. m_model->on_complete = [this] {
  147. if (m_table_view)
  148. m_table_view->selection().clear();
  149. if (m_icon_view)
  150. m_icon_view->selection().clear();
  151. add_path_to_history(model().root_path());
  152. bool can_write_in_path = access(model().root_path().characters(), W_OK) == 0;
  153. m_mkdir_action->set_enabled(can_write_in_path);
  154. m_touch_action->set_enabled(can_write_in_path);
  155. if (on_path_change)
  156. on_path_change(model().root_path(), can_write_in_path);
  157. };
  158. m_model->register_client(*this);
  159. m_model->on_thumbnail_progress = [this](int done, int total) {
  160. if (on_thumbnail_progress)
  161. on_thumbnail_progress(done, total);
  162. };
  163. }
  164. void DirectoryView::setup_icon_view()
  165. {
  166. m_icon_view = add<GUI::IconView>();
  167. if (is_desktop()) {
  168. m_icon_view->set_frame_shape(Gfx::FrameShape::NoFrame);
  169. m_icon_view->set_scrollbars_enabled(false);
  170. m_icon_view->set_fill_with_background_color(false);
  171. }
  172. m_icon_view->set_model(m_sorting_model);
  173. m_icon_view->set_model_column(GUI::FileSystemModel::Column::Name);
  174. m_icon_view->on_activation = [&](auto& index) {
  175. handle_activation(index);
  176. };
  177. m_icon_view->on_selection_change = [this] {
  178. handle_selection_change();
  179. };
  180. m_icon_view->on_context_menu_request = [this](auto& index, auto& event) {
  181. if (on_context_menu_request)
  182. on_context_menu_request(index, event);
  183. };
  184. m_icon_view->on_drop = [this](auto& index, auto& event) {
  185. if (on_drop)
  186. on_drop(index, event);
  187. };
  188. }
  189. void DirectoryView::setup_columns_view()
  190. {
  191. m_columns_view = add<GUI::ColumnsView>();
  192. m_columns_view->set_model(m_sorting_model);
  193. m_columns_view->set_model_column(GUI::FileSystemModel::Column::Name);
  194. m_columns_view->on_activation = [&](auto& index) {
  195. handle_activation(index);
  196. };
  197. m_columns_view->on_selection_change = [this] {
  198. handle_selection_change();
  199. };
  200. m_columns_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_columns_view->on_drop = [this](auto& index, auto& event) {
  205. if (on_drop)
  206. on_drop(index, event);
  207. };
  208. }
  209. void DirectoryView::setup_table_view()
  210. {
  211. m_table_view = add<GUI::TableView>();
  212. m_table_view->set_model(m_sorting_model);
  213. m_table_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  214. m_table_view->on_activation = [&](auto& index) {
  215. handle_activation(index);
  216. };
  217. m_table_view->on_selection_change = [this] {
  218. handle_selection_change();
  219. };
  220. m_table_view->on_context_menu_request = [this](auto& index, auto& event) {
  221. if (on_context_menu_request)
  222. on_context_menu_request(index, event);
  223. };
  224. m_table_view->on_drop = [this](auto& index, auto& event) {
  225. if (on_drop)
  226. on_drop(index, event);
  227. };
  228. }
  229. DirectoryView::~DirectoryView()
  230. {
  231. m_model->unregister_client(*this);
  232. }
  233. void DirectoryView::model_did_update(unsigned flags)
  234. {
  235. if (flags & GUI::Model::UpdateFlag::InvalidateAllIndexes) {
  236. for_each_view_implementation([](auto& view) {
  237. view.selection().clear();
  238. });
  239. }
  240. update_statusbar();
  241. }
  242. void DirectoryView::set_view_mode(ViewMode mode)
  243. {
  244. if (m_view_mode == mode)
  245. return;
  246. m_view_mode = mode;
  247. update();
  248. if (mode == ViewMode::Table) {
  249. set_active_widget(m_table_view);
  250. return;
  251. }
  252. if (mode == ViewMode::Columns) {
  253. set_active_widget(m_columns_view);
  254. return;
  255. }
  256. if (mode == ViewMode::Icon) {
  257. set_active_widget(m_icon_view);
  258. return;
  259. }
  260. ASSERT_NOT_REACHED();
  261. }
  262. void DirectoryView::add_path_to_history(const StringView& path)
  263. {
  264. if (m_path_history.size() && m_path_history.at(m_path_history_position) == path)
  265. return;
  266. if (m_path_history_position < m_path_history.size())
  267. m_path_history.resize(m_path_history_position + 1);
  268. m_path_history.append(path);
  269. m_path_history_position = m_path_history.size() - 1;
  270. }
  271. void DirectoryView::open(const StringView& path)
  272. {
  273. if (model().root_path() == path) {
  274. model().update();
  275. return;
  276. }
  277. model().set_root_path(path);
  278. }
  279. void DirectoryView::set_status_message(const StringView& message)
  280. {
  281. if (on_status_message)
  282. on_status_message(message);
  283. }
  284. void DirectoryView::open_parent_directory()
  285. {
  286. auto path = String::format("%s/..", model().root_path().characters());
  287. model().set_root_path(path);
  288. }
  289. void DirectoryView::refresh()
  290. {
  291. model().update();
  292. }
  293. void DirectoryView::open_previous_directory()
  294. {
  295. if (m_path_history_position > 0) {
  296. m_path_history_position--;
  297. model().set_root_path(m_path_history[m_path_history_position]);
  298. }
  299. }
  300. void DirectoryView::open_next_directory()
  301. {
  302. if (m_path_history_position < m_path_history.size() - 1) {
  303. m_path_history_position++;
  304. model().set_root_path(m_path_history[m_path_history_position]);
  305. }
  306. }
  307. void DirectoryView::update_statusbar()
  308. {
  309. size_t total_size = model().node({}).total_size;
  310. if (current_view().selection().is_empty()) {
  311. set_status_message(String::format("%d item%s (%s)",
  312. model().row_count(),
  313. model().row_count() != 1 ? "s" : "",
  314. human_readable_size(total_size).characters()));
  315. return;
  316. }
  317. int selected_item_count = current_view().selection().size();
  318. size_t selected_byte_count = 0;
  319. current_view().selection().for_each_index([&](auto& index) {
  320. auto& model = *current_view().model();
  321. auto size_index = model.index(index.row(), GUI::FileSystemModel::Column::Size, model.parent_index(index));
  322. auto file_size = size_index.data().to_i32();
  323. selected_byte_count += file_size;
  324. });
  325. StringBuilder builder;
  326. builder.append(String::number(selected_item_count));
  327. builder.append(" item");
  328. if (selected_item_count != 1)
  329. builder.append('s');
  330. builder.append(" selected (");
  331. builder.append(human_readable_size(selected_byte_count).characters());
  332. builder.append(')');
  333. if (selected_item_count == 1) {
  334. auto& node = this->node(current_view().selection().first());
  335. if (!node.symlink_target.is_empty()) {
  336. builder.append(" -> ");
  337. builder.append(node.symlink_target);
  338. }
  339. }
  340. set_status_message(builder.to_string());
  341. }
  342. void DirectoryView::set_should_show_dotfiles(bool show_dotfiles)
  343. {
  344. m_model->set_should_show_dotfiles(show_dotfiles);
  345. }
  346. void DirectoryView::launch(const URL&, const LauncherHandler& launcher_handler)
  347. {
  348. pid_t child;
  349. if (launcher_handler.details().launcher_type == Desktop::Launcher::LauncherType::Application) {
  350. const char* argv[] = { launcher_handler.details().name.characters(), nullptr };
  351. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  352. if (disown(child) < 0)
  353. perror("disown");
  354. } else {
  355. for (auto& path : selected_file_paths()) {
  356. const char* argv[] = { launcher_handler.details().name.characters(), path.characters(), nullptr };
  357. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  358. if (disown(child) < 0)
  359. perror("disown");
  360. }
  361. }
  362. }
  363. Vector<String> DirectoryView::selected_file_paths() const
  364. {
  365. Vector<String> paths;
  366. auto& view = current_view();
  367. auto& model = *view.model();
  368. view.selection().for_each_index([&](const GUI::ModelIndex& index) {
  369. auto parent_index = model.parent_index(index);
  370. auto name_index = model.index(index.row(), GUI::FileSystemModel::Column::Name, parent_index);
  371. auto path = name_index.data(GUI::ModelRole::Custom).to_string();
  372. paths.append(path);
  373. });
  374. return paths;
  375. }
  376. void DirectoryView::do_delete(bool should_confirm)
  377. {
  378. auto paths = selected_file_paths();
  379. ASSERT(!paths.is_empty());
  380. FileUtils::delete_paths(paths, should_confirm, window());
  381. }
  382. void DirectoryView::handle_selection_change()
  383. {
  384. update_statusbar();
  385. bool can_delete = !current_view().selection().is_empty() && access(path().characters(), W_OK) == 0;
  386. m_delete_action->set_enabled(can_delete);
  387. m_force_delete_action->set_enabled(can_delete);
  388. if (on_selection_change)
  389. on_selection_change(*m_table_view);
  390. }
  391. void DirectoryView::setup_actions()
  392. {
  393. 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&) {
  394. String value;
  395. if (GUI::InputBox::show(value, window(), "Enter name:", "New directory") == GUI::InputBox::ExecOK && !value.is_empty()) {
  396. auto new_dir_path = LexicalPath::canonicalized_path(
  397. String::format("%s/%s",
  398. path().characters(),
  399. value.characters()));
  400. int rc = mkdir(new_dir_path.characters(), 0777);
  401. if (rc < 0) {
  402. auto saved_errno = errno;
  403. GUI::MessageBox::show(window(), String::format("mkdir(\"%s\") failed: %s", new_dir_path.characters(), strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  404. }
  405. }
  406. });
  407. 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&) {
  408. String value;
  409. if (GUI::InputBox::show(value, window(), "Enter name:", "New file") == GUI::InputBox::ExecOK && !value.is_empty()) {
  410. auto new_file_path = LexicalPath::canonicalized_path(
  411. String::format("%s/%s",
  412. path().characters(),
  413. value.characters()));
  414. struct stat st;
  415. int rc = stat(new_file_path.characters(), &st);
  416. if ((rc < 0 && errno != ENOENT)) {
  417. auto saved_errno = errno;
  418. GUI::MessageBox::show(window(), String::format("stat(\"%s\") failed: %s", new_file_path.characters(), strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  419. return;
  420. }
  421. if (rc == 0) {
  422. GUI::MessageBox::show(window(), String::format("%s: Already exists", new_file_path.characters()), "Error", GUI::MessageBox::Type::Error);
  423. return;
  424. }
  425. int fd = creat(new_file_path.characters(), 0666);
  426. if (fd < 0) {
  427. auto saved_errno = errno;
  428. GUI::MessageBox::show(window(), String::format("creat(\"%s\") failed: %s", new_file_path.characters(), strerror(saved_errno)), "Error", GUI::MessageBox::Type::Error);
  429. return;
  430. }
  431. rc = close(fd);
  432. ASSERT(rc >= 0);
  433. }
  434. });
  435. m_open_terminal_action = GUI::Action::create("Open Terminal here...", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"), [&](auto&) {
  436. posix_spawn_file_actions_t spawn_actions;
  437. posix_spawn_file_actions_init(&spawn_actions);
  438. posix_spawn_file_actions_addchdir(&spawn_actions, path().characters());
  439. pid_t pid;
  440. const char* argv[] = { "Terminal", nullptr };
  441. if ((errno = posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) {
  442. perror("posix_spawn");
  443. } else {
  444. if (disown(pid) < 0)
  445. perror("disown");
  446. }
  447. posix_spawn_file_actions_destroy(&spawn_actions);
  448. });
  449. m_delete_action = GUI::CommonActions::make_delete_action([this](auto&) { do_delete(true); }, window());
  450. m_force_delete_action = GUI::Action::create(
  451. "Delete without confirmation", { Mod_Shift, Key_Delete },
  452. [this](auto&) { do_delete(false); },
  453. window());
  454. }