main.cpp 28 KB

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