DirectoryView.cpp 16 KB

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