main.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Undefine <cqundefine@gmail.com>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include "GraphWidget.h"
  9. #include "MemoryStatsWidget.h"
  10. #include "NetworkStatisticsWidget.h"
  11. #include "ProcessFileDescriptorMapWidget.h"
  12. #include "ProcessMemoryMapWidget.h"
  13. #include "ProcessModel.h"
  14. #include "ProcessStateWidget.h"
  15. #include "ProcessUnveiledPathsWidget.h"
  16. #include "ThreadStackWidget.h"
  17. #include <AK/NumberFormat.h>
  18. #include <Applications/SystemMonitor/ProcessWindowGML.h>
  19. #include <Applications/SystemMonitor/SystemMonitorGML.h>
  20. #include <LibConfig/Client.h>
  21. #include <LibCore/ArgsParser.h>
  22. #include <LibCore/EventLoop.h>
  23. #include <LibCore/Object.h>
  24. #include <LibCore/System.h>
  25. #include <LibCore/Timer.h>
  26. #include <LibGUI/Action.h>
  27. #include <LibGUI/ActionGroup.h>
  28. #include <LibGUI/Application.h>
  29. #include <LibGUI/BoxLayout.h>
  30. #include <LibGUI/FileIconProvider.h>
  31. #include <LibGUI/GroupBox.h>
  32. #include <LibGUI/Icon.h>
  33. #include <LibGUI/ImageWidget.h>
  34. #include <LibGUI/JsonArrayModel.h>
  35. #include <LibGUI/Label.h>
  36. #include <LibGUI/LazyWidget.h>
  37. #include <LibGUI/Menu.h>
  38. #include <LibGUI/Menubar.h>
  39. #include <LibGUI/MessageBox.h>
  40. #include <LibGUI/Painter.h>
  41. #include <LibGUI/Process.h>
  42. #include <LibGUI/SeparatorWidget.h>
  43. #include <LibGUI/SortingProxyModel.h>
  44. #include <LibGUI/StackWidget.h>
  45. #include <LibGUI/Statusbar.h>
  46. #include <LibGUI/TabWidget.h>
  47. #include <LibGUI/TreeView.h>
  48. #include <LibGUI/Widget.h>
  49. #include <LibGUI/Window.h>
  50. #include <LibGfx/Font/FontDatabase.h>
  51. #include <LibGfx/Palette.h>
  52. #include <LibMain/Main.h>
  53. #include <LibThreading/BackgroundAction.h>
  54. #include <serenity.h>
  55. #include <signal.h>
  56. #include <spawn.h>
  57. #include <stdio.h>
  58. #include <unistd.h>
  59. static ErrorOr<NonnullRefPtr<GUI::Window>> build_process_window(pid_t);
  60. static void build_performance_tab(GUI::Widget&);
  61. static RefPtr<GUI::Statusbar> statusbar;
  62. namespace SystemMonitor {
  63. class ProgressbarPaintingDelegate final : public GUI::TableCellPaintingDelegate {
  64. public:
  65. virtual ~ProgressbarPaintingDelegate() override = default;
  66. virtual void paint(GUI::Painter& painter, Gfx::IntRect const& a_rect, Palette const& palette, GUI::ModelIndex const& index) override
  67. {
  68. auto rect = a_rect.shrunken(2, 2);
  69. auto percentage = index.data(GUI::ModelRole::Custom).to_i32();
  70. auto data = index.data();
  71. DeprecatedString text;
  72. if (data.is_string())
  73. text = data.as_string();
  74. Gfx::StylePainter::paint_progressbar(painter, rect, palette, 0, 100, percentage, text);
  75. painter.draw_rect(rect, Color::Black);
  76. }
  77. };
  78. class UnavailableProcessWidget final : public GUI::Frame {
  79. C_OBJECT(UnavailableProcessWidget)
  80. public:
  81. virtual ~UnavailableProcessWidget() override = default;
  82. DeprecatedString const& text() const { return m_text; }
  83. void set_text(DeprecatedString text)
  84. {
  85. m_text = move(text);
  86. update();
  87. }
  88. private:
  89. UnavailableProcessWidget()
  90. {
  91. REGISTER_DEPRECATED_STRING_PROPERTY("text", text, set_text);
  92. }
  93. virtual void paint_event(GUI::PaintEvent& event) override
  94. {
  95. Frame::paint_event(event);
  96. if (text().is_empty())
  97. return;
  98. GUI::Painter painter(*this);
  99. painter.add_clip_rect(event.rect());
  100. painter.draw_text(frame_inner_rect(), text(), Gfx::TextAlignment::Center, palette().window_text(), Gfx::TextElision::Right);
  101. }
  102. DeprecatedString m_text;
  103. };
  104. class StorageTabWidget final : public GUI::LazyWidget {
  105. C_OBJECT(StorageTabWidget)
  106. public:
  107. StorageTabWidget()
  108. {
  109. this->on_first_show = [](GUI::LazyWidget& self) {
  110. auto& fs_table_view = *self.find_child_of_type_named<GUI::TableView>("storage_table");
  111. Vector<GUI::JsonArrayModel::FieldSpec> df_fields;
  112. df_fields.empend("mount_point", "Mount point"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterLeft);
  113. df_fields.empend("class_name", "Class"_short_string, Gfx::TextAlignment::CenterLeft);
  114. df_fields.empend("source", "Source"_short_string, Gfx::TextAlignment::CenterLeft);
  115. df_fields.empend(
  116. "Size"_short_string, Gfx::TextAlignment::CenterRight,
  117. [](JsonObject const& object) {
  118. StringBuilder size_builder;
  119. size_builder.append(' ');
  120. size_builder.append(human_readable_size(object.get_u64("total_block_count"sv).value_or(0) * object.get_u64("block_size"sv).value_or(0)));
  121. size_builder.append(' ');
  122. return size_builder.to_deprecated_string();
  123. },
  124. [](JsonObject const& object) {
  125. return object.get_u64("total_block_count"sv).value_or(0) * object.get_u64("block_size"sv).value_or(0);
  126. },
  127. [](JsonObject const& object) {
  128. auto total_blocks = object.get_u64("total_block_count"sv).value_or(0);
  129. if (total_blocks == 0)
  130. return 0;
  131. auto free_blocks = object.get_u64("free_block_count"sv).value_or(0);
  132. auto used_blocks = total_blocks - free_blocks;
  133. int percentage = (static_cast<double>(used_blocks) / static_cast<double>(total_blocks) * 100.0);
  134. return percentage;
  135. });
  136. df_fields.empend(
  137. "Used"_short_string, Gfx::TextAlignment::CenterRight,
  138. [](JsonObject const& object) {
  139. auto total_blocks = object.get_u64("total_block_count"sv).value_or(0);
  140. auto free_blocks = object.get_u64("free_block_count"sv).value_or(0);
  141. auto used_blocks = total_blocks - free_blocks;
  142. return human_readable_size(used_blocks * object.get_u64("block_size"sv).value_or(0)); },
  143. [](JsonObject const& object) {
  144. auto total_blocks = object.get_u64("total_block_count"sv).value_or(0);
  145. auto free_blocks = object.get_u64("free_block_count"sv).value_or(0);
  146. auto used_blocks = total_blocks - free_blocks;
  147. return used_blocks * object.get_u64("block_size"sv).value_or(0);
  148. });
  149. df_fields.empend(
  150. "Available"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight,
  151. [](JsonObject const& object) {
  152. return human_readable_size(object.get_u64("free_block_count"sv).value_or(0) * object.get_u64("block_size"sv).value_or(0));
  153. },
  154. [](JsonObject const& object) {
  155. return object.get_u64("free_block_count"sv).value_or(0) * object.get_u64("block_size"sv).value_or(0);
  156. });
  157. df_fields.empend("Access"_short_string, Gfx::TextAlignment::CenterLeft, [](JsonObject const& object) {
  158. bool readonly = object.get_bool("readonly"sv).value_or(false);
  159. int mount_flags = object.get_i32("mount_flags"sv).value_or(0);
  160. return readonly || (mount_flags & MS_RDONLY) ? "Read-only" : "Read/Write";
  161. });
  162. df_fields.empend("Mount flags"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterLeft, [](JsonObject const& object) {
  163. int mount_flags = object.get_i32("mount_flags"sv).value_or(0);
  164. StringBuilder builder;
  165. bool first = true;
  166. auto check = [&](int flag, StringView name) {
  167. if (!(mount_flags & flag))
  168. return;
  169. if (!first)
  170. builder.append(',');
  171. builder.append(name);
  172. first = false;
  173. };
  174. check(MS_NODEV, "nodev"sv);
  175. check(MS_NOEXEC, "noexec"sv);
  176. check(MS_NOSUID, "nosuid"sv);
  177. check(MS_BIND, "bind"sv);
  178. check(MS_RDONLY, "ro"sv);
  179. check(MS_WXALLOWED, "wxallowed"sv);
  180. check(MS_AXALLOWED, "axallowed"sv);
  181. check(MS_NOREGULAR, "noregular"sv);
  182. if (builder.string_view().is_empty())
  183. return DeprecatedString("defaults");
  184. return builder.to_deprecated_string();
  185. });
  186. df_fields.empend("free_block_count", "Free blocks"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight);
  187. df_fields.empend("total_block_count", "Total blocks"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight);
  188. df_fields.empend("free_inode_count", "Free inodes"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight);
  189. df_fields.empend("total_inode_count", "Total inodes"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight);
  190. df_fields.empend("block_size", "Block size"_string.release_value_but_fixme_should_propagate_errors(), Gfx::TextAlignment::CenterRight);
  191. fs_table_view.set_model(MUST(GUI::SortingProxyModel::create(GUI::JsonArrayModel::create("/sys/kernel/df", move(df_fields)))));
  192. fs_table_view.set_column_painting_delegate(3, make<ProgressbarPaintingDelegate>());
  193. fs_table_view.model()->invalidate();
  194. };
  195. }
  196. };
  197. }
  198. REGISTER_WIDGET(SystemMonitor, StorageTabWidget)
  199. REGISTER_WIDGET(SystemMonitor, UnavailableProcessWidget)
  200. static bool can_access_pid(pid_t pid)
  201. {
  202. int rc = kill(pid, 0);
  203. return rc == 0;
  204. }
  205. ErrorOr<int> serenity_main(Main::Arguments arguments)
  206. {
  207. {
  208. // Before we do anything else, boost our process priority to the maximum allowed.
  209. // It's very frustrating when the system is bogged down under load and you just want
  210. // System Monitor to work.
  211. sched_param param {
  212. .sched_priority = THREAD_PRIORITY_MAX,
  213. };
  214. sched_setparam(0, &param);
  215. }
  216. TRY(Core::System::pledge("stdio thread proc recvfd sendfd rpath exec unix"));
  217. auto app = TRY(GUI::Application::create(arguments));
  218. Config::pledge_domain("SystemMonitor");
  219. TRY(Core::System::unveil("/etc/passwd", "r"));
  220. TRY(Core::System::unveil("/res", "r"));
  221. TRY(Core::System::unveil("/proc", "r"));
  222. TRY(Core::System::unveil("/sys/kernel", "r"));
  223. TRY(Core::System::unveil("/dev", "r"));
  224. TRY(Core::System::unveil("/bin", "r"));
  225. TRY(Core::System::unveil("/bin/Escalator", "x"));
  226. TRY(Core::System::unveil("/bin/NetworkSettings", "x"));
  227. TRY(Core::System::unveil("/usr/lib", "r"));
  228. // This directory only exists if ports are installed
  229. if (auto result = Core::System::unveil("/usr/local/bin", "r"); result.is_error() && result.error().code() != ENOENT)
  230. return result.release_error();
  231. if (auto result = Core::System::unveil("/usr/local/lib", "r"); result.is_error() && result.error().code() != ENOENT)
  232. return result.release_error();
  233. // This file is only accessible when running as root if it is available on the disk image.
  234. // It might be possible to not have this file on the disk image, if the user decided to not
  235. // include kernel symbols for debug purposes so don't fail if the error is ENOENT.
  236. if (auto result = Core::System::unveil("/boot/Kernel.debug", "r"); result.is_error() && (result.error().code() != EACCES && result.error().code() != ENOENT))
  237. return result.release_error();
  238. TRY(Core::System::unveil("/bin/Profiler", "rx"));
  239. TRY(Core::System::unveil("/bin/HackStudio", "rx"));
  240. TRY(Core::System::unveil(nullptr, nullptr));
  241. StringView args_tab = "processes"sv;
  242. Core::ArgsParser parser;
  243. parser.add_option(args_tab, "Tab, one of 'processes', 'graphs', 'fs', 'hardware', or 'network'", "open-tab", 't', "tab");
  244. parser.parse(arguments);
  245. StringView args_tab_view = args_tab;
  246. auto app_icon = GUI::Icon::default_icon("app-system-monitor"sv);
  247. auto window = GUI::Window::construct();
  248. window->set_title("System Monitor");
  249. window->resize(560, 430);
  250. auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
  251. TRY(main_widget->load_from_gml(system_monitor_gml));
  252. auto& tabwidget = *main_widget->find_descendant_of_type_named<GUI::TabWidget>("main_tabs");
  253. statusbar = main_widget->find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  254. auto& process_table_container = *tabwidget.find_descendant_of_type_named<GUI::Widget>("processes");
  255. auto process_model = ProcessModel::create();
  256. process_model->on_state_update = [&](int process_count, int thread_count) {
  257. statusbar->set_text(0, DeprecatedString::formatted("Processes: {}", process_count));
  258. statusbar->set_text(1, DeprecatedString::formatted("Threads: {}", thread_count));
  259. };
  260. auto& performance_widget = *tabwidget.find_descendant_of_type_named<GUI::Widget>("performance");
  261. build_performance_tab(performance_widget);
  262. auto& process_table_view = *process_table_container.find_child_of_type_named<GUI::TreeView>("process_table");
  263. process_table_view.set_model(TRY(GUI::SortingProxyModel::create(process_model)));
  264. for (auto column = 0; column < ProcessModel::Column::__Count; ++column) {
  265. process_table_view.set_column_visible(column,
  266. Config::read_bool("SystemMonitor"sv, "ProcessTableColumns"sv, process_model->column_name(column),
  267. process_model->is_default_column(column)));
  268. }
  269. process_table_view.set_key_column_and_sort_order(ProcessModel::Column::CPU, GUI::SortOrder::Descending);
  270. process_model->update();
  271. i32 frequency = Config::read_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, 3);
  272. if (frequency != 1 && frequency != 3 && frequency != 5) {
  273. frequency = 3;
  274. Config::write_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, frequency);
  275. }
  276. auto update_stats = [&] {
  277. // FIXME: remove the primitive re-toggling code once persistent model indices work.
  278. auto toggled_indices = process_table_view.selection().indices();
  279. toggled_indices.remove_all_matching([&](auto const& index) { return !process_table_view.is_toggled(index); });
  280. process_model->update();
  281. if (!process_table_view.selection().is_empty())
  282. process_table_view.selection().for_each_index([&](auto& selection) {
  283. if (toggled_indices.contains_slow(selection))
  284. process_table_view.expand_all_parents_of(selection);
  285. });
  286. if (auto* memory_stats_widget = SystemMonitor::MemoryStatsWidget::the())
  287. memory_stats_widget->refresh();
  288. };
  289. update_stats();
  290. auto& refresh_timer = window->add<Core::Timer>(frequency * 1000, move(update_stats));
  291. refresh_timer.start();
  292. auto selected_id = [&](ProcessModel::Column column) -> pid_t {
  293. if (process_table_view.selection().is_empty())
  294. return -1;
  295. auto pid_index = process_table_view.model()->index(process_table_view.selection().first().row(), column, process_table_view.selection().first().parent());
  296. return pid_index.data().to_i32();
  297. };
  298. auto selected_name = [&](ProcessModel::Column column) -> DeprecatedString {
  299. if (process_table_view.selection().is_empty())
  300. return {};
  301. auto pid_index = process_table_view.model()->index(process_table_view.selection().first().row(), column, process_table_view.selection().first().parent());
  302. return pid_index.data().to_deprecated_string();
  303. };
  304. auto kill_action = GUI::Action::create(
  305. "&Kill Process", { Mod_Ctrl, Key_K }, { Key_Delete }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/kill.png"sv)), [&](const GUI::Action&) {
  306. pid_t pid = selected_id(ProcessModel::Column::PID);
  307. if (pid == -1)
  308. return;
  309. auto rc = GUI::MessageBox::show(window, DeprecatedString::formatted("Do you really want to kill \"{}\" (PID {})?", selected_name(ProcessModel::Column::Name), pid), "System Monitor"sv, GUI::MessageBox::Type::Question, GUI::MessageBox::InputType::YesNo);
  310. if (rc == GUI::Dialog::ExecResult::Yes)
  311. kill(pid, SIGKILL);
  312. },
  313. &process_table_view);
  314. auto stop_action = GUI::Action::create(
  315. "&Stop Process", { Mod_Ctrl, Key_S }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/stop-hand.png"sv)), [&](const GUI::Action&) {
  316. pid_t pid = selected_id(ProcessModel::Column::PID);
  317. if (pid == -1)
  318. return;
  319. auto rc = GUI::MessageBox::show(window, DeprecatedString::formatted("Do you really want to stop \"{}\" (PID {})?", selected_name(ProcessModel::Column::Name), pid), "System Monitor"sv, GUI::MessageBox::Type::Question, GUI::MessageBox::InputType::YesNo);
  320. if (rc == GUI::Dialog::ExecResult::Yes)
  321. kill(pid, SIGSTOP);
  322. },
  323. &process_table_view);
  324. auto continue_action = GUI::Action::create(
  325. "&Continue Process", { Mod_Ctrl, Key_C }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/continue.png"sv)), [&](const GUI::Action&) {
  326. pid_t pid = selected_id(ProcessModel::Column::PID);
  327. if (pid != -1)
  328. kill(pid, SIGCONT);
  329. },
  330. &process_table_view);
  331. auto profile_action = GUI::Action::create(
  332. "&Profile Process", { Mod_Ctrl, Key_P },
  333. TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png"sv)), [&](auto&) {
  334. pid_t pid = selected_id(ProcessModel::Column::PID);
  335. if (pid == -1)
  336. return;
  337. auto pid_string = DeprecatedString::number(pid);
  338. GUI::Process::spawn_or_show_error(window, "/bin/Profiler"sv, Array { "--pid", pid_string.characters() });
  339. },
  340. &process_table_view);
  341. auto debug_action = GUI::Action::create(
  342. "Debug in HackStudio", { Mod_Ctrl, Key_D }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"sv)), [&](const GUI::Action&) {
  343. pid_t pid = selected_id(ProcessModel::Column::PID);
  344. if (pid == -1)
  345. return;
  346. auto pid_string = DeprecatedString::number(pid);
  347. GUI::Process::spawn_or_show_error(window, "/bin/HackStudio"sv, Array { "--pid", pid_string.characters() });
  348. },
  349. &process_table_view);
  350. HashMap<pid_t, NonnullRefPtr<GUI::Window>> process_windows;
  351. auto process_properties_action = GUI::CommonActions::make_properties_action(
  352. [&](auto&) {
  353. auto pid = selected_id(ProcessModel::Column::PID);
  354. if (pid == -1)
  355. return;
  356. RefPtr<GUI::Window> process_window;
  357. auto it = process_windows.find(pid);
  358. if (it == process_windows.end()) {
  359. auto process_window_or_error = build_process_window(pid);
  360. if (process_window_or_error.is_error())
  361. return;
  362. process_window = process_window_or_error.release_value();
  363. process_window->on_close_request = [pid, &process_windows] {
  364. process_windows.remove(pid);
  365. return GUI::Window::CloseRequestDecision::Close;
  366. };
  367. process_windows.set(pid, *process_window);
  368. } else {
  369. process_window = it->value;
  370. }
  371. process_window->show();
  372. process_window->move_to_front();
  373. },
  374. &process_table_view);
  375. auto& file_menu = window->add_menu("&File"_short_string);
  376. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  377. GUI::Application::the()->quit();
  378. }));
  379. auto process_context_menu = GUI::Menu::construct();
  380. process_context_menu->add_action(kill_action);
  381. process_context_menu->add_action(stop_action);
  382. process_context_menu->add_action(continue_action);
  383. process_context_menu->add_separator();
  384. process_context_menu->add_action(profile_action);
  385. process_context_menu->add_action(debug_action);
  386. process_context_menu->add_separator();
  387. process_context_menu->add_action(process_properties_action);
  388. process_table_view.on_context_menu_request = [&]([[maybe_unused]] const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  389. if (index.is_valid())
  390. process_context_menu->popup(event.screen_position(), process_properties_action);
  391. };
  392. auto& frequency_menu = window->add_menu(TRY("F&requency"_string));
  393. GUI::ActionGroup frequency_action_group;
  394. frequency_action_group.set_exclusive(true);
  395. auto make_frequency_action = [&](int seconds) {
  396. auto action = GUI::Action::create_checkable(DeprecatedString::formatted("&{} Sec", seconds), [&refresh_timer, seconds](auto&) {
  397. Config::write_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, seconds);
  398. refresh_timer.restart(seconds * 1000);
  399. });
  400. action->set_status_tip(DeprecatedString::formatted("Refresh every {} seconds", seconds));
  401. action->set_checked(frequency == seconds);
  402. frequency_action_group.add_action(*action);
  403. frequency_menu.add_action(*action);
  404. };
  405. make_frequency_action(1);
  406. make_frequency_action(3);
  407. make_frequency_action(5);
  408. auto& help_menu = window->add_menu("&Help"_short_string);
  409. help_menu.add_action(GUI::CommonActions::make_command_palette_action(window));
  410. help_menu.add_action(GUI::CommonActions::make_about_action("System Monitor", app_icon, window));
  411. process_table_view.on_activation = [&](auto&) {
  412. if (process_properties_action->is_enabled())
  413. process_properties_action->activate();
  414. };
  415. static pid_t last_selected_pid;
  416. process_table_view.on_selection_change = [&] {
  417. pid_t pid = selected_id(ProcessModel::Column::PID);
  418. if (pid == last_selected_pid || pid < 1)
  419. return;
  420. last_selected_pid = pid;
  421. bool has_access = can_access_pid(pid);
  422. kill_action->set_enabled(has_access);
  423. stop_action->set_enabled(has_access);
  424. continue_action->set_enabled(has_access);
  425. profile_action->set_enabled(has_access);
  426. debug_action->set_enabled(has_access);
  427. process_properties_action->set_enabled(has_access);
  428. };
  429. app->on_action_enter = [](GUI::Action const& action) {
  430. statusbar->set_override_text(action.status_tip());
  431. };
  432. app->on_action_leave = [](GUI::Action const&) {
  433. statusbar->set_override_text({});
  434. };
  435. window->show();
  436. window->set_icon(app_icon.bitmap_for_size(16));
  437. if (args_tab_view == "processes")
  438. tabwidget.set_active_widget(&process_table_container);
  439. else if (args_tab_view == "graphs")
  440. tabwidget.set_active_widget(&performance_widget);
  441. else if (args_tab_view == "fs")
  442. tabwidget.set_active_widget(tabwidget.find_descendant_of_type_named<SystemMonitor::StorageTabWidget>("storage"));
  443. else if (args_tab_view == "network")
  444. tabwidget.set_active_widget(tabwidget.find_descendant_of_type_named<GUI::Widget>("network"));
  445. int exec = app->exec();
  446. // When exiting the application, save the configuration of the columns
  447. // to be loaded the next time the application is opened.
  448. auto& process_table_header = process_table_view.column_header();
  449. for (auto column = 0; column < ProcessModel::Column::__Count; ++column)
  450. Config::write_bool("SystemMonitor"sv, "ProcessTableColumns"sv, process_model->column_name(column), process_table_header.is_section_visible(column));
  451. return exec;
  452. }
  453. ErrorOr<NonnullRefPtr<GUI::Window>> build_process_window(pid_t pid)
  454. {
  455. auto window = GUI::Window::construct();
  456. window->resize(480, 360);
  457. window->set_title(DeprecatedString::formatted("PID {} - System Monitor", pid));
  458. auto app_icon = GUI::Icon::default_icon("app-system-monitor"sv);
  459. window->set_icon(app_icon.bitmap_for_size(16));
  460. auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
  461. TRY(main_widget->load_from_gml(process_window_gml));
  462. GUI::ModelIndex process_index;
  463. for (int row = 0; row < ProcessModel::the().row_count({}); ++row) {
  464. auto index = ProcessModel::the().index(row, ProcessModel::Column::PID);
  465. if (index.data().to_i32() == pid) {
  466. process_index = index;
  467. break;
  468. }
  469. }
  470. VERIFY(process_index.is_valid());
  471. if (auto icon_data = process_index.sibling_at_column(ProcessModel::Column::Icon).data(); icon_data.is_icon()) {
  472. main_widget->find_descendant_of_type_named<GUI::ImageWidget>("process_icon")->set_bitmap(icon_data.as_icon().bitmap_for_size(32));
  473. }
  474. main_widget->find_descendant_of_type_named<GUI::Label>("process_name")->set_text(String::formatted("{} (PID {})", process_index.sibling_at_column(ProcessModel::Column::Name).data().to_deprecated_string(), pid).release_value_but_fixme_should_propagate_errors());
  475. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessStateWidget>("process_state")->set_pid(pid);
  476. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessFileDescriptorMapWidget>("open_files")->set_pid(pid);
  477. main_widget->find_descendant_of_type_named<SystemMonitor::ThreadStackWidget>("thread_stack")->set_ids(pid, pid);
  478. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessMemoryMapWidget>("memory_map")->set_pid(pid);
  479. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessUnveiledPathsWidget>("unveiled_paths")->set_pid(pid);
  480. auto& widget_stack = *main_widget->find_descendant_of_type_named<GUI::StackWidget>("widget_stack");
  481. auto& unavailable_process_widget = *widget_stack.find_descendant_of_type_named<SystemMonitor::UnavailableProcessWidget>("unavailable_process");
  482. unavailable_process_widget.set_text(DeprecatedString::formatted("Unable to access PID {}", pid));
  483. if (can_access_pid(pid))
  484. widget_stack.set_active_widget(widget_stack.find_descendant_of_type_named<GUI::TabWidget>("available_process"));
  485. else
  486. widget_stack.set_active_widget(&unavailable_process_widget);
  487. return window;
  488. }
  489. void build_performance_tab(GUI::Widget& graphs_container)
  490. {
  491. auto& cpu_graph_group_box = *graphs_container.find_descendant_of_type_named<GUI::GroupBox>("cpu_graph");
  492. size_t cpu_graphs_per_row = min(4, ProcessModel::the().cpus().size());
  493. auto cpu_graph_rows = ceil_div(ProcessModel::the().cpus().size(), cpu_graphs_per_row);
  494. cpu_graph_group_box.set_fixed_height(120u * cpu_graph_rows);
  495. Vector<SystemMonitor::GraphWidget&> cpu_graphs;
  496. for (auto row = 0u; row < cpu_graph_rows; ++row) {
  497. auto& cpu_graph_row = cpu_graph_group_box.add<GUI::Widget>();
  498. cpu_graph_row.set_layout<GUI::HorizontalBoxLayout>(6);
  499. cpu_graph_row.set_fixed_height(108);
  500. for (auto i = 0u; i < cpu_graphs_per_row; ++i) {
  501. auto& cpu_graph = cpu_graph_row.add<SystemMonitor::GraphWidget>();
  502. cpu_graph.set_max(100);
  503. cpu_graph.set_value_format(0, {
  504. .graph_color_role = ColorRole::SyntaxPreprocessorStatement,
  505. .text_formatter = [](u64 value) {
  506. return DeprecatedString::formatted("Total: {}%", value);
  507. },
  508. });
  509. cpu_graph.set_value_format(1, {
  510. .graph_color_role = ColorRole::SyntaxPreprocessorValue,
  511. .text_formatter = [](u64 value) {
  512. return DeprecatedString::formatted("Kernel: {}%", value);
  513. },
  514. });
  515. cpu_graphs.append(cpu_graph);
  516. }
  517. }
  518. ProcessModel::the().on_cpu_info_change = [cpu_graphs](Vector<NonnullOwnPtr<ProcessModel::CpuInfo>> const& cpus) mutable {
  519. float sum_cpu = 0;
  520. for (size_t i = 0; i < cpus.size(); ++i) {
  521. cpu_graphs[i].add_value({ static_cast<size_t>(cpus[i]->total_cpu_percent), static_cast<size_t>(cpus[i]->total_cpu_percent_kernel) });
  522. sum_cpu += cpus[i]->total_cpu_percent;
  523. }
  524. float cpu_usage = sum_cpu / (float)cpus.size();
  525. statusbar->set_text(2, DeprecatedString::formatted("CPU usage: {}%", (int)roundf(cpu_usage)));
  526. };
  527. auto& memory_graph = *graphs_container.find_descendant_of_type_named<SystemMonitor::GraphWidget>("memory_graph");
  528. memory_graph.set_value_format(0, {
  529. .graph_color_role = ColorRole::SyntaxComment,
  530. .text_formatter = [](u64 bytes) {
  531. return DeprecatedString::formatted("Committed: {}", human_readable_size(bytes));
  532. },
  533. });
  534. memory_graph.set_value_format(1, {
  535. .graph_color_role = ColorRole::SyntaxPreprocessorStatement,
  536. .text_formatter = [](u64 bytes) {
  537. return DeprecatedString::formatted("Allocated: {}", human_readable_size(bytes));
  538. },
  539. });
  540. memory_graph.set_value_format(2, {
  541. .graph_color_role = ColorRole::SyntaxPreprocessorValue,
  542. .text_formatter = [](u64 bytes) {
  543. return DeprecatedString::formatted("Kernel heap: {}", human_readable_size(bytes));
  544. },
  545. });
  546. }