Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "DevicesModel.h"
28#include "GraphWidget.h"
29#include "MemoryStatsWidget.h"
30#include "NetworkStatisticsWidget.h"
31#include "ProcessFileDescriptorMapWidget.h"
32#include "ProcessMemoryMapWidget.h"
33#include "ProcessModel.h"
34#include "ProcessStacksWidget.h"
35#include "ProcessTableView.h"
36#include "ProcessUnveiledPathsWidget.h"
37#include <LibCore/Timer.h>
38#include <LibGUI/AboutDialog.h>
39#include <LibGUI/Action.h>
40#include <LibGUI/ActionGroup.h>
41#include <LibGUI/Application.h>
42#include <LibGUI/BoxLayout.h>
43#include <LibGUI/GroupBox.h>
44#include <LibGUI/JsonArrayModel.h>
45#include <LibGUI/Label.h>
46#include <LibGUI/LazyWidget.h>
47#include <LibGUI/Menu.h>
48#include <LibGUI/MenuBar.h>
49#include <LibGUI/Painter.h>
50#include <LibGUI/SortingProxyModel.h>
51#include <LibGUI/Splitter.h>
52#include <LibGUI/TabWidget.h>
53#include <LibGUI/ToolBar.h>
54#include <LibGUI/Widget.h>
55#include <LibGUI/Window.h>
56#include <LibGfx/Palette.h>
57#include <LibPCIDB/Database.h>
58#include <signal.h>
59#include <stdio.h>
60#include <unistd.h>
61
62static String human_readable_size(u32 size)
63{
64 if (size < (64 * KB))
65 return String::format("%u", size);
66 if (size < MB)
67 return String::format("%u KB", size / KB);
68 if (size < GB)
69 return String::format("%u MB", size / MB);
70 return String::format("%u GB", size / GB);
71}
72
73static NonnullRefPtr<GUI::Widget> build_file_systems_tab();
74static NonnullRefPtr<GUI::Widget> build_pci_devices_tab();
75static NonnullRefPtr<GUI::Widget> build_devices_tab();
76static NonnullRefPtr<GUI::Widget> build_graphs_tab();
77
78int main(int argc, char** argv)
79{
80 if (pledge("stdio proc shared_buffer accept rpath unix cpath fattr", nullptr) < 0) {
81 perror("pledge");
82 return 1;
83 }
84
85 GUI::Application app(argc, argv);
86
87 if (pledge("stdio proc shared_buffer accept rpath", nullptr) < 0) {
88 perror("pledge");
89 return 1;
90 }
91
92 if (unveil("/etc/passwd", "r") < 0) {
93 perror("unveil");
94 return 1;
95 }
96
97 if (unveil("/res", "r") < 0) {
98 perror("unveil");
99 return 1;
100 }
101
102 if (unveil("/proc", "r") < 0) {
103 perror("unveil");
104 return 1;
105 }
106
107 if (unveil("/dev", "r") < 0) {
108 perror("unveil");
109 return 1;
110 }
111
112 unveil(nullptr, nullptr);
113
114 auto window = GUI::Window::construct();
115 window->set_title("System Monitor");
116 window->set_rect(20, 200, 680, 400);
117
118 auto keeper = GUI::Widget::construct();
119 window->set_main_widget(keeper);
120 keeper->set_layout(make<GUI::VerticalBoxLayout>());
121 keeper->set_fill_with_background_color(true);
122 keeper->layout()->set_margins({ 4, 4, 4, 4 });
123
124 auto tabwidget = keeper->add<GUI::TabWidget>();
125
126 auto process_container_splitter = tabwidget->add_tab<GUI::VerticalSplitter>("Processes");
127
128 auto process_table_container = process_container_splitter->add<GUI::Widget>();
129
130 tabwidget->add_widget("Graphs", build_graphs_tab());
131
132 tabwidget->add_widget("File systems", build_file_systems_tab());
133
134 tabwidget->add_widget("PCI devices", build_pci_devices_tab());
135
136 tabwidget->add_widget("Devices", build_devices_tab());
137
138 auto network_stats_widget = NetworkStatisticsWidget::construct();
139 tabwidget->add_widget("Network", network_stats_widget);
140
141 process_table_container->set_layout(make<GUI::VerticalBoxLayout>());
142 process_table_container->layout()->set_margins({ 4, 0, 4, 0 });
143 process_table_container->layout()->set_spacing(0);
144
145 auto toolbar = process_table_container->add<GUI::ToolBar>();
146 toolbar->set_has_frame(false);
147 auto process_table_view = process_table_container->add<ProcessTableView>();
148
149 auto refresh_timer = window->add<Core::Timer>(
150 1000, [&] {
151 process_table_view->refresh();
152 if (auto* memory_stats_widget = MemoryStatsWidget::the())
153 memory_stats_widget->refresh();
154 });
155
156 auto kill_action = GUI::Action::create("Kill process", { Mod_Ctrl, Key_K }, Gfx::Bitmap::load_from_file("/res/icons/kill16.png"), [process_table_view](const GUI::Action&) {
157 pid_t pid = process_table_view->selected_pid();
158 if (pid != -1)
159 kill(pid, SIGKILL);
160 });
161
162 auto stop_action = GUI::Action::create("Stop process", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/stop16.png"), [process_table_view](const GUI::Action&) {
163 pid_t pid = process_table_view->selected_pid();
164 if (pid != -1)
165 kill(pid, SIGSTOP);
166 });
167
168 auto continue_action = GUI::Action::create("Continue process", { Mod_Ctrl, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/continue16.png"), [process_table_view](const GUI::Action&) {
169 pid_t pid = process_table_view->selected_pid();
170 if (pid != -1)
171 kill(pid, SIGCONT);
172 });
173
174 toolbar->add_action(kill_action);
175 toolbar->add_action(stop_action);
176 toolbar->add_action(continue_action);
177
178 auto menubar = make<GUI::MenuBar>();
179 auto app_menu = GUI::Menu::construct("System Monitor");
180 app_menu->add_action(GUI::CommonActions::make_quit_action([](auto&) {
181 GUI::Application::the().quit(0);
182 return;
183 }));
184 menubar->add_menu(move(app_menu));
185
186 auto process_menu = GUI::Menu::construct("Process");
187 process_menu->add_action(kill_action);
188 process_menu->add_action(stop_action);
189 process_menu->add_action(continue_action);
190 menubar->add_menu(move(process_menu));
191
192 auto process_context_menu = GUI::Menu::construct();
193 process_context_menu->add_action(kill_action);
194 process_context_menu->add_action(stop_action);
195 process_context_menu->add_action(continue_action);
196 process_table_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
197 (void)index;
198 process_context_menu->popup(event.screen_position());
199 };
200
201 auto frequency_menu = GUI::Menu::construct("Frequency");
202 GUI::ActionGroup frequency_action_group;
203 frequency_action_group.set_exclusive(true);
204
205 auto make_frequency_action = [&](auto& title, int interval, bool checked = false) {
206 auto action = GUI::Action::create(title, [&refresh_timer, interval](auto& action) {
207 refresh_timer->restart(interval);
208 action.set_checked(true);
209 });
210 action->set_checkable(true);
211 action->set_checked(checked);
212 frequency_action_group.add_action(*action);
213 frequency_menu->add_action(*action);
214 };
215
216 make_frequency_action("0.25 sec", 250);
217 make_frequency_action("0.5 sec", 500);
218 make_frequency_action("1 sec", 1000, true);
219 make_frequency_action("3 sec", 3000);
220 make_frequency_action("5 sec", 5000);
221
222 menubar->add_menu(move(frequency_menu));
223
224 auto help_menu = GUI::Menu::construct("Help");
225 help_menu->add_action(GUI::Action::create("About", [&](const GUI::Action&) {
226 GUI::AboutDialog::show("System Monitor", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-system-monitor.png"), window);
227 }));
228 menubar->add_menu(move(help_menu));
229
230 app.set_menubar(move(menubar));
231
232 auto process_tab_widget = process_container_splitter->add<GUI::TabWidget>();
233
234 auto memory_map_widget = process_tab_widget->add_tab<ProcessMemoryMapWidget>("Memory map");
235 auto open_files_widget = process_tab_widget->add_tab<ProcessFileDescriptorMapWidget>("Open files");
236 auto unveiled_paths_widget = process_tab_widget->add_tab<ProcessUnveiledPathsWidget>("Unveiled paths");
237 auto stacks_widget = process_tab_widget->add_tab<ProcessStacksWidget>("Stacks");
238
239 process_table_view->on_process_selected = [&](pid_t pid) {
240 open_files_widget->set_pid(pid);
241 stacks_widget->set_pid(pid);
242 memory_map_widget->set_pid(pid);
243 unveiled_paths_widget->set_pid(pid);
244 };
245
246 window->show();
247
248 window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-system-monitor.png"));
249
250 return app.exec();
251}
252
253class ProgressBarPaintingDelegate final : public GUI::TableCellPaintingDelegate {
254public:
255 virtual ~ProgressBarPaintingDelegate() override {}
256
257 virtual void paint(GUI::Painter& painter, const Gfx::Rect& a_rect, const Palette& palette, const GUI::Model& model, const GUI::ModelIndex& index) override
258 {
259 auto rect = a_rect.shrunken(2, 2);
260 auto percentage = model.data(index, GUI::Model::Role::Custom).to_i32();
261
262 auto data = model.data(index, GUI::Model::Role::Display);
263 String text;
264 if (data.is_string())
265 text = data.as_string();
266 Gfx::StylePainter::paint_progress_bar(painter, rect, palette, 0, 100, percentage, text);
267 painter.draw_rect(rect, Color::Black);
268 }
269};
270
271NonnullRefPtr<GUI::Widget> build_file_systems_tab()
272{
273 auto fs_widget = GUI::LazyWidget::construct();
274
275 fs_widget->on_first_show = [](GUI::LazyWidget& self) {
276 self.set_layout(make<GUI::VerticalBoxLayout>());
277 self.layout()->set_margins({ 4, 4, 4, 4 });
278 auto fs_table_view = self.add<GUI::TableView>();
279 fs_table_view->set_size_columns_to_fit_content(true);
280
281 Vector<GUI::JsonArrayModel::FieldSpec> df_fields;
282 df_fields.empend("mount_point", "Mount point", Gfx::TextAlignment::CenterLeft);
283 df_fields.empend("class_name", "Class", Gfx::TextAlignment::CenterLeft);
284 df_fields.empend("device", "Device", Gfx::TextAlignment::CenterLeft);
285 df_fields.empend(
286 "Size", Gfx::TextAlignment::CenterRight,
287 [](const JsonObject& object) {
288 StringBuilder size_builder;
289 size_builder.append(" ");
290 size_builder.append(human_readable_size(object.get("total_block_count").to_u32() * object.get("block_size").to_u32()));
291 size_builder.append(" ");
292 return size_builder.to_string();
293 },
294 [](const JsonObject& object) {
295 return object.get("total_block_count").to_u32() * object.get("block_size").to_u32();
296 });
297 df_fields.empend(
298 "Used", Gfx::TextAlignment::CenterRight,
299 [](const JsonObject& object) {
300 auto total_blocks = object.get("total_block_count").to_u32();
301 auto free_blocks = object.get("free_block_count").to_u32();
302 auto used_blocks = total_blocks - free_blocks;
303 return human_readable_size(used_blocks * object.get("block_size").to_u32()); },
304 [](const JsonObject& object) {
305 auto total_blocks = object.get("total_block_count").to_u32();
306 auto free_blocks = object.get("free_block_count").to_u32();
307 auto used_blocks = total_blocks - free_blocks;
308 return used_blocks * object.get("block_size").to_u32();
309 },
310 [](const JsonObject& object) {
311 auto total_blocks = object.get("total_block_count").to_u32();
312 if (total_blocks == 0)
313 return 0;
314 auto free_blocks = object.get("free_block_count").to_u32();
315 auto used_blocks = total_blocks - free_blocks;
316 int percentage = (int)((float)used_blocks / (float)total_blocks * 100.0f);
317 return percentage;
318 });
319 df_fields.empend(
320 "Available", Gfx::TextAlignment::CenterRight,
321 [](const JsonObject& object) {
322 return human_readable_size(object.get("free_block_count").to_u32() * object.get("block_size").to_u32());
323 },
324 [](const JsonObject& object) {
325 return object.get("free_block_count").to_u32() * object.get("block_size").to_u32();
326 });
327 df_fields.empend("Access", Gfx::TextAlignment::CenterLeft, [](const JsonObject& object) {
328 return object.get("readonly").to_bool() ? "Read-only" : "Read/Write";
329 });
330 df_fields.empend("Mount flags", Gfx::TextAlignment::CenterLeft, [](const JsonObject& object) {
331 int mount_flags = object.get("mount_flags").to_int();
332 StringBuilder builder;
333 bool first = true;
334 auto check = [&](int flag, const char* name) {
335 if (!(mount_flags & flag))
336 return;
337 if (!first)
338 builder.append(',');
339 builder.append(name);
340 first = false;
341 };
342 check(MS_NODEV, "nodev");
343 check(MS_NOEXEC, "noexec");
344 check(MS_NOSUID, "nosuid");
345 check(MS_BIND, "bind");
346 if (builder.string_view().is_empty())
347 return String("defaults");
348 return builder.to_string();
349 });
350 df_fields.empend("free_block_count", "Free blocks", Gfx::TextAlignment::CenterRight);
351 df_fields.empend("total_block_count", "Total blocks", Gfx::TextAlignment::CenterRight);
352 df_fields.empend("free_inode_count", "Free inodes", Gfx::TextAlignment::CenterRight);
353 df_fields.empend("total_inode_count", "Total inodes", Gfx::TextAlignment::CenterRight);
354 df_fields.empend("block_size", "Block size", Gfx::TextAlignment::CenterRight);
355 fs_table_view->set_model(GUI::SortingProxyModel::create(GUI::JsonArrayModel::create("/proc/df", move(df_fields))));
356
357 fs_table_view->set_cell_painting_delegate(3, make<ProgressBarPaintingDelegate>());
358
359 fs_table_view->model()->update();
360 };
361 return fs_widget;
362}
363
364NonnullRefPtr<GUI::Widget> build_pci_devices_tab()
365{
366 auto pci_widget = GUI::LazyWidget::construct();
367
368 pci_widget->on_first_show = [](GUI::LazyWidget& self) {
369 self.set_layout(make<GUI::VerticalBoxLayout>());
370 self.layout()->set_margins({ 4, 4, 4, 4 });
371 auto pci_table_view = self.add<GUI::TableView>();
372 pci_table_view->set_size_columns_to_fit_content(true);
373
374 auto db = PCIDB::Database::open();
375
376 Vector<GUI::JsonArrayModel::FieldSpec> pci_fields;
377 pci_fields.empend(
378 "Address", Gfx::TextAlignment::CenterLeft,
379 [](const JsonObject& object) {
380 auto seg = object.get("seg").to_u32();
381 auto bus = object.get("bus").to_u32();
382 auto slot = object.get("slot").to_u32();
383 auto function = object.get("function").to_u32();
384 return String::format("%04x:%02x:%02x.%d", seg, bus, slot, function);
385 });
386 pci_fields.empend(
387 "Class", Gfx::TextAlignment::CenterLeft,
388 [db](const JsonObject& object) {
389 auto class_id = object.get("class").to_u32();
390 String class_name = db->get_class(class_id);
391 return class_name == "" ? String::format("%04x", class_id) : class_name;
392 });
393 pci_fields.empend(
394 "Vendor", Gfx::TextAlignment::CenterLeft,
395 [db](const JsonObject& object) {
396 auto vendor_id = object.get("vendor_id").to_u32();
397 String vendor_name = db->get_vendor(vendor_id);
398 return vendor_name == "" ? String::format("%02x", vendor_id) : vendor_name;
399 });
400 pci_fields.empend(
401 "Device", Gfx::TextAlignment::CenterLeft,
402 [db](const JsonObject& object) {
403 auto vendor_id = object.get("vendor_id").to_u32();
404 auto device_id = object.get("device_id").to_u32();
405 String device_name = db->get_device(vendor_id, device_id);
406 return device_name == "" ? String::format("%02x", device_id) : device_name;
407 });
408 pci_fields.empend(
409 "Revision", Gfx::TextAlignment::CenterRight,
410 [](const JsonObject& object) {
411 auto revision_id = object.get("revision_id").to_u32();
412 return String::format("%02x", revision_id);
413 });
414
415 pci_table_view->set_model(GUI::SortingProxyModel::create(GUI::JsonArrayModel::create("/proc/pci", move(pci_fields))));
416 pci_table_view->model()->update();
417 };
418
419 return pci_widget;
420}
421
422NonnullRefPtr<GUI::Widget> build_devices_tab()
423{
424 auto devices_widget = GUI::LazyWidget::construct();
425
426 devices_widget->on_first_show = [](GUI::LazyWidget& self) {
427 self.set_layout(make<GUI::VerticalBoxLayout>());
428 self.layout()->set_margins({ 4, 4, 4, 4 });
429
430 auto devices_table_view = self.add<GUI::TableView>();
431 devices_table_view->set_size_columns_to_fit_content(true);
432 devices_table_view->set_model(GUI::SortingProxyModel::create(DevicesModel::create()));
433 devices_table_view->model()->update();
434 };
435
436 return devices_widget;
437}
438
439NonnullRefPtr<GUI::Widget> build_graphs_tab()
440{
441 auto graphs_container = GUI::LazyWidget::construct();
442
443 graphs_container->on_first_show = [](GUI::LazyWidget& self) {
444 self.set_fill_with_background_color(true);
445 self.set_background_role(ColorRole::Button);
446 self.set_layout(make<GUI::VerticalBoxLayout>());
447 self.layout()->set_margins({ 4, 4, 4, 4 });
448
449 auto cpu_graph_group_box = self.add<GUI::GroupBox>("CPU usage");
450 cpu_graph_group_box->set_layout(make<GUI::VerticalBoxLayout>());
451 cpu_graph_group_box->layout()->set_margins({ 6, 16, 6, 6 });
452 cpu_graph_group_box->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
453 cpu_graph_group_box->set_preferred_size(0, 120);
454 auto cpu_graph = cpu_graph_group_box->add<GraphWidget>();
455 cpu_graph->set_max(100);
456 cpu_graph->set_text_color(Color::Green);
457 cpu_graph->set_graph_color(Color::from_rgb(0x00bb00));
458 cpu_graph->text_formatter = [](int value, int) {
459 return String::format("%d%%", value);
460 };
461
462 ProcessModel::the().on_new_cpu_data_point = [graph = cpu_graph.ptr()](float cpu_percent) {
463 graph->add_value(cpu_percent);
464 };
465
466 auto memory_graph_group_box = self.add<GUI::GroupBox>("Memory usage");
467 memory_graph_group_box->set_layout(make<GUI::VerticalBoxLayout>());
468 memory_graph_group_box->layout()->set_margins({ 6, 16, 6, 6 });
469 memory_graph_group_box->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
470 memory_graph_group_box->set_preferred_size(0, 120);
471 auto memory_graph = memory_graph_group_box->add<GraphWidget>();
472 memory_graph->set_text_color(Color::Cyan);
473 memory_graph->set_graph_color(Color::from_rgb(0x00bbbb));
474 memory_graph->text_formatter = [](int value, int max) {
475 return String::format("%d / %d KB", value, max);
476 };
477
478 auto memory_stats_widget = self.add<MemoryStatsWidget>(*memory_graph);
479 };
480 return graphs_container;
481}