DirectoryView.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 <AK/NumberFormat.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibCore/StandardPaths.h>
  30. #include <LibGUI/MessageBox.h>
  31. #include <LibGUI/SortingProxyModel.h>
  32. #include <serenity.h>
  33. #include <spawn.h>
  34. #include <stdio.h>
  35. #include <unistd.h>
  36. NonnullRefPtr<GUI::Action> LauncherHandler::create_launch_action(Function<void(const LauncherHandler&)> launch_handler)
  37. {
  38. RefPtr<Gfx::Bitmap> icon;
  39. auto icon_file = details().icons.get("16x16");
  40. if (icon_file.has_value())
  41. icon = Gfx::Bitmap::load_from_file(icon_file.value());
  42. return GUI::Action::create(details().name, move(icon), [this, launch_handler = move(launch_handler)](auto&) {
  43. launch_handler(*this);
  44. });
  45. }
  46. RefPtr<LauncherHandler> DirectoryView::get_default_launch_handler(const NonnullRefPtrVector<LauncherHandler>& handlers)
  47. {
  48. // If this is an application, pick it first
  49. for (size_t i = 0; i < handlers.size(); i++) {
  50. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::Application)
  51. return handlers[i];
  52. }
  53. // If there's a handler preferred by the user, pick this first
  54. for (size_t i = 0; i < handlers.size(); i++) {
  55. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserPreferred)
  56. return handlers[i];
  57. }
  58. // Otherwise, use the user's default, if available
  59. for (size_t i = 0; i < handlers.size(); i++) {
  60. if (handlers[i].details().launcher_type == Desktop::Launcher::LauncherType::UserDefault)
  61. return handlers[i];
  62. }
  63. // If still no match, use the first one we find
  64. if (!handlers.is_empty()) {
  65. return handlers[0];
  66. }
  67. return {};
  68. }
  69. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(const URL& url)
  70. {
  71. NonnullRefPtrVector<LauncherHandler> handlers;
  72. for (auto& h : Desktop::Launcher::get_handlers_with_details_for_url(url)) {
  73. handlers.append(adopt(*new LauncherHandler(h)));
  74. }
  75. return handlers;
  76. }
  77. NonnullRefPtrVector<LauncherHandler> DirectoryView::get_launch_handlers(const String& path)
  78. {
  79. return get_launch_handlers(URL::create_with_file_protocol(path));
  80. }
  81. void DirectoryView::handle_activation(const GUI::ModelIndex& index)
  82. {
  83. if (!index.is_valid())
  84. return;
  85. dbgprintf("on activation: %d,%d, this=%p, m_model=%p\n", index.row(), index.column(), this, m_model.ptr());
  86. auto& node = model().node(index);
  87. auto path = node.full_path(model());
  88. struct stat st;
  89. if (stat(path.characters(), &st) < 0) {
  90. perror("stat");
  91. return;
  92. }
  93. if (S_ISDIR(st.st_mode)) {
  94. if (is_desktop()) {
  95. Desktop::Launcher::open(URL::create_with_file_protocol(path));
  96. return;
  97. }
  98. open(path);
  99. return;
  100. }
  101. auto url = URL::create_with_file_protocol(path);
  102. auto launcher_handlers = get_launch_handlers(url);
  103. auto default_launcher = get_default_launch_handler(launcher_handlers);
  104. if (default_launcher) {
  105. launch(url, *default_launcher);
  106. } else {
  107. auto error_message = String::format("Could not open %s", path.characters());
  108. GUI::MessageBox::show(window(), error_message, "File Manager", GUI::MessageBox::Type::Error);
  109. }
  110. }
  111. DirectoryView::DirectoryView(Mode mode)
  112. : m_mode(mode)
  113. , m_model(GUI::FileSystemModel::create())
  114. , m_sorting_model(GUI::SortingProxyModel::create(m_model))
  115. {
  116. set_active_widget(nullptr);
  117. set_content_margins({ 2, 2, 2, 2 });
  118. setup_model();
  119. setup_icon_view();
  120. if (mode != Mode::Desktop) {
  121. setup_columns_view();
  122. setup_table_view();
  123. }
  124. set_view_mode(ViewMode::Icon);
  125. }
  126. void DirectoryView::setup_model()
  127. {
  128. m_model->set_root_path(Core::StandardPaths::desktop_directory());
  129. m_model->on_error = [this](int error, const char* error_string) {
  130. bool quit = false;
  131. if (m_path_history.size())
  132. open(m_path_history.at(m_path_history_position));
  133. else
  134. quit = true;
  135. if (on_error)
  136. on_error(error, error_string, quit);
  137. };
  138. m_model->on_complete = [this] {
  139. if (m_table_view)
  140. m_table_view->selection().clear();
  141. if (m_icon_view)
  142. m_icon_view->selection().clear();
  143. add_path_to_history(model().root_path());
  144. if (on_path_change)
  145. on_path_change(model().root_path());
  146. };
  147. m_model->register_client(*this);
  148. m_model->on_thumbnail_progress = [this](int done, int total) {
  149. if (on_thumbnail_progress)
  150. on_thumbnail_progress(done, total);
  151. };
  152. }
  153. void DirectoryView::setup_icon_view()
  154. {
  155. m_icon_view = add<GUI::IconView>();
  156. if (is_desktop()) {
  157. m_icon_view->set_frame_shape(Gfx::FrameShape::NoFrame);
  158. m_icon_view->set_scrollbars_enabled(false);
  159. m_icon_view->set_fill_with_background_color(false);
  160. }
  161. m_icon_view->set_model(m_sorting_model);
  162. m_icon_view->set_model_column(GUI::FileSystemModel::Column::Name);
  163. m_icon_view->on_activation = [&](auto& index) {
  164. handle_activation(map_index(index));
  165. };
  166. m_icon_view->on_selection_change = [this] {
  167. update_statusbar();
  168. if (on_selection_change)
  169. on_selection_change(*m_icon_view);
  170. };
  171. m_icon_view->on_context_menu_request = [this](auto& index, auto& event) {
  172. if (on_context_menu_request)
  173. on_context_menu_request(map_index(index), event);
  174. };
  175. m_icon_view->on_drop = [this](auto& index, auto& event) {
  176. if (on_drop)
  177. on_drop(map_index(index), event);
  178. };
  179. }
  180. void DirectoryView::setup_columns_view()
  181. {
  182. m_columns_view = add<GUI::ColumnsView>();
  183. m_columns_view->set_model(m_sorting_model);
  184. m_columns_view->set_model_column(GUI::FileSystemModel::Column::Name);
  185. m_columns_view->on_activation = [&](auto& index) {
  186. handle_activation(map_index(index));
  187. };
  188. m_columns_view->on_selection_change = [this] {
  189. update_statusbar();
  190. if (on_selection_change)
  191. on_selection_change(*m_columns_view);
  192. };
  193. m_columns_view->on_context_menu_request = [this](auto& index, auto& event) {
  194. if (on_context_menu_request)
  195. on_context_menu_request(map_index(index), event);
  196. };
  197. m_columns_view->on_drop = [this](auto& index, auto& event) {
  198. if (on_drop)
  199. on_drop(map_index(index), event);
  200. };
  201. }
  202. void DirectoryView::setup_table_view()
  203. {
  204. m_table_view = add<GUI::TableView>();
  205. m_table_view->set_model(m_sorting_model);
  206. m_table_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending);
  207. m_table_view->on_activation = [&](auto& index) {
  208. handle_activation(map_index(index));
  209. };
  210. m_table_view->on_selection_change = [this] {
  211. update_statusbar();
  212. if (on_selection_change)
  213. on_selection_change(*m_table_view);
  214. };
  215. m_table_view->on_context_menu_request = [this](auto& index, auto& event) {
  216. if (on_context_menu_request)
  217. on_context_menu_request(map_index(index), event);
  218. };
  219. m_table_view->on_drop = [this](auto& index, auto& event) {
  220. if (on_drop)
  221. on_drop(map_index(index), event);
  222. };
  223. }
  224. DirectoryView::~DirectoryView()
  225. {
  226. m_model->unregister_client(*this);
  227. }
  228. void DirectoryView::model_did_update(unsigned flags)
  229. {
  230. if (flags & GUI::Model::UpdateFlag::InvalidateAllIndexes) {
  231. for_each_view_implementation([](auto& view) {
  232. view.selection().clear();
  233. });
  234. }
  235. update_statusbar();
  236. }
  237. void DirectoryView::set_view_mode(ViewMode mode)
  238. {
  239. if (m_view_mode == mode)
  240. return;
  241. m_view_mode = mode;
  242. update();
  243. if (mode == ViewMode::Table) {
  244. set_active_widget(m_table_view);
  245. return;
  246. }
  247. if (mode == ViewMode::Columns) {
  248. set_active_widget(m_columns_view);
  249. return;
  250. }
  251. if (mode == ViewMode::Icon) {
  252. set_active_widget(m_icon_view);
  253. return;
  254. }
  255. ASSERT_NOT_REACHED();
  256. }
  257. void DirectoryView::add_path_to_history(const StringView& path)
  258. {
  259. if (m_path_history.size() && m_path_history.at(m_path_history_position) == path)
  260. return;
  261. if (m_path_history_position < m_path_history.size())
  262. m_path_history.resize(m_path_history_position + 1);
  263. m_path_history.append(path);
  264. m_path_history_position = m_path_history.size() - 1;
  265. }
  266. void DirectoryView::open(const StringView& path)
  267. {
  268. if (model().root_path() == path) {
  269. model().update();
  270. return;
  271. }
  272. model().set_root_path(path);
  273. }
  274. void DirectoryView::set_status_message(const StringView& message)
  275. {
  276. if (on_status_message)
  277. on_status_message(message);
  278. }
  279. void DirectoryView::open_parent_directory()
  280. {
  281. auto path = String::format("%s/..", model().root_path().characters());
  282. model().set_root_path(path);
  283. }
  284. void DirectoryView::refresh()
  285. {
  286. model().update();
  287. }
  288. void DirectoryView::open_previous_directory()
  289. {
  290. if (m_path_history_position > 0) {
  291. m_path_history_position--;
  292. model().set_root_path(m_path_history[m_path_history_position]);
  293. }
  294. }
  295. void DirectoryView::open_next_directory()
  296. {
  297. if (m_path_history_position < m_path_history.size() - 1) {
  298. m_path_history_position++;
  299. model().set_root_path(m_path_history[m_path_history_position]);
  300. }
  301. }
  302. GUI::ModelIndex DirectoryView::map_index(const GUI::ModelIndex& index) const
  303. {
  304. return m_sorting_model->map_to_source(index);
  305. }
  306. void DirectoryView::update_statusbar()
  307. {
  308. size_t total_size = model().node({}).total_size;
  309. if (current_view().selection().is_empty()) {
  310. set_status_message(String::format("%d item%s (%s)",
  311. model().row_count(),
  312. model().row_count() != 1 ? "s" : "",
  313. human_readable_size(total_size).characters()));
  314. return;
  315. }
  316. int selected_item_count = current_view().selection().size();
  317. size_t selected_byte_count = 0;
  318. current_view().selection().for_each_index([&](auto& index) {
  319. auto& model = *current_view().model();
  320. auto size_index = model.index(index.row(), GUI::FileSystemModel::Column::Size, model.parent_index(index));
  321. auto file_size = size_index.data().to_i32();
  322. selected_byte_count += file_size;
  323. });
  324. StringBuilder builder;
  325. builder.append(String::number(selected_item_count));
  326. builder.append(" item");
  327. if (selected_item_count != 1)
  328. builder.append('s');
  329. builder.append(" selected (");
  330. builder.append(human_readable_size(selected_byte_count).characters());
  331. builder.append(')');
  332. if (selected_item_count == 1) {
  333. auto& node = model().node(map_index(current_view().selection().first()));
  334. if (!node.symlink_target.is_empty()) {
  335. builder.append(" -> ");
  336. builder.append(node.symlink_target);
  337. }
  338. }
  339. set_status_message(builder.to_string());
  340. }
  341. void DirectoryView::set_should_show_dotfiles(bool show_dotfiles)
  342. {
  343. m_model->set_should_show_dotfiles(show_dotfiles);
  344. }
  345. void DirectoryView::launch(const URL&, const LauncherHandler& launcher_handler)
  346. {
  347. pid_t child;
  348. if (launcher_handler.details().launcher_type == Desktop::Launcher::LauncherType::Application) {
  349. const char* argv[] = { launcher_handler.details().name.characters(), nullptr };
  350. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  351. if (disown(child) < 0)
  352. perror("disown");
  353. } else {
  354. for (auto& path : selected_file_paths()) {
  355. const char* argv[] = { launcher_handler.details().name.characters(), path.characters(), nullptr };
  356. posix_spawn(&child, launcher_handler.details().executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ);
  357. if (disown(child) < 0)
  358. perror("disown");
  359. }
  360. }
  361. }
  362. Vector<String> DirectoryView::selected_file_paths() const
  363. {
  364. Vector<String> paths;
  365. auto& view = current_view();
  366. auto& model = *view.model();
  367. view.selection().for_each_index([&](const GUI::ModelIndex& index) {
  368. auto parent_index = model.parent_index(index);
  369. auto name_index = model.index(index.row(), GUI::FileSystemModel::Column::Name, parent_index);
  370. auto path = name_index.data(GUI::ModelRole::Custom).to_string();
  371. paths.append(path);
  372. });
  373. return paths;
  374. }