main.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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/EventReceiver.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 ErrorOr<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. String const& text() const { return m_text; }
  83. void set_text(String text)
  84. {
  85. m_text = move(text);
  86. update();
  87. }
  88. private:
  89. UnavailableProcessWidget()
  90. {
  91. REGISTER_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. String 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, Gfx::TextAlignment::CenterLeft);
  113. df_fields.empend("class_name", "Class"_string, Gfx::TextAlignment::CenterLeft);
  114. df_fields.empend("source", "Source"_string, Gfx::TextAlignment::CenterLeft);
  115. df_fields.empend(
  116. "Size"_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"_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, 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"_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, 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, Gfx::TextAlignment::CenterRight);
  187. df_fields.empend("total_block_count", "Total blocks"_string, Gfx::TextAlignment::CenterRight);
  188. df_fields.empend("free_inode_count", "Free inodes"_string, Gfx::TextAlignment::CenterRight);
  189. df_fields.empend("total_inode_count", "Total inodes"_string, Gfx::TextAlignment::CenterRight);
  190. df_fields.empend("block_size", "Block size"_string, 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. // HackStudio doesn't exist in the minimal build configuration.
  240. if (auto result = Core::System::unveil("/bin/HackStudio", "rx"); result.is_error() && result.error().code() != ENOENT)
  241. return result.release_error();
  242. TRY(Core::System::unveil(nullptr, nullptr));
  243. StringView args_tab = "processes"sv;
  244. Core::ArgsParser parser;
  245. parser.add_option(args_tab, "Tab, one of 'processes', 'graphs', 'fs', 'hardware', or 'network'", "open-tab", 't', "tab");
  246. parser.parse(arguments);
  247. StringView args_tab_view = args_tab;
  248. auto app_icon = TRY(GUI::Icon::try_create_default_icon("app-system-monitor"sv));
  249. auto window = TRY(GUI::Window::try_create());
  250. window->set_title("System Monitor");
  251. window->resize(560, 430);
  252. auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
  253. TRY(main_widget->load_from_gml(system_monitor_gml));
  254. auto& tabwidget = *main_widget->find_descendant_of_type_named<GUI::TabWidget>("main_tabs");
  255. statusbar = main_widget->find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  256. auto& process_table_container = *tabwidget.find_descendant_of_type_named<GUI::Widget>("processes");
  257. auto process_model = ProcessModel::create();
  258. process_model->on_state_update = [&](int process_count, int thread_count) {
  259. statusbar->set_text(0, String::formatted("Processes: {}", process_count).release_value_but_fixme_should_propagate_errors());
  260. statusbar->set_text(1, String::formatted("Threads: {}", thread_count).release_value_but_fixme_should_propagate_errors());
  261. };
  262. auto& performance_widget = *tabwidget.find_descendant_of_type_named<GUI::Widget>("performance");
  263. TRY(build_performance_tab(performance_widget));
  264. auto& process_table_view = *process_table_container.find_child_of_type_named<GUI::TreeView>("process_table");
  265. process_table_view.set_model(TRY(GUI::SortingProxyModel::create(process_model)));
  266. for (auto column = 0; column < ProcessModel::Column::__Count; ++column) {
  267. process_table_view.set_column_visible(column,
  268. Config::read_bool("SystemMonitor"sv, "ProcessTableColumns"sv, TRY(process_model->column_name(column)),
  269. process_model->is_default_column(column)));
  270. }
  271. process_table_view.set_key_column_and_sort_order(ProcessModel::Column::CPU, GUI::SortOrder::Descending);
  272. process_model->update();
  273. i32 frequency = Config::read_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, 3);
  274. if (frequency != 1 && frequency != 3 && frequency != 5) {
  275. frequency = 3;
  276. Config::write_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, frequency);
  277. }
  278. auto update_stats = [&] {
  279. // FIXME: remove the primitive re-toggling code once persistent model indices work.
  280. auto toggled_indices = process_table_view.selection().indices();
  281. toggled_indices.remove_all_matching([&](auto const& index) { return !process_table_view.is_toggled(index); });
  282. process_model->update();
  283. if (!process_table_view.selection().is_empty())
  284. process_table_view.selection().for_each_index([&](auto& selection) {
  285. if (toggled_indices.contains_slow(selection))
  286. process_table_view.expand_all_parents_of(selection);
  287. });
  288. if (auto* memory_stats_widget = SystemMonitor::MemoryStatsWidget::the())
  289. memory_stats_widget->refresh();
  290. };
  291. update_stats();
  292. auto refresh_timer = TRY(window->try_add<Core::Timer>(frequency * 1000, move(update_stats)));
  293. refresh_timer->start();
  294. auto selected_id = [&](ProcessModel::Column column) -> pid_t {
  295. if (process_table_view.selection().is_empty())
  296. return -1;
  297. auto pid_index = process_table_view.model()->index(process_table_view.selection().first().row(), column, process_table_view.selection().first().parent());
  298. return pid_index.data().to_i32();
  299. };
  300. auto selected_name = [&](ProcessModel::Column column) -> DeprecatedString {
  301. if (process_table_view.selection().is_empty())
  302. return {};
  303. auto pid_index = process_table_view.model()->index(process_table_view.selection().first().row(), column, process_table_view.selection().first().parent());
  304. return pid_index.data().to_deprecated_string();
  305. };
  306. auto kill_action = GUI::Action::create(
  307. "&Kill Process", { Mod_Ctrl, Key_K }, { Key_Delete }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/kill.png"sv)), [&](const GUI::Action&) {
  308. pid_t pid = selected_id(ProcessModel::Column::PID);
  309. if (pid == -1)
  310. return;
  311. 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);
  312. if (rc == GUI::Dialog::ExecResult::Yes)
  313. kill(pid, SIGKILL);
  314. },
  315. &process_table_view);
  316. auto stop_action = GUI::Action::create(
  317. "&Stop Process", { Mod_Ctrl, Key_S }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/stop-hand.png"sv)), [&](const GUI::Action&) {
  318. pid_t pid = selected_id(ProcessModel::Column::PID);
  319. if (pid == -1)
  320. return;
  321. 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);
  322. if (rc == GUI::Dialog::ExecResult::Yes)
  323. kill(pid, SIGSTOP);
  324. },
  325. &process_table_view);
  326. auto continue_action = GUI::Action::create(
  327. "&Continue Process", { Mod_Ctrl, Key_C }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/continue.png"sv)), [&](const GUI::Action&) {
  328. pid_t pid = selected_id(ProcessModel::Column::PID);
  329. if (pid != -1)
  330. kill(pid, SIGCONT);
  331. },
  332. &process_table_view);
  333. auto profile_action = GUI::Action::create(
  334. "&Profile Process", { Mod_Ctrl, Key_P },
  335. TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-profiler.png"sv)), [&](auto&) {
  336. pid_t pid = selected_id(ProcessModel::Column::PID);
  337. if (pid == -1)
  338. return;
  339. auto pid_string = DeprecatedString::number(pid);
  340. GUI::Process::spawn_or_show_error(window, "/bin/Profiler"sv, Array { "--pid", pid_string.characters() });
  341. },
  342. &process_table_view);
  343. auto debug_action = GUI::Action::create(
  344. "Debug in HackStudio", { Mod_Ctrl, Key_D }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"sv)), [&](const GUI::Action&) {
  345. pid_t pid = selected_id(ProcessModel::Column::PID);
  346. if (pid == -1)
  347. return;
  348. auto pid_string = DeprecatedString::number(pid);
  349. GUI::Process::spawn_or_show_error(window, "/bin/HackStudio"sv, Array { "--pid", pid_string.characters() });
  350. },
  351. &process_table_view);
  352. HashMap<pid_t, NonnullRefPtr<GUI::Window>> process_windows;
  353. auto process_properties_action = GUI::CommonActions::make_properties_action(
  354. [&](auto&) {
  355. auto pid = selected_id(ProcessModel::Column::PID);
  356. if (pid == -1)
  357. return;
  358. RefPtr<GUI::Window> process_window;
  359. auto it = process_windows.find(pid);
  360. if (it == process_windows.end()) {
  361. auto process_window_or_error = build_process_window(pid);
  362. if (process_window_or_error.is_error())
  363. return;
  364. process_window = process_window_or_error.release_value();
  365. process_window->on_close_request = [pid, &process_windows] {
  366. process_windows.remove(pid);
  367. return GUI::Window::CloseRequestDecision::Close;
  368. };
  369. process_windows.set(pid, *process_window);
  370. } else {
  371. process_window = it->value;
  372. }
  373. process_window->show();
  374. process_window->move_to_front();
  375. },
  376. &process_table_view);
  377. auto file_menu = window->add_menu("&File"_string);
  378. file_menu->add_action(GUI::CommonActions::make_quit_action([](auto&) {
  379. GUI::Application::the()->quit();
  380. }));
  381. auto process_context_menu = TRY(GUI::Menu::try_create());
  382. process_context_menu->add_action(kill_action);
  383. process_context_menu->add_action(stop_action);
  384. process_context_menu->add_action(continue_action);
  385. process_context_menu->add_separator();
  386. process_context_menu->add_action(profile_action);
  387. process_context_menu->add_action(debug_action);
  388. process_context_menu->add_separator();
  389. process_context_menu->add_action(process_properties_action);
  390. process_table_view.on_context_menu_request = [&]([[maybe_unused]] const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  391. if (index.is_valid())
  392. process_context_menu->popup(event.screen_position(), process_properties_action);
  393. };
  394. auto frequency_menu = window->add_menu("F&requency"_string);
  395. GUI::ActionGroup frequency_action_group;
  396. frequency_action_group.set_exclusive(true);
  397. auto make_frequency_action = [&](int seconds) -> ErrorOr<void> {
  398. auto action = GUI::Action::create_checkable(DeprecatedString::formatted("&{} Sec", seconds), [&refresh_timer, seconds](auto&) {
  399. Config::write_i32("SystemMonitor"sv, "Monitor"sv, "Frequency"sv, seconds);
  400. refresh_timer->restart(seconds * 1000);
  401. });
  402. action->set_status_tip(TRY(String::formatted("Refresh every {} seconds", seconds)));
  403. action->set_checked(frequency == seconds);
  404. frequency_action_group.add_action(*action);
  405. frequency_menu->add_action(*action);
  406. return {};
  407. };
  408. TRY(make_frequency_action(1));
  409. TRY(make_frequency_action(3));
  410. TRY(make_frequency_action(5));
  411. auto help_menu = window->add_menu("&Help"_string);
  412. help_menu->add_action(GUI::CommonActions::make_command_palette_action(window));
  413. help_menu->add_action(GUI::CommonActions::make_about_action("System Monitor"_string, app_icon, window));
  414. process_table_view.on_activation = [&](auto&) {
  415. if (process_properties_action->is_enabled())
  416. process_properties_action->activate();
  417. };
  418. static pid_t last_selected_pid;
  419. process_table_view.on_selection_change = [&] {
  420. pid_t pid = selected_id(ProcessModel::Column::PID);
  421. if (pid == last_selected_pid || pid < 1)
  422. return;
  423. last_selected_pid = pid;
  424. bool has_access = can_access_pid(pid);
  425. kill_action->set_enabled(has_access);
  426. stop_action->set_enabled(has_access);
  427. continue_action->set_enabled(has_access);
  428. profile_action->set_enabled(has_access);
  429. debug_action->set_enabled(has_access);
  430. process_properties_action->set_enabled(has_access);
  431. };
  432. app->on_action_enter = [](GUI::Action const& action) {
  433. statusbar->set_override_text(action.status_tip());
  434. };
  435. app->on_action_leave = [](GUI::Action const&) {
  436. statusbar->set_override_text({});
  437. };
  438. window->show();
  439. window->set_icon(app_icon.bitmap_for_size(16));
  440. if (args_tab_view == "processes")
  441. tabwidget.set_active_widget(&process_table_container);
  442. else if (args_tab_view == "graphs")
  443. tabwidget.set_active_widget(&performance_widget);
  444. else if (args_tab_view == "fs")
  445. tabwidget.set_active_widget(tabwidget.find_descendant_of_type_named<SystemMonitor::StorageTabWidget>("storage"));
  446. else if (args_tab_view == "network")
  447. tabwidget.set_active_widget(tabwidget.find_descendant_of_type_named<GUI::Widget>("network"));
  448. int exec = app->exec();
  449. // When exiting the application, save the configuration of the columns
  450. // to be loaded the next time the application is opened.
  451. auto& process_table_header = process_table_view.column_header();
  452. for (auto column = 0; column < ProcessModel::Column::__Count; ++column)
  453. Config::write_bool("SystemMonitor"sv, "ProcessTableColumns"sv, TRY(process_model->column_name(column)), process_table_header.is_section_visible(column));
  454. return exec;
  455. }
  456. ErrorOr<NonnullRefPtr<GUI::Window>> build_process_window(pid_t pid)
  457. {
  458. auto window = TRY(GUI::Window::try_create());
  459. window->resize(480, 360);
  460. window->set_title(DeprecatedString::formatted("PID {} - System Monitor", pid));
  461. auto app_icon = TRY(GUI::Icon::try_create_default_icon("app-system-monitor"sv));
  462. window->set_icon(app_icon.bitmap_for_size(16));
  463. auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
  464. TRY(main_widget->load_from_gml(process_window_gml));
  465. GUI::ModelIndex process_index;
  466. for (int row = 0; row < ProcessModel::the().row_count({}); ++row) {
  467. auto index = ProcessModel::the().index(row, ProcessModel::Column::PID);
  468. if (index.data().to_i32() == pid) {
  469. process_index = index;
  470. break;
  471. }
  472. }
  473. VERIFY(process_index.is_valid());
  474. if (auto icon_data = process_index.sibling_at_column(ProcessModel::Column::Icon).data(); icon_data.is_icon()) {
  475. main_widget->find_descendant_of_type_named<GUI::ImageWidget>("process_icon")->set_bitmap(icon_data.as_icon().bitmap_for_size(32));
  476. }
  477. main_widget->find_descendant_of_type_named<GUI::Label>("process_name")->set_text(TRY(String::formatted("{} (PID {})", process_index.sibling_at_column(ProcessModel::Column::Name).data().to_deprecated_string(), pid)));
  478. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessStateWidget>("process_state")->set_pid(pid);
  479. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessFileDescriptorMapWidget>("open_files")->set_pid(pid);
  480. main_widget->find_descendant_of_type_named<SystemMonitor::ThreadStackWidget>("thread_stack")->set_ids(pid, pid);
  481. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessMemoryMapWidget>("memory_map")->set_pid(pid);
  482. main_widget->find_descendant_of_type_named<SystemMonitor::ProcessUnveiledPathsWidget>("unveiled_paths")->set_pid(pid);
  483. auto& widget_stack = *main_widget->find_descendant_of_type_named<GUI::StackWidget>("widget_stack");
  484. auto& unavailable_process_widget = *widget_stack.find_descendant_of_type_named<SystemMonitor::UnavailableProcessWidget>("unavailable_process");
  485. unavailable_process_widget.set_text(TRY(String::formatted("Unable to access PID {}", pid)));
  486. if (can_access_pid(pid))
  487. widget_stack.set_active_widget(widget_stack.find_descendant_of_type_named<GUI::TabWidget>("available_process"));
  488. else
  489. widget_stack.set_active_widget(&unavailable_process_widget);
  490. return window;
  491. }
  492. ErrorOr<void> build_performance_tab(GUI::Widget& graphs_container)
  493. {
  494. auto& cpu_graph_group_box = *graphs_container.find_descendant_of_type_named<GUI::GroupBox>("cpu_graph");
  495. size_t cpu_graphs_per_row = min(4, ProcessModel::the().cpus().size());
  496. auto cpu_graph_rows = ceil_div(ProcessModel::the().cpus().size(), cpu_graphs_per_row);
  497. cpu_graph_group_box.set_fixed_height(120u * cpu_graph_rows);
  498. Vector<SystemMonitor::GraphWidget&> cpu_graphs;
  499. for (auto row = 0u; row < cpu_graph_rows; ++row) {
  500. auto cpu_graph_row = TRY(cpu_graph_group_box.try_add<GUI::Widget>());
  501. cpu_graph_row->set_layout<GUI::HorizontalBoxLayout>(6);
  502. cpu_graph_row->set_fixed_height(108);
  503. for (auto i = 0u; i < cpu_graphs_per_row; ++i) {
  504. auto cpu_graph = TRY(cpu_graph_row->try_add<SystemMonitor::GraphWidget>());
  505. cpu_graph->set_max(100);
  506. cpu_graph->set_value_format(0, {
  507. .graph_color_role = ColorRole::SyntaxPreprocessorStatement,
  508. .text_formatter = [](u64 value) {
  509. return DeprecatedString::formatted("Total: {}%", value);
  510. },
  511. });
  512. cpu_graph->set_value_format(1, {
  513. .graph_color_role = ColorRole::SyntaxPreprocessorValue,
  514. .text_formatter = [](u64 value) {
  515. return DeprecatedString::formatted("Kernel: {}%", value);
  516. },
  517. });
  518. cpu_graphs.append(cpu_graph);
  519. }
  520. }
  521. ProcessModel::the().on_cpu_info_change = [cpu_graphs](Vector<NonnullOwnPtr<ProcessModel::CpuInfo>> const& cpus) mutable {
  522. float sum_cpu = 0;
  523. for (size_t i = 0; i < cpus.size(); ++i) {
  524. cpu_graphs[i].add_value({ static_cast<size_t>(cpus[i]->total_cpu_percent), static_cast<size_t>(cpus[i]->total_cpu_percent_kernel) });
  525. sum_cpu += cpus[i]->total_cpu_percent;
  526. }
  527. float cpu_usage = sum_cpu / (float)cpus.size();
  528. statusbar->set_text(2, String::formatted("CPU usage: {}%", (int)roundf(cpu_usage)).release_value_but_fixme_should_propagate_errors());
  529. };
  530. auto& memory_graph = *graphs_container.find_descendant_of_type_named<SystemMonitor::GraphWidget>("memory_graph");
  531. memory_graph.set_value_format(0, {
  532. .graph_color_role = ColorRole::SyntaxComment,
  533. .text_formatter = [](u64 bytes) {
  534. return DeprecatedString::formatted("Committed: {}", human_readable_size(bytes));
  535. },
  536. });
  537. memory_graph.set_value_format(1, {
  538. .graph_color_role = ColorRole::SyntaxPreprocessorStatement,
  539. .text_formatter = [](u64 bytes) {
  540. return DeprecatedString::formatted("Allocated: {}", human_readable_size(bytes));
  541. },
  542. });
  543. memory_graph.set_value_format(2, {
  544. .graph_color_role = ColorRole::SyntaxPreprocessorValue,
  545. .text_formatter = [](u64 bytes) {
  546. return DeprecatedString::formatted("Kernel heap: {}", human_readable_size(bytes));
  547. },
  548. });
  549. return {};
  550. }