PropertiesWindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022-2023, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "PropertiesWindow.h"
  8. #include <AK/LexicalPath.h>
  9. #include <AK/NumberFormat.h>
  10. #include <Applications/FileManager/DirectoryView.h>
  11. #include <Applications/FileManager/PropertiesWindowGeneralTabGML.h>
  12. #include <LibCore/Directory.h>
  13. #include <LibCore/System.h>
  14. #include <LibDesktop/Launcher.h>
  15. #include <LibFileSystem/FileSystem.h>
  16. #include <LibGUI/BoxLayout.h>
  17. #include <LibGUI/CheckBox.h>
  18. #include <LibGUI/FileIconProvider.h>
  19. #include <LibGUI/FilePicker.h>
  20. #include <LibGUI/IconView.h>
  21. #include <LibGUI/LinkLabel.h>
  22. #include <LibGUI/MessageBox.h>
  23. #include <LibGUI/SeparatorWidget.h>
  24. #include <LibGUI/TabWidget.h>
  25. #include <grp.h>
  26. #include <pwd.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <unistd.h>
  30. ErrorOr<NonnullRefPtr<PropertiesWindow>> PropertiesWindow::try_create(DeprecatedString const& path, bool disable_rename, Window* parent)
  31. {
  32. auto window = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) PropertiesWindow(path, parent)));
  33. window->set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/properties.png"sv)));
  34. TRY(window->create_widgets(disable_rename));
  35. return window;
  36. }
  37. PropertiesWindow::PropertiesWindow(DeprecatedString const& path, Window* parent_window)
  38. : Window(parent_window)
  39. {
  40. auto lexical_path = LexicalPath(path);
  41. m_name = lexical_path.basename();
  42. m_path = lexical_path.string();
  43. m_parent_path = lexical_path.dirname();
  44. set_rect({ 0, 0, 360, 420 });
  45. set_resizable(false);
  46. }
  47. ErrorOr<void> PropertiesWindow::create_widgets(bool disable_rename)
  48. {
  49. auto main_widget = TRY(set_main_widget<GUI::Widget>());
  50. TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>(4, 6));
  51. main_widget->set_fill_with_background_color(true);
  52. auto tab_widget = TRY(main_widget->try_add<GUI::TabWidget>());
  53. auto general_tab = TRY(tab_widget->try_add_tab<GUI::Widget>("General"_short_string));
  54. TRY(general_tab->load_from_gml(properties_window_general_tab_gml));
  55. m_icon = general_tab->find_descendant_of_type_named<GUI::ImageWidget>("icon");
  56. m_name_box = general_tab->find_descendant_of_type_named<GUI::TextBox>("name");
  57. m_name_box->set_text(m_name);
  58. m_name_box->set_mode(disable_rename ? GUI::TextBox::Mode::DisplayOnly : GUI::TextBox::Mode::Editable);
  59. m_name_box->on_change = [&]() {
  60. m_name_dirty = m_name != m_name_box->text();
  61. m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
  62. };
  63. auto* location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("location");
  64. location->set_text(TRY(String::from_deprecated_string(m_path)));
  65. location->on_click = [this] {
  66. Desktop::Launcher::open(URL::create_with_file_scheme(m_parent_path, m_name));
  67. };
  68. auto st = TRY(Core::System::lstat(m_path));
  69. DeprecatedString owner_name;
  70. DeprecatedString group_name;
  71. if (auto* pw = getpwuid(st.st_uid)) {
  72. owner_name = pw->pw_name;
  73. } else {
  74. owner_name = "n/a";
  75. }
  76. if (auto* gr = getgrgid(st.st_gid)) {
  77. group_name = gr->gr_name;
  78. } else {
  79. group_name = "n/a";
  80. }
  81. m_mode = st.st_mode;
  82. m_old_mode = st.st_mode;
  83. auto* type = general_tab->find_descendant_of_type_named<GUI::Label>("type");
  84. type->set_text(TRY(String::from_deprecated_string(get_description(m_mode))));
  85. if (S_ISLNK(m_mode)) {
  86. auto link_destination_or_error = FileSystem::read_link(m_path);
  87. if (link_destination_or_error.is_error()) {
  88. perror("readlink");
  89. } else {
  90. auto link_destination = link_destination_or_error.release_value();
  91. auto* link_location = general_tab->find_descendant_of_type_named<GUI::LinkLabel>("link_location");
  92. link_location->set_text(link_destination);
  93. link_location->on_click = [link_destination] {
  94. auto link_directory = LexicalPath(link_destination.to_deprecated_string());
  95. Desktop::Launcher::open(URL::create_with_file_scheme(link_directory.dirname(), link_directory.basename()));
  96. };
  97. }
  98. } else {
  99. auto* link_location_widget = general_tab->find_descendant_of_type_named<GUI::Widget>("link_location_widget");
  100. general_tab->remove_child(*link_location_widget);
  101. }
  102. m_size_label = general_tab->find_descendant_of_type_named<GUI::Label>("size");
  103. m_size_label->set_text(S_ISDIR(st.st_mode)
  104. ? TRY("Calculating..."_string)
  105. : TRY(String::from_deprecated_string(human_readable_size_long(st.st_size, UseThousandsSeparator::Yes))));
  106. auto* owner = general_tab->find_descendant_of_type_named<GUI::Label>("owner");
  107. owner->set_text(String::formatted("{} ({})", owner_name, st.st_uid).release_value_but_fixme_should_propagate_errors());
  108. auto* group = general_tab->find_descendant_of_type_named<GUI::Label>("group");
  109. group->set_text(String::formatted("{} ({})", group_name, st.st_gid).release_value_but_fixme_should_propagate_errors());
  110. auto* created_at = general_tab->find_descendant_of_type_named<GUI::Label>("created_at");
  111. created_at->set_text(String::from_deprecated_string(GUI::FileSystemModel::timestamp_string(st.st_ctime)).release_value_but_fixme_should_propagate_errors());
  112. auto* last_modified = general_tab->find_descendant_of_type_named<GUI::Label>("last_modified");
  113. last_modified->set_text(String::from_deprecated_string(GUI::FileSystemModel::timestamp_string(st.st_mtime)).release_value_but_fixme_should_propagate_errors());
  114. auto* owner_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_read");
  115. auto* owner_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_write");
  116. auto* owner_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("owner_execute");
  117. TRY(setup_permission_checkboxes(*owner_read, *owner_write, *owner_execute, { S_IRUSR, S_IWUSR, S_IXUSR }, m_mode));
  118. auto* group_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_read");
  119. auto* group_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_write");
  120. auto* group_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("group_execute");
  121. TRY(setup_permission_checkboxes(*group_read, *group_write, *group_execute, { S_IRGRP, S_IWGRP, S_IXGRP }, m_mode));
  122. auto* others_read = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_read");
  123. auto* others_write = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_write");
  124. auto* others_execute = general_tab->find_descendant_of_type_named<GUI::CheckBox>("others_execute");
  125. TRY(setup_permission_checkboxes(*others_read, *others_write, *others_execute, { S_IROTH, S_IWOTH, S_IXOTH }, m_mode));
  126. auto button_widget = TRY(main_widget->try_add<GUI::Widget>());
  127. TRY(button_widget->try_set_layout<GUI::HorizontalBoxLayout>(GUI::Margins {}, 5));
  128. button_widget->set_fixed_height(22);
  129. TRY(button_widget->add_spacer());
  130. auto ok_button = TRY(make_button("OK"_short_string, button_widget));
  131. ok_button->on_click = [this](auto) {
  132. if (apply_changes())
  133. close();
  134. };
  135. auto cancel_button = TRY(make_button("Cancel"_short_string, button_widget));
  136. cancel_button->on_click = [this](auto) {
  137. close();
  138. };
  139. m_apply_button = TRY(make_button("Apply"_short_string, button_widget));
  140. m_apply_button->on_click = [this](auto) { apply_changes(); };
  141. m_apply_button->set_enabled(false);
  142. if (S_ISDIR(m_old_mode)) {
  143. m_directory_statistics_calculator = make_ref_counted<DirectoryStatisticsCalculator>(m_path);
  144. m_directory_statistics_calculator->on_update = [this, origin_event_loop = &Core::EventLoop::current()](off_t total_size_in_bytes, size_t file_count, size_t directory_count) {
  145. origin_event_loop->deferred_invoke([=, weak_this = make_weak_ptr<PropertiesWindow>()] {
  146. if (auto strong_this = weak_this.strong_ref())
  147. strong_this->m_size_label->set_text(String::formatted("{}\n{} files, {} subdirectories", human_readable_size_long(total_size_in_bytes, UseThousandsSeparator::Yes), file_count, directory_count).release_value_but_fixme_should_propagate_errors());
  148. });
  149. };
  150. m_directory_statistics_calculator->start();
  151. }
  152. update();
  153. return {};
  154. }
  155. void PropertiesWindow::update()
  156. {
  157. m_icon->set_bitmap(GUI::FileIconProvider::icon_for_path(make_full_path(m_name), m_mode).bitmap_for_size(32));
  158. set_title(DeprecatedString::formatted("{} - Properties", m_name));
  159. }
  160. void PropertiesWindow::permission_changed(mode_t mask, bool set)
  161. {
  162. if (set) {
  163. m_mode |= mask;
  164. } else {
  165. m_mode &= ~mask;
  166. }
  167. m_permissions_dirty = m_mode != m_old_mode;
  168. m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty);
  169. }
  170. DeprecatedString PropertiesWindow::make_full_path(DeprecatedString const& name)
  171. {
  172. return DeprecatedString::formatted("{}/{}", m_parent_path, name);
  173. }
  174. bool PropertiesWindow::apply_changes()
  175. {
  176. if (m_name_dirty) {
  177. DeprecatedString new_name = m_name_box->text();
  178. DeprecatedString new_file = make_full_path(new_name).characters();
  179. if (FileSystem::exists(new_file)) {
  180. GUI::MessageBox::show(this, DeprecatedString::formatted("A file \"{}\" already exists!", new_name), "Error"sv, GUI::MessageBox::Type::Error);
  181. return false;
  182. }
  183. if (rename(make_full_path(m_name).characters(), new_file.characters())) {
  184. GUI::MessageBox::show(this, DeprecatedString::formatted("Could not rename file: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
  185. return false;
  186. }
  187. m_name = new_name;
  188. m_name_dirty = false;
  189. update();
  190. }
  191. if (m_permissions_dirty) {
  192. if (chmod(make_full_path(m_name).characters(), m_mode)) {
  193. GUI::MessageBox::show(this, DeprecatedString::formatted("Could not update permissions: {}!", strerror(errno)), "Error"sv, GUI::MessageBox::Type::Error);
  194. return false;
  195. }
  196. m_old_mode = m_mode;
  197. m_permissions_dirty = false;
  198. }
  199. auto directory_view = parent()->find_descendant_of_type_named<FileManager::DirectoryView>("directory_view");
  200. directory_view->refresh();
  201. update();
  202. m_apply_button->set_enabled(false);
  203. return true;
  204. }
  205. ErrorOr<void> PropertiesWindow::setup_permission_checkboxes(GUI::CheckBox& box_read, GUI::CheckBox& box_write, GUI::CheckBox& box_execute, PermissionMasks masks, mode_t mode)
  206. {
  207. auto st = TRY(Core::System::lstat(m_path));
  208. auto can_edit_checkboxes = st.st_uid == getuid();
  209. box_read.set_checked(mode & masks.read);
  210. box_read.on_checked = [&, masks](bool checked) { permission_changed(masks.read, checked); };
  211. box_read.set_enabled(can_edit_checkboxes);
  212. box_write.set_checked(mode & masks.write);
  213. box_write.on_checked = [&, masks](bool checked) { permission_changed(masks.write, checked); };
  214. box_write.set_enabled(can_edit_checkboxes);
  215. box_execute.set_checked(mode & masks.execute);
  216. box_execute.on_checked = [&, masks](bool checked) { permission_changed(masks.execute, checked); };
  217. box_execute.set_enabled(can_edit_checkboxes);
  218. return {};
  219. }
  220. ErrorOr<NonnullRefPtr<GUI::Button>> PropertiesWindow::make_button(String text, GUI::Widget& parent)
  221. {
  222. auto button = TRY(parent.try_add<GUI::Button>(text));
  223. button->set_fixed_size(70, 22);
  224. return button;
  225. }
  226. void PropertiesWindow::close()
  227. {
  228. GUI::Window::close();
  229. if (m_directory_statistics_calculator)
  230. m_directory_statistics_calculator->stop();
  231. }
  232. PropertiesWindow::DirectoryStatisticsCalculator::DirectoryStatisticsCalculator(DeprecatedString path)
  233. {
  234. m_work_queue.enqueue(path);
  235. }
  236. void PropertiesWindow::DirectoryStatisticsCalculator::start()
  237. {
  238. using namespace AK::TimeLiterals;
  239. VERIFY(!m_background_action);
  240. m_background_action = Threading::BackgroundAction<int>::construct(
  241. [this, strong_this = NonnullRefPtr(*this)](auto& task) -> ErrorOr<int> {
  242. auto timer = Core::ElapsedTimer();
  243. while (!m_work_queue.is_empty()) {
  244. auto base_directory = m_work_queue.dequeue();
  245. auto result = Core::Directory::for_each_entry(base_directory, Core::DirIterator::SkipParentAndBaseDir, [&](auto const& entry, auto const& directory) -> ErrorOr<IterationDecision> {
  246. if (task.is_canceled())
  247. return Error::from_errno(ECANCELED);
  248. struct stat st = {};
  249. if (fstatat(directory.fd(), entry.name.characters(), &st, AT_SYMLINK_NOFOLLOW) < 0) {
  250. perror("fstatat");
  251. return IterationDecision::Continue;
  252. }
  253. if (S_ISDIR(st.st_mode)) {
  254. auto full_path = LexicalPath::join(directory.path().string(), entry.name).string();
  255. m_directory_count++;
  256. m_work_queue.enqueue(full_path);
  257. } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
  258. m_file_count++;
  259. m_total_size_in_bytes += st.st_size;
  260. }
  261. // Show the first update, then show any subsequent updates every 100ms.
  262. if (!task.is_canceled() && on_update && (!timer.is_valid() || timer.elapsed_time() > 100_ms)) {
  263. timer.start();
  264. on_update(m_total_size_in_bytes, m_file_count, m_directory_count);
  265. }
  266. return IterationDecision::Continue;
  267. });
  268. if (result.is_error() && result.error().code() == ECANCELED)
  269. return Error::from_errno(ECANCELED);
  270. }
  271. return 0;
  272. },
  273. [this](auto) -> ErrorOr<void> {
  274. if (on_update)
  275. on_update(m_total_size_in_bytes, m_file_count, m_directory_count);
  276. return {};
  277. },
  278. [](auto) {
  279. // Ignore the error.
  280. });
  281. }
  282. void PropertiesWindow::DirectoryStatisticsCalculator::stop()
  283. {
  284. VERIFY(m_background_action);
  285. m_background_action->cancel();
  286. }