TreeMapWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. * Copyright (c) 2021-2022, the SerenityOS developers.
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "TreeMapWidget.h"
  8. #include "Tree.h"
  9. #include <AK/Array.h>
  10. #include <AK/DeprecatedString.h>
  11. #include <AK/NumberFormat.h>
  12. #include <LibGUI/ConnectionToWindowServer.h>
  13. #include <LibGUI/Painter.h>
  14. #include <LibGfx/Font/Font.h>
  15. #include <WindowServer/WindowManager.h>
  16. REGISTER_WIDGET(SpaceAnalyzer, TreeMapWidget)
  17. namespace SpaceAnalyzer {
  18. static constexpr Array colors = {
  19. Color(253, 231, 37),
  20. Color(148, 216, 64),
  21. Color(60, 188, 117),
  22. Color(31, 150, 139),
  23. Color(45, 112, 142),
  24. Color(63, 71, 136),
  25. Color(85, 121, 104),
  26. };
  27. static float get_normalized_aspect_ratio(float a, float b)
  28. {
  29. if (a < b) {
  30. return a / b;
  31. } else {
  32. return b / a;
  33. }
  34. }
  35. static bool node_is_leaf(TreeNode const& node)
  36. {
  37. return node.num_children() == 0;
  38. }
  39. bool TreeMapWidget::rect_can_contain_label(Gfx::IntRect const& rect) const
  40. {
  41. return rect.height() >= font().presentation_size() && rect.width() > 20;
  42. }
  43. void TreeMapWidget::paint_cell_frame(GUI::Painter& painter, TreeNode const& node, Gfx::IntRect const& cell_rect, Gfx::IntRect const& inner_rect, int depth, HasLabel has_label) const
  44. {
  45. if (cell_rect.width() <= 2 || cell_rect.height() <= 2) {
  46. painter.fill_rect(cell_rect, Color::Black);
  47. return;
  48. }
  49. Gfx::IntRect remainder = cell_rect;
  50. Color color = colors[depth % (sizeof(colors) / sizeof(colors[0]))];
  51. if (m_selected_node_cache == &node) {
  52. color = color.darkened(0.8f);
  53. }
  54. // Draw borders.
  55. painter.fill_rect(remainder.take_from_right(1), Color::Black);
  56. painter.fill_rect(remainder.take_from_bottom(1), Color::Black);
  57. // Draw highlights.
  58. painter.fill_rect(remainder.take_from_right(1), color.darkened());
  59. painter.fill_rect(remainder.take_from_bottom(1), color.darkened());
  60. painter.fill_rect(remainder.take_from_top(1), color.lightened());
  61. painter.fill_rect(remainder.take_from_left(1), color.lightened());
  62. // Paint the background.
  63. if (inner_rect.is_empty()) {
  64. painter.fill_rect(remainder, color);
  65. } else {
  66. // Draw black edges above and to the left of the inner_rect.
  67. Gfx::IntRect border_rect = inner_rect.inflated(2, 2);
  68. Gfx::IntRect hammer_rect = border_rect;
  69. hammer_rect.set_width(hammer_rect.width() - 1);
  70. hammer_rect.set_height(hammer_rect.height() - 1);
  71. painter.fill_rect(border_rect.take_from_top(1), Color::Black);
  72. painter.fill_rect(border_rect.take_from_left(1), Color::Black);
  73. for (auto& shard : remainder.shatter(hammer_rect)) {
  74. painter.fill_rect(shard, color);
  75. }
  76. }
  77. // Paint text.
  78. if (has_label == HasLabel::Yes) {
  79. Gfx::IntRect text_rect = remainder;
  80. text_rect.shrink(4, 4);
  81. painter.clear_clip_rect();
  82. painter.add_clip_rect(text_rect);
  83. if (node_is_leaf(node)) {
  84. painter.draw_text(text_rect, node.name(), font(), Gfx::TextAlignment::TopLeft, Color::Black);
  85. text_rect.take_from_top(font().presentation_size() + 1);
  86. painter.draw_text(text_rect, human_readable_size(node.area()), font(), Gfx::TextAlignment::TopLeft, Color::Black);
  87. } else {
  88. painter.draw_text(text_rect, DeprecatedString::formatted("{} - {}", node.name(), human_readable_size(node.area())), font(), Gfx::TextAlignment::TopLeft, Color::Black);
  89. }
  90. painter.clear_clip_rect();
  91. }
  92. }
  93. template<typename Function>
  94. void TreeMapWidget::lay_out_children(TreeNode const& node, Gfx::IntRect const& rect, int depth, Function callback)
  95. {
  96. if (node.num_children() == 0) {
  97. return;
  98. }
  99. // Check if the children are sorted yet, if not do that now.
  100. for (size_t k = 0; k < node.num_children() - 1; k++) {
  101. if (node.child_at(k).area() < node.child_at(k + 1).area()) {
  102. node.sort_children_by_area();
  103. break;
  104. }
  105. }
  106. i64 total_area = node.area();
  107. Gfx::IntRect canvas = rect;
  108. bool remaining_nodes_are_too_small = false;
  109. for (size_t i = 0; !remaining_nodes_are_too_small && i < node.num_children(); i++) {
  110. const i64 i_node_area = node.child_at(i).area();
  111. if (i_node_area == 0)
  112. break;
  113. const size_t long_side_size = max(canvas.width(), canvas.height());
  114. const size_t short_side_size = min(canvas.width(), canvas.height());
  115. size_t row_or_column_size = long_side_size * i_node_area / total_area;
  116. i64 node_area_sum = i_node_area;
  117. size_t k = i + 1;
  118. // Try to add nodes to this row or column so long as the worst aspect ratio of
  119. // the new set of nodes is better than the worst aspect ratio of the current set.
  120. {
  121. float best_worst_aspect_ratio_so_far = get_normalized_aspect_ratio(row_or_column_size, short_side_size);
  122. for (; k < node.num_children(); k++) {
  123. // Do a preliminary calculation of the worst aspect ratio of the nodes at index i and k
  124. // if that aspect ratio is better than the 'best_worst_aspect_ratio_so_far' we keep it,
  125. // otherwise it is discarded.
  126. i64 k_node_area = node.child_at(k).area();
  127. if (k_node_area == 0) {
  128. break;
  129. }
  130. i64 new_node_area_sum = node_area_sum + k_node_area;
  131. size_t new_row_or_column_size = long_side_size * new_node_area_sum / total_area;
  132. size_t i_node_size = short_side_size * i_node_area / new_node_area_sum;
  133. size_t k_node_size = short_side_size * k_node_area / new_node_area_sum;
  134. float i_node_aspect_ratio = get_normalized_aspect_ratio(new_row_or_column_size, i_node_size);
  135. float k_node_aspect_ratio = get_normalized_aspect_ratio(new_row_or_column_size, k_node_size);
  136. float new_worst_aspect_ratio = min(i_node_aspect_ratio, k_node_aspect_ratio);
  137. if (new_worst_aspect_ratio < best_worst_aspect_ratio_so_far) {
  138. break;
  139. }
  140. best_worst_aspect_ratio_so_far = new_worst_aspect_ratio;
  141. node_area_sum = new_node_area_sum;
  142. row_or_column_size = new_row_or_column_size;
  143. }
  144. }
  145. // Paint the elements from 'i' up to and including 'k-1'.
  146. {
  147. const size_t fixed_side_size = row_or_column_size;
  148. i64 placement_area = node_area_sum;
  149. size_t main_dim = short_side_size;
  150. // Lay out nodes in a row or column.
  151. Orientation orientation = canvas.width() > canvas.height() ? Orientation::Horizontal : Orientation::Vertical;
  152. Gfx::IntRect layout_rect = canvas;
  153. layout_rect.set_primary_size_for_orientation(orientation, fixed_side_size);
  154. for (size_t q = i; q < k; q++) {
  155. auto& child = node.child_at(q);
  156. size_t node_size = main_dim * child.area() / placement_area;
  157. Gfx::IntRect cell_rect = layout_rect;
  158. cell_rect.set_secondary_size_for_orientation(orientation, node_size);
  159. Gfx::IntRect inner_rect;
  160. HasLabel has_label = HasLabel::No;
  161. if (child.num_children() != 0 && rect.height() >= 8 && rect.width() >= 8) {
  162. inner_rect = cell_rect;
  163. inner_rect.shrink(4, 4); // border and shading
  164. if (rect_can_contain_label(inner_rect)) {
  165. int const margin = 5;
  166. has_label = HasLabel::Yes;
  167. inner_rect.set_y(inner_rect.y() + font().presentation_size() + margin);
  168. inner_rect.set_height(inner_rect.height() - (font().presentation_size() + margin * 2));
  169. inner_rect.set_x(inner_rect.x() + margin);
  170. inner_rect.set_width(inner_rect.width() - margin * 2);
  171. }
  172. } else if (rect_can_contain_label(cell_rect)) {
  173. has_label = HasLabel::Yes;
  174. }
  175. callback(child, q, cell_rect, inner_rect, depth, has_label, IsRemainder::No);
  176. if (cell_rect.width() * cell_rect.height() < 16) {
  177. remaining_nodes_are_too_small = true;
  178. } else if (!inner_rect.is_empty()) {
  179. lay_out_children(child, inner_rect, depth + 1, callback);
  180. }
  181. layout_rect.set_secondary_offset_for_orientation(orientation, layout_rect.secondary_offset_for_orientation(orientation) + node_size);
  182. main_dim -= node_size;
  183. placement_area -= child.area();
  184. }
  185. canvas.set_primary_offset_for_orientation(orientation, canvas.primary_offset_for_orientation(orientation) + fixed_side_size);
  186. canvas.set_primary_size_for_orientation(orientation, canvas.primary_size_for_orientation(orientation) - fixed_side_size);
  187. }
  188. // Consume nodes that were added to this row or column.
  189. i = k - 1;
  190. total_area -= node_area_sum;
  191. }
  192. // If not the entire canvas was filled with nodes, fill the remaining area with a dither pattern.
  193. if (!canvas.is_empty()) {
  194. callback(node, 0, canvas, Gfx::IntRect(), depth, HasLabel::No, IsRemainder::Yes);
  195. }
  196. }
  197. TreeNode const* TreeMapWidget::path_node(size_t n) const
  198. {
  199. if (!m_tree.ptr())
  200. return nullptr;
  201. TreeNode const* iter = &m_tree->root();
  202. size_t path_index = 0;
  203. while (iter && path_index < m_path.size() && path_index < n) {
  204. auto child_name = m_path[path_index];
  205. auto maybe_child = iter->child_with_name(child_name);
  206. if (!maybe_child.has_value())
  207. return nullptr;
  208. iter = &maybe_child.release_value();
  209. path_index++;
  210. }
  211. return iter;
  212. }
  213. void TreeMapWidget::paint_event(GUI::PaintEvent& event)
  214. {
  215. GUI::Frame::paint_event(event);
  216. GUI::Painter painter(*this);
  217. m_selected_node_cache = path_node(m_path.size());
  218. TreeNode const* node = path_node(m_viewpoint);
  219. if (!node) {
  220. painter.fill_rect(frame_inner_rect(), Color::MidGray);
  221. } else if (node_is_leaf(*node)) {
  222. paint_cell_frame(painter, *node, frame_inner_rect(), Gfx::IntRect(), m_viewpoint - 1, HasLabel::Yes);
  223. } else {
  224. lay_out_children(*node, frame_inner_rect(), m_viewpoint, [&](TreeNode const& node, int, Gfx::IntRect const& rect, Gfx::IntRect const& inner_rect, int depth, HasLabel has_label, IsRemainder remainder) {
  225. if (remainder == IsRemainder::No) {
  226. paint_cell_frame(painter, node, rect, inner_rect, depth, has_label);
  227. } else {
  228. Color color = colors[depth % (sizeof(colors) / sizeof(colors[0]))];
  229. Gfx::IntRect dither_rect = rect;
  230. painter.fill_rect(dither_rect.take_from_right(1), Color::Black);
  231. painter.fill_rect(dither_rect.take_from_bottom(1), Color::Black);
  232. painter.fill_rect_with_dither_pattern(dither_rect, color, Color::Black);
  233. }
  234. });
  235. }
  236. }
  237. Vector<DeprecatedString> TreeMapWidget::path_to_position(Gfx::IntPoint position)
  238. {
  239. TreeNode const* node = path_node(m_viewpoint);
  240. if (!node) {
  241. return {};
  242. }
  243. Vector<DeprecatedString> path;
  244. lay_out_children(*node, frame_inner_rect(), m_viewpoint, [&](TreeNode const& node, int, Gfx::IntRect const& rect, Gfx::IntRect const&, int, HasLabel, IsRemainder is_remainder) {
  245. if (is_remainder == IsRemainder::No && rect.contains(position)) {
  246. path.append(node.name());
  247. }
  248. });
  249. return path;
  250. }
  251. void TreeMapWidget::mousemove_event(GUI::MouseEvent& event)
  252. {
  253. auto* node = path_node(m_viewpoint);
  254. if (!node) {
  255. set_tooltip({});
  256. return;
  257. }
  258. auto* hovered_node = node;
  259. lay_out_children(*node, frame_inner_rect(), m_viewpoint, [&](TreeNode const&, int index, Gfx::IntRect const& rect, Gfx::IntRect const&, int, HasLabel, IsRemainder is_remainder) {
  260. if (is_remainder == IsRemainder::No && rect.contains(event.position())) {
  261. hovered_node = &hovered_node->child_at(index);
  262. }
  263. });
  264. set_tooltip(DeprecatedString::formatted("{}\n{}", hovered_node->name(), human_readable_size(hovered_node->area())));
  265. }
  266. void TreeMapWidget::mousedown_event(GUI::MouseEvent& event)
  267. {
  268. TreeNode const* node = path_node(m_viewpoint);
  269. if (node && !node_is_leaf(*node)) {
  270. auto path = path_to_position(event.position());
  271. if (!path.is_empty()) {
  272. m_path.shrink(m_viewpoint);
  273. m_path.extend(path);
  274. if (on_path_change) {
  275. on_path_change();
  276. }
  277. update();
  278. }
  279. }
  280. }
  281. void TreeMapWidget::doubleclick_event(GUI::MouseEvent& event)
  282. {
  283. if (event.button() != GUI::MouseButton::Primary)
  284. return;
  285. TreeNode const* node = path_node(m_viewpoint);
  286. if (node && !node_is_leaf(*node)) {
  287. auto path = path_to_position(event.position());
  288. m_path.shrink(m_viewpoint);
  289. m_path.extend(path);
  290. m_viewpoint = m_path.size();
  291. if (on_path_change) {
  292. on_path_change();
  293. }
  294. update();
  295. }
  296. }
  297. void TreeMapWidget::keydown_event(GUI::KeyEvent& event)
  298. {
  299. if (event.key() == KeyCode::Key_Left)
  300. set_viewpoint(m_viewpoint == 0 ? m_path.size() : m_viewpoint - 1);
  301. else if (event.key() == KeyCode::Key_Right)
  302. set_viewpoint(m_viewpoint == m_path.size() ? 0 : m_viewpoint + 1);
  303. else
  304. event.ignore();
  305. }
  306. void TreeMapWidget::mousewheel_event(GUI::MouseEvent& event)
  307. {
  308. int delta = event.wheel_raw_delta_y();
  309. if (delta > 0) {
  310. size_t step_back = delta;
  311. if (step_back > m_viewpoint)
  312. step_back = m_viewpoint;
  313. set_viewpoint(m_viewpoint - step_back);
  314. } else {
  315. size_t step_up = -delta;
  316. set_viewpoint(m_viewpoint + step_up);
  317. }
  318. }
  319. void TreeMapWidget::context_menu_event(GUI::ContextMenuEvent& context_menu_event)
  320. {
  321. if (on_context_menu_request)
  322. on_context_menu_request(context_menu_event);
  323. }
  324. void TreeMapWidget::recalculate_path_for_new_tree()
  325. {
  326. TreeNode const* current = &m_tree->root();
  327. size_t new_path_length = 0;
  328. for (auto& segment : m_path) {
  329. auto maybe_child = current->child_with_name(segment);
  330. if (!maybe_child.has_value())
  331. break;
  332. new_path_length++;
  333. current = &maybe_child.release_value();
  334. }
  335. m_path.shrink(new_path_length);
  336. if (new_path_length < m_viewpoint)
  337. m_viewpoint = new_path_length - 1;
  338. }
  339. void TreeMapWidget::set_tree(RefPtr<Tree> tree)
  340. {
  341. m_tree = tree;
  342. recalculate_path_for_new_tree();
  343. if (on_path_change) {
  344. on_path_change();
  345. }
  346. update();
  347. }
  348. void TreeMapWidget::set_viewpoint(size_t viewpoint)
  349. {
  350. if (m_viewpoint == viewpoint)
  351. return;
  352. if (viewpoint > m_path.size())
  353. viewpoint = m_path.size();
  354. m_viewpoint = viewpoint;
  355. if (on_path_change) {
  356. on_path_change();
  357. }
  358. update();
  359. }
  360. size_t TreeMapWidget::path_size() const
  361. {
  362. return m_path.size() + 1;
  363. }
  364. size_t TreeMapWidget::viewpoint() const
  365. {
  366. return m_viewpoint;
  367. }
  368. }