main.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. #include "DevicesModel.h"
  27. #include "GraphWidget.h"
  28. #include "MemoryStatsWidget.h"
  29. #include "NetworkStatisticsWidget.h"
  30. #include "ProcessFileDescriptorMapWidget.h"
  31. #include "ProcessMemoryMapWidget.h"
  32. #include "ProcessModel.h"
  33. #include "ProcessStacksWidget.h"
  34. #include "ProcessTableView.h"
  35. #include "ProcessUnveiledPathsWidget.h"
  36. #include <LibCore/Timer.h>
  37. #include <LibGUI/AboutDialog.h>
  38. #include <LibGUI/Action.h>
  39. #include <LibGUI/ActionGroup.h>
  40. #include <LibGUI/Application.h>
  41. #include <LibGUI/BoxLayout.h>
  42. #include <LibGUI/GroupBox.h>
  43. #include <LibGUI/JsonArrayModel.h>
  44. #include <LibGUI/Label.h>
  45. #include <LibGUI/LazyWidget.h>
  46. #include <LibGUI/Menu.h>
  47. #include <LibGUI/MenuBar.h>
  48. #include <LibGUI/Painter.h>
  49. #include <LibGUI/SortingProxyModel.h>
  50. #include <LibGUI/Splitter.h>
  51. #include <LibGUI/TabWidget.h>
  52. #include <LibGUI/ToolBar.h>
  53. #include <LibGUI/Widget.h>
  54. #include <LibGUI/Window.h>
  55. #include <LibGfx/Palette.h>
  56. #include <LibPCIDB/Database.h>
  57. #include <signal.h>
  58. #include <stdio.h>
  59. #include <unistd.h>
  60. static String human_readable_size(u32 size)
  61. {
  62. if (size < (64 * KB))
  63. return String::format("%u", size);
  64. if (size < MB)
  65. return String::format("%u KB", size / KB);
  66. if (size < GB)
  67. return String::format("%u MB", size / MB);
  68. return String::format("%u GB", size / GB);
  69. }
  70. static NonnullRefPtr<GUI::Widget> build_file_systems_tab();
  71. static NonnullRefPtr<GUI::Widget> build_pci_devices_tab();
  72. static NonnullRefPtr<GUI::Widget> build_devices_tab();
  73. static NonnullRefPtr<GUI::Widget> build_graphs_tab();
  74. class UnavailableProcessWidget final : public GUI::Frame {
  75. C_OBJECT(UnavailableProcessWidget)
  76. public:
  77. virtual ~UnavailableProcessWidget() override {}
  78. const String& text() const { return m_text; }
  79. void set_text(String text) { m_text = move(text); }
  80. private:
  81. UnavailableProcessWidget(String text)
  82. : m_text(move(text))
  83. {
  84. }
  85. virtual void paint_event(GUI::PaintEvent& event) override
  86. {
  87. Frame::paint_event(event);
  88. if (text().is_empty())
  89. return;
  90. GUI::Painter painter(*this);
  91. painter.add_clip_rect(event.rect());
  92. painter.draw_text(frame_inner_rect(), text(), Gfx::TextAlignment::Center, palette().window_text(), Gfx::TextElision::Right);
  93. }
  94. String m_text;
  95. };
  96. static bool
  97. can_access_pid(pid_t pid)
  98. {
  99. auto path = String::format("/proc/%d", pid);
  100. return access(path.characters(), X_OK) == 0;
  101. }
  102. int main(int argc, char** argv)
  103. {
  104. if (pledge("stdio proc shared_buffer accept rpath unix cpath fattr", nullptr) < 0) {
  105. perror("pledge");
  106. return 1;
  107. }
  108. GUI::Application app(argc, argv);
  109. if (pledge("stdio proc shared_buffer accept rpath", nullptr) < 0) {
  110. perror("pledge");
  111. return 1;
  112. }
  113. if (unveil("/etc/passwd", "r") < 0) {
  114. perror("unveil");
  115. return 1;
  116. }
  117. if (unveil("/res", "r") < 0) {
  118. perror("unveil");
  119. return 1;
  120. }
  121. if (unveil("/proc", "r") < 0) {
  122. perror("unveil");
  123. return 1;
  124. }
  125. if (unveil("/dev", "r") < 0) {
  126. perror("unveil");
  127. return 1;
  128. }
  129. unveil(nullptr, nullptr);
  130. auto window = GUI::Window::construct();
  131. window->set_title("System Monitor");
  132. window->set_rect(20, 200, 680, 400);
  133. auto& keeper = window->set_main_widget<GUI::Widget>();
  134. keeper.set_layout<GUI::VerticalBoxLayout>();
  135. keeper.set_fill_with_background_color(true);
  136. keeper.layout()->set_margins({ 2, 2, 2, 2 });
  137. auto& tabwidget = keeper.add<GUI::TabWidget>();
  138. auto& process_container_splitter = tabwidget.add_tab<GUI::VerticalSplitter>("Processes");
  139. process_container_splitter.layout()->set_margins({ 4, 4, 4, 4 });
  140. auto& process_table_container = process_container_splitter.add<GUI::Widget>();
  141. tabwidget.add_widget("Graphs", build_graphs_tab());
  142. tabwidget.add_widget("File systems", build_file_systems_tab());
  143. tabwidget.add_widget("PCI devices", build_pci_devices_tab());
  144. tabwidget.add_widget("Devices", build_devices_tab());
  145. auto network_stats_widget = NetworkStatisticsWidget::construct();
  146. tabwidget.add_widget("Network", network_stats_widget);
  147. process_table_container.set_layout<GUI::VerticalBoxLayout>();
  148. process_table_container.layout()->set_spacing(0);
  149. auto& process_table_view = process_table_container.add<ProcessTableView>();
  150. auto& refresh_timer = window->add<Core::Timer>(
  151. 1000, [&] {
  152. process_table_view.refresh();
  153. if (auto* memory_stats_widget = MemoryStatsWidget::the())
  154. memory_stats_widget->refresh();
  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. 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&) {
  162. pid_t pid = process_table_view.selected_pid();
  163. if (pid != -1)
  164. kill(pid, SIGSTOP);
  165. });
  166. 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&) {
  167. pid_t pid = process_table_view.selected_pid();
  168. if (pid != -1)
  169. kill(pid, SIGCONT);
  170. });
  171. auto menubar = GUI::MenuBar::construct();
  172. auto& app_menu = menubar->add_menu("System Monitor");
  173. app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  174. GUI::Application::the().quit(0);
  175. return;
  176. }));
  177. auto& process_menu = menubar->add_menu("Process");
  178. process_menu.add_action(kill_action);
  179. process_menu.add_action(stop_action);
  180. process_menu.add_action(continue_action);
  181. auto process_context_menu = GUI::Menu::construct();
  182. process_context_menu->add_action(kill_action);
  183. process_context_menu->add_action(stop_action);
  184. process_context_menu->add_action(continue_action);
  185. process_table_view.on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  186. (void)index;
  187. process_context_menu->popup(event.screen_position());
  188. };
  189. auto& frequency_menu = menubar->add_menu("Frequency");
  190. GUI::ActionGroup frequency_action_group;
  191. frequency_action_group.set_exclusive(true);
  192. auto make_frequency_action = [&](auto& title, int interval, bool checked = false) {
  193. auto action = GUI::Action::create_checkable(title, [&refresh_timer, interval](auto&) {
  194. refresh_timer.restart(interval);
  195. });
  196. action->set_checked(checked);
  197. frequency_action_group.add_action(*action);
  198. frequency_menu.add_action(*action);
  199. };
  200. make_frequency_action("0.25 sec", 250);
  201. make_frequency_action("0.5 sec", 500);
  202. make_frequency_action("1 sec", 1000, true);
  203. make_frequency_action("3 sec", 3000);
  204. make_frequency_action("5 sec", 5000);
  205. auto& help_menu = menubar->add_menu("Help");
  206. help_menu.add_action(GUI::Action::create("About", [&](const GUI::Action&) {
  207. GUI::AboutDialog::show("System Monitor", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-system-monitor.png"), window);
  208. }));
  209. app.set_menubar(move(menubar));
  210. auto& process_tab_unused_widget = process_container_splitter.add<UnavailableProcessWidget>("No process selected");
  211. process_tab_unused_widget.set_visible(true);
  212. auto& process_tab_widget = process_container_splitter.add<GUI::TabWidget>();
  213. process_tab_widget.set_visible(false);
  214. auto& memory_map_widget = process_tab_widget.add_tab<ProcessMemoryMapWidget>("Memory map");
  215. auto& open_files_widget = process_tab_widget.add_tab<ProcessFileDescriptorMapWidget>("Open files");
  216. auto& unveiled_paths_widget = process_tab_widget.add_tab<ProcessUnveiledPathsWidget>("Unveiled paths");
  217. auto& stacks_widget = process_tab_widget.add_tab<ProcessStacksWidget>("Stacks");
  218. process_table_view.on_process_selected = [&](pid_t pid) {
  219. if (!can_access_pid(pid)) {
  220. process_tab_widget.set_visible(false);
  221. process_tab_unused_widget.set_text("Process cannot be accessed");
  222. process_tab_unused_widget.set_visible(true);
  223. return;
  224. }
  225. process_tab_widget.set_visible(true);
  226. process_tab_unused_widget.set_visible(false);
  227. open_files_widget.set_pid(pid);
  228. stacks_widget.set_pid(pid);
  229. memory_map_widget.set_pid(pid);
  230. unveiled_paths_widget.set_pid(pid);
  231. };
  232. window->show();
  233. window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-system-monitor.png"));
  234. return app.exec();
  235. }
  236. class ProgressBarPaintingDelegate final : public GUI::TableCellPaintingDelegate {
  237. public:
  238. virtual ~ProgressBarPaintingDelegate() override {}
  239. virtual void paint(GUI::Painter& painter, const Gfx::Rect& a_rect, const Palette& palette, const GUI::Model& model, const GUI::ModelIndex& index) override
  240. {
  241. auto rect = a_rect.shrunken(2, 2);
  242. auto percentage = model.data(index, GUI::Model::Role::Custom).to_i32();
  243. auto data = model.data(index, GUI::Model::Role::Display);
  244. String text;
  245. if (data.is_string())
  246. text = data.as_string();
  247. Gfx::StylePainter::paint_progress_bar(painter, rect, palette, 0, 100, percentage, text);
  248. painter.draw_rect(rect, Color::Black);
  249. }
  250. };
  251. NonnullRefPtr<GUI::Widget> build_file_systems_tab()
  252. {
  253. auto fs_widget = GUI::LazyWidget::construct();
  254. fs_widget->on_first_show = [](GUI::LazyWidget& self) {
  255. self.set_layout<GUI::VerticalBoxLayout>();
  256. self.layout()->set_margins({ 4, 4, 4, 4 });
  257. auto& fs_table_view = self.add<GUI::TableView>();
  258. Vector<GUI::JsonArrayModel::FieldSpec> df_fields;
  259. df_fields.empend("mount_point", "Mount point", Gfx::TextAlignment::CenterLeft);
  260. df_fields.empend("class_name", "Class", Gfx::TextAlignment::CenterLeft);
  261. df_fields.empend("source", "Source", Gfx::TextAlignment::CenterLeft);
  262. df_fields.empend(
  263. "Size", Gfx::TextAlignment::CenterRight,
  264. [](const JsonObject& object) {
  265. StringBuilder size_builder;
  266. size_builder.append(" ");
  267. size_builder.append(human_readable_size(object.get("total_block_count").to_u32() * object.get("block_size").to_u32()));
  268. size_builder.append(" ");
  269. return size_builder.to_string();
  270. },
  271. [](const JsonObject& object) {
  272. return object.get("total_block_count").to_u32() * object.get("block_size").to_u32();
  273. },
  274. [](const JsonObject& object) {
  275. auto total_blocks = object.get("total_block_count").to_u32();
  276. if (total_blocks == 0)
  277. return 0;
  278. auto free_blocks = object.get("free_block_count").to_u32();
  279. auto used_blocks = total_blocks - free_blocks;
  280. int percentage = (int)((float)used_blocks / (float)total_blocks * 100.0f);
  281. return percentage;
  282. });
  283. df_fields.empend(
  284. "Used", Gfx::TextAlignment::CenterRight,
  285. [](const JsonObject& object) {
  286. auto total_blocks = object.get("total_block_count").to_u32();
  287. auto free_blocks = object.get("free_block_count").to_u32();
  288. auto used_blocks = total_blocks - free_blocks;
  289. return human_readable_size(used_blocks * object.get("block_size").to_u32()); },
  290. [](const JsonObject& object) {
  291. auto total_blocks = object.get("total_block_count").to_u32();
  292. auto free_blocks = object.get("free_block_count").to_u32();
  293. auto used_blocks = total_blocks - free_blocks;
  294. return used_blocks * object.get("block_size").to_u32();
  295. });
  296. df_fields.empend(
  297. "Available", Gfx::TextAlignment::CenterRight,
  298. [](const JsonObject& object) {
  299. return human_readable_size(object.get("free_block_count").to_u32() * object.get("block_size").to_u32());
  300. },
  301. [](const JsonObject& object) {
  302. return object.get("free_block_count").to_u32() * object.get("block_size").to_u32();
  303. });
  304. df_fields.empend("Access", Gfx::TextAlignment::CenterLeft, [](const JsonObject& object) {
  305. return object.get("readonly").to_bool() ? "Read-only" : "Read/Write";
  306. });
  307. df_fields.empend("Mount flags", Gfx::TextAlignment::CenterLeft, [](const JsonObject& object) {
  308. int mount_flags = object.get("mount_flags").to_int();
  309. StringBuilder builder;
  310. bool first = true;
  311. auto check = [&](int flag, const char* name) {
  312. if (!(mount_flags & flag))
  313. return;
  314. if (!first)
  315. builder.append(',');
  316. builder.append(name);
  317. first = false;
  318. };
  319. check(MS_NODEV, "nodev");
  320. check(MS_NOEXEC, "noexec");
  321. check(MS_NOSUID, "nosuid");
  322. check(MS_BIND, "bind");
  323. if (builder.string_view().is_empty())
  324. return String("defaults");
  325. return builder.to_string();
  326. });
  327. df_fields.empend("free_block_count", "Free blocks", Gfx::TextAlignment::CenterRight);
  328. df_fields.empend("total_block_count", "Total blocks", Gfx::TextAlignment::CenterRight);
  329. df_fields.empend("free_inode_count", "Free inodes", Gfx::TextAlignment::CenterRight);
  330. df_fields.empend("total_inode_count", "Total inodes", Gfx::TextAlignment::CenterRight);
  331. df_fields.empend("block_size", "Block size", Gfx::TextAlignment::CenterRight);
  332. fs_table_view.set_model(GUI::SortingProxyModel::create(GUI::JsonArrayModel::create("/proc/df", move(df_fields))));
  333. fs_table_view.set_cell_painting_delegate(3, make<ProgressBarPaintingDelegate>());
  334. fs_table_view.model()->update();
  335. };
  336. return fs_widget;
  337. }
  338. NonnullRefPtr<GUI::Widget> build_pci_devices_tab()
  339. {
  340. auto pci_widget = GUI::LazyWidget::construct();
  341. pci_widget->on_first_show = [](GUI::LazyWidget& self) {
  342. self.set_layout<GUI::VerticalBoxLayout>();
  343. self.layout()->set_margins({ 4, 4, 4, 4 });
  344. auto& pci_table_view = self.add<GUI::TableView>();
  345. auto db = PCIDB::Database::open();
  346. Vector<GUI::JsonArrayModel::FieldSpec> pci_fields;
  347. pci_fields.empend(
  348. "Address", Gfx::TextAlignment::CenterLeft,
  349. [](const JsonObject& object) {
  350. auto seg = object.get("seg").to_u32();
  351. auto bus = object.get("bus").to_u32();
  352. auto slot = object.get("slot").to_u32();
  353. auto function = object.get("function").to_u32();
  354. return String::format("%04x:%02x:%02x.%d", seg, bus, slot, function);
  355. });
  356. pci_fields.empend(
  357. "Class", Gfx::TextAlignment::CenterLeft,
  358. [db](const JsonObject& object) {
  359. auto class_id = object.get("class").to_u32();
  360. String class_name = db->get_class(class_id);
  361. return class_name == "" ? String::format("%04x", class_id) : class_name;
  362. });
  363. pci_fields.empend(
  364. "Vendor", Gfx::TextAlignment::CenterLeft,
  365. [db](const JsonObject& object) {
  366. auto vendor_id = object.get("vendor_id").to_u32();
  367. String vendor_name = db->get_vendor(vendor_id);
  368. return vendor_name == "" ? String::format("%02x", vendor_id) : vendor_name;
  369. });
  370. pci_fields.empend(
  371. "Device", Gfx::TextAlignment::CenterLeft,
  372. [db](const JsonObject& object) {
  373. auto vendor_id = object.get("vendor_id").to_u32();
  374. auto device_id = object.get("device_id").to_u32();
  375. String device_name = db->get_device(vendor_id, device_id);
  376. return device_name == "" ? String::format("%02x", device_id) : device_name;
  377. });
  378. pci_fields.empend(
  379. "Revision", Gfx::TextAlignment::CenterRight,
  380. [](const JsonObject& object) {
  381. auto revision_id = object.get("revision_id").to_u32();
  382. return String::format("%02x", revision_id);
  383. });
  384. pci_table_view.set_model(GUI::SortingProxyModel::create(GUI::JsonArrayModel::create("/proc/pci", move(pci_fields))));
  385. pci_table_view.model()->update();
  386. };
  387. return pci_widget;
  388. }
  389. NonnullRefPtr<GUI::Widget> build_devices_tab()
  390. {
  391. auto devices_widget = GUI::LazyWidget::construct();
  392. devices_widget->on_first_show = [](GUI::LazyWidget& self) {
  393. self.set_layout<GUI::VerticalBoxLayout>();
  394. self.layout()->set_margins({ 4, 4, 4, 4 });
  395. auto& devices_table_view = self.add<GUI::TableView>();
  396. devices_table_view.set_model(GUI::SortingProxyModel::create(DevicesModel::create()));
  397. devices_table_view.model()->update();
  398. };
  399. return devices_widget;
  400. }
  401. NonnullRefPtr<GUI::Widget> build_graphs_tab()
  402. {
  403. auto graphs_container = GUI::LazyWidget::construct();
  404. graphs_container->on_first_show = [](GUI::LazyWidget& self) {
  405. self.set_fill_with_background_color(true);
  406. self.set_background_role(ColorRole::Button);
  407. self.set_layout<GUI::VerticalBoxLayout>();
  408. self.layout()->set_margins({ 4, 4, 4, 4 });
  409. auto& cpu_graph_group_box = self.add<GUI::GroupBox>("CPU usage");
  410. cpu_graph_group_box.set_layout<GUI::VerticalBoxLayout>();
  411. cpu_graph_group_box.layout()->set_margins({ 6, 16, 6, 6 });
  412. cpu_graph_group_box.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  413. cpu_graph_group_box.set_preferred_size(0, 120);
  414. auto& cpu_graph = cpu_graph_group_box.add<GraphWidget>();
  415. cpu_graph.set_max(100);
  416. cpu_graph.set_text_color(Color::Green);
  417. cpu_graph.set_graph_color(Color::from_rgb(0x00bb00));
  418. cpu_graph.text_formatter = [](int value, int) {
  419. return String::format("%d%%", value);
  420. };
  421. ProcessModel::the().on_new_cpu_data_point = [graph = &cpu_graph](float cpu_percent) {
  422. graph->add_value(cpu_percent);
  423. };
  424. auto& memory_graph_group_box = self.add<GUI::GroupBox>("Memory usage");
  425. memory_graph_group_box.set_layout<GUI::VerticalBoxLayout>();
  426. memory_graph_group_box.layout()->set_margins({ 6, 16, 6, 6 });
  427. memory_graph_group_box.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  428. memory_graph_group_box.set_preferred_size(0, 120);
  429. auto& memory_graph = memory_graph_group_box.add<GraphWidget>();
  430. memory_graph.set_text_color(Color::Cyan);
  431. memory_graph.set_graph_color(Color::from_rgb(0x00bbbb));
  432. memory_graph.text_formatter = [](int value, int max) {
  433. return String::format("%d / %d KB", value, max);
  434. };
  435. self.add<MemoryStatsWidget>(memory_graph);
  436. };
  437. return graphs_container;
  438. }