main.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/CircularQueue.h>
  29. #include <AK/JsonObject.h>
  30. #include <LibCore/ArgsParser.h>
  31. #include <LibCore/File.h>
  32. #include <LibCore/ProcessStatisticsReader.h>
  33. #include <LibGUI/Application.h>
  34. #include <LibGUI/Frame.h>
  35. #include <LibGUI/Painter.h>
  36. #include <LibGUI/Window.h>
  37. #include <LibGfx/Palette.h>
  38. #include <serenity.h>
  39. #include <spawn.h>
  40. #include <stdio.h>
  41. enum class GraphType {
  42. CPU,
  43. Memory,
  44. };
  45. class GraphWidget final : public GUI::Frame {
  46. C_OBJECT(GraphWidget);
  47. public:
  48. static constexpr size_t history_size = 30;
  49. GraphWidget(GraphType graph_type, Optional<Gfx::Color> graph_color, Optional<Gfx::Color> graph_error_color)
  50. : m_graph_type(graph_type)
  51. {
  52. set_frame_thickness(1);
  53. m_graph_color = graph_color.value_or(palette().menu_selection());
  54. m_graph_error_color = graph_error_color.value_or(Color::Red);
  55. start_timer(1000);
  56. }
  57. private:
  58. virtual void timer_event(Core::TimerEvent&) override
  59. {
  60. switch (m_graph_type) {
  61. case GraphType::CPU: {
  62. unsigned busy;
  63. unsigned idle;
  64. if (get_cpu_usage(busy, idle)) {
  65. unsigned busy_diff = busy - m_last_cpu_busy;
  66. unsigned idle_diff = idle - m_last_cpu_idle;
  67. m_last_cpu_busy = busy;
  68. m_last_cpu_idle = idle;
  69. float cpu = (float)busy_diff / (float)(busy_diff + idle_diff);
  70. m_history.enqueue(cpu);
  71. m_tooltip = String::format("CPU usage: %.1f%%", 100 * cpu);
  72. } else {
  73. m_history.enqueue(-1);
  74. m_tooltip = StringView("Unable to determine CPU usage");
  75. }
  76. break;
  77. }
  78. case GraphType::Memory: {
  79. unsigned allocated;
  80. unsigned available;
  81. if (get_memory_usage(allocated, available)) {
  82. float total_memory = allocated + available;
  83. float memory = (float)allocated / total_memory;
  84. m_history.enqueue(memory);
  85. m_tooltip = String::format("Memory: %.1f MiB of %.1f MiB in use", (float)allocated / MiB, total_memory / MiB);
  86. } else {
  87. m_history.enqueue(-1);
  88. m_tooltip = StringView("Unable to determine memory usage");
  89. }
  90. break;
  91. }
  92. default:
  93. ASSERT_NOT_REACHED();
  94. }
  95. set_tooltip(m_tooltip);
  96. update();
  97. }
  98. virtual void paint_event(GUI::PaintEvent& event) override
  99. {
  100. GUI::Frame::paint_event(event);
  101. GUI::Painter painter(*this);
  102. painter.add_clip_rect(event.rect());
  103. painter.add_clip_rect(frame_inner_rect());
  104. painter.fill_rect(event.rect(), Color::Black);
  105. int i = m_history.capacity() - m_history.size();
  106. auto rect = frame_inner_rect();
  107. for (auto value : m_history) {
  108. if (value >= 0) {
  109. painter.draw_line(
  110. { rect.x() + i, rect.bottom() },
  111. { rect.x() + i, rect.top() + (int)(round(rect.height() - (value * rect.height()))) },
  112. m_graph_color);
  113. } else {
  114. painter.draw_line(
  115. { rect.x() + i, rect.top() },
  116. { rect.x() + i, rect.bottom() },
  117. m_graph_error_color);
  118. }
  119. ++i;
  120. }
  121. }
  122. virtual void mousedown_event(GUI::MouseEvent& event) override
  123. {
  124. if (event.button() != GUI::MouseButton::Left)
  125. return;
  126. pid_t child_pid;
  127. const char* argv[] = { "SystemMonitor", nullptr };
  128. if ((errno = posix_spawn(&child_pid, "/bin/SystemMonitor", nullptr, nullptr, const_cast<char**>(argv), environ))) {
  129. perror("posix_spawn");
  130. } else {
  131. if (disown(child_pid) < 0)
  132. perror("disown");
  133. }
  134. }
  135. static bool get_cpu_usage(unsigned& busy, unsigned& idle)
  136. {
  137. busy = 0;
  138. idle = 0;
  139. auto all_processes = Core::ProcessStatisticsReader::get_all();
  140. if (all_processes.is_empty())
  141. return false;
  142. for (auto& it : all_processes) {
  143. for (auto& jt : it.value.threads) {
  144. if (it.value.pid == 0)
  145. idle += jt.ticks_user + jt.ticks_kernel;
  146. else
  147. busy += jt.ticks_user + jt.ticks_kernel;
  148. }
  149. }
  150. return true;
  151. }
  152. static bool get_memory_usage(unsigned& allocated, unsigned& available)
  153. {
  154. auto proc_memstat = Core::File::construct("/proc/memstat");
  155. if (!proc_memstat->open(Core::IODevice::OpenMode::ReadOnly))
  156. return false;
  157. auto file_contents = proc_memstat->read_all();
  158. auto json = JsonValue::from_string(file_contents);
  159. ASSERT(json.has_value());
  160. unsigned user_physical_allocated = json.value().as_object().get("user_physical_allocated").to_u32();
  161. unsigned user_physical_available = json.value().as_object().get("user_physical_available").to_u32();
  162. allocated = (user_physical_allocated * PAGE_SIZE);
  163. available = (user_physical_available * PAGE_SIZE);
  164. return true;
  165. }
  166. GraphType m_graph_type;
  167. Gfx::Color m_graph_color;
  168. Gfx::Color m_graph_error_color;
  169. CircularQueue<float, history_size> m_history;
  170. unsigned m_last_cpu_busy { 0 };
  171. unsigned m_last_cpu_idle { 0 };
  172. String m_tooltip;
  173. };
  174. int main(int argc, char** argv)
  175. {
  176. if (pledge("stdio shared_buffer accept proc exec rpath unix cpath fattr", nullptr) < 0) {
  177. perror("pledge");
  178. return 1;
  179. }
  180. auto app = GUI::Application::construct(argc, argv);
  181. if (pledge("stdio shared_buffer accept proc exec rpath", nullptr) < 0) {
  182. perror("pledge");
  183. return 1;
  184. }
  185. bool cpu = false;
  186. bool memory = false;
  187. const char* name = nullptr;
  188. const char* color = nullptr;
  189. const char* error_color = nullptr;
  190. Core::ArgsParser args_parser;
  191. args_parser.add_option(cpu, "Show CPU usage", "cpu", 'C');
  192. args_parser.add_option(memory, "Show memory usage", "memory", 'M');
  193. args_parser.add_option(name, "Applet name used by WindowServer.ini to set the applet order", "name", 'n', "name");
  194. args_parser.add_option(color, "Graph color", "color", 'c', "color");
  195. args_parser.add_option(error_color, "Graph color (error)", "error-color", 'e', "error-color");
  196. args_parser.parse(argc, argv);
  197. if (!cpu && !memory) {
  198. printf("Either --cpu or --memory option must be used");
  199. return 1;
  200. }
  201. if (cpu && memory) {
  202. printf("--cpu and --memory options must not be used together");
  203. return 1;
  204. }
  205. GraphType graph_type;
  206. if (cpu)
  207. graph_type = GraphType::CPU;
  208. if (memory)
  209. graph_type = GraphType::Memory;
  210. if (name == nullptr)
  211. name = "ResourceGraph";
  212. Optional<Gfx::Color> graph_color, graph_error_color;
  213. if (color != nullptr)
  214. graph_color = Gfx::Color::from_string(color);
  215. if (error_color != nullptr)
  216. graph_error_color = Gfx::Color::from_string(error_color);
  217. auto window = GUI::Window::construct();
  218. window->set_title(name);
  219. window->set_window_type(GUI::WindowType::MenuApplet);
  220. window->resize(GraphWidget::history_size + 2, 16);
  221. window->set_main_widget<GraphWidget>(graph_type, graph_color, graph_error_color);
  222. window->show();
  223. if (unveil("/res", "r") < 0) {
  224. perror("unveil");
  225. return 1;
  226. }
  227. // FIXME: This is required by Core::ProcessStatisticsReader.
  228. // It would be good if we didn't depend on that.
  229. if (unveil("/etc/passwd", "r") < 0) {
  230. perror("unveil");
  231. return 1;
  232. }
  233. if (unveil("/proc/all", "r") < 0) {
  234. perror("unveil");
  235. return 1;
  236. }
  237. if (unveil("/proc/memstat", "r") < 0) {
  238. perror("unveil");
  239. return 1;
  240. }
  241. if (unveil("/bin/SystemMonitor", "x") < 0) {
  242. perror("unveil");
  243. return 1;
  244. }
  245. unveil(nullptr, nullptr);
  246. return app->exec();
  247. }