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 <LibGUI/Model.h>
28#include <LibGUI/Painter.h>
29#include <LibGUI/ScrollBar.h>
30#include <LibGUI/TreeView.h>
31#include <LibGfx/Bitmap.h>
32#include <LibGfx/Palette.h>
33
34//#define DEBUG_ITEM_RECTS
35
36namespace GUI {
37
38struct TreeView::MetadataForIndex {
39 bool open { false };
40};
41
42TreeView::MetadataForIndex& TreeView::ensure_metadata_for_index(const ModelIndex& index) const
43{
44 ASSERT(index.is_valid());
45 auto it = m_view_metadata.find(index.internal_data());
46 if (it != m_view_metadata.end())
47 return *it->value;
48 auto new_metadata = make<MetadataForIndex>();
49 auto& new_metadata_ref = *new_metadata;
50 m_view_metadata.set(index.internal_data(), move(new_metadata));
51 return new_metadata_ref;
52}
53
54TreeView::TreeView()
55{
56 set_background_role(ColorRole::Base);
57 set_foreground_role(ColorRole::BaseText);
58 set_size_columns_to_fit_content(true);
59 set_headers_visible(false);
60 m_expand_bitmap = Gfx::Bitmap::load_from_file("/res/icons/treeview-expand.png");
61 m_collapse_bitmap = Gfx::Bitmap::load_from_file("/res/icons/treeview-collapse.png");
62}
63
64TreeView::~TreeView()
65{
66}
67
68ModelIndex TreeView::index_at_event_position(const Gfx::Point& a_position, bool& is_toggle) const
69{
70 auto position = a_position.translated(0, -header_height()).translated(horizontal_scrollbar().value() - frame_thickness(), vertical_scrollbar().value() - frame_thickness());
71 is_toggle = false;
72 if (!model())
73 return {};
74 ModelIndex result;
75 traverse_in_paint_order([&](const ModelIndex& index, const Gfx::Rect& rect, const Gfx::Rect& toggle_rect, int) {
76 if (toggle_rect.contains(position)) {
77 result = index;
78 is_toggle = true;
79 return IterationDecision::Break;
80 }
81 if (rect.contains_vertically(position.y())) {
82 result = index;
83 return IterationDecision::Break;
84 }
85 return IterationDecision::Continue;
86 });
87 return result;
88}
89
90void TreeView::doubleclick_event(MouseEvent& event)
91{
92 if (!model())
93 return;
94 auto& model = *this->model();
95 bool is_toggle;
96 auto index = index_at_event_position(event.position(), is_toggle);
97 if (!index.is_valid())
98 return;
99
100 if (event.button() == MouseButton::Left) {
101 if (selection().first() != index)
102 selection().set(index);
103
104 if (model.row_count(index))
105 toggle_index(index);
106 else
107 activate(index);
108 }
109}
110
111void TreeView::toggle_index(const ModelIndex& index)
112{
113 ASSERT(model()->row_count(index));
114 auto& metadata = ensure_metadata_for_index(index);
115 metadata.open = !metadata.open;
116 update_column_sizes();
117 update_content_size();
118 update();
119}
120
121template<typename Callback>
122void TreeView::traverse_in_paint_order(Callback callback) const
123{
124 ASSERT(model());
125 auto& model = *this->model();
126 int indent_level = 1;
127 int y_offset = 0;
128 int tree_column_x_offset = this->tree_column_x_offset();
129
130 Function<IterationDecision(const ModelIndex&)> traverse_index = [&](const ModelIndex& index) {
131 int row_count_at_index = model.row_count(index);
132 if (index.is_valid()) {
133 auto& metadata = ensure_metadata_for_index(index);
134 int x_offset = tree_column_x_offset + horizontal_padding() + indent_level * indent_width_in_pixels();
135 auto node_text = model.data(index, Model::Role::Display).to_string();
136 Gfx::Rect rect = {
137 x_offset, y_offset,
138 icon_size() + icon_spacing() + text_padding() + font().width(node_text) + text_padding(), item_height()
139 };
140 Gfx::Rect toggle_rect;
141 if (row_count_at_index > 0) {
142 int toggle_x = tree_column_x_offset + horizontal_padding() + (indent_width_in_pixels() * indent_level) - (icon_size() / 2) - 4;
143 toggle_rect = { toggle_x, rect.y(), toggle_size(), toggle_size() };
144 toggle_rect.center_vertically_within(rect);
145 }
146 if (callback(index, rect, toggle_rect, indent_level) == IterationDecision::Break)
147 return IterationDecision::Break;
148 y_offset += item_height();
149 // NOTE: Skip traversing children if this index is closed!
150 if (!metadata.open)
151 return IterationDecision::Continue;
152 }
153
154 ++indent_level;
155 int row_count = model.row_count(index);
156 for (int i = 0; i < row_count; ++i) {
157 if (traverse_index(model.index(i, model.tree_column(), index)) == IterationDecision::Break)
158 return IterationDecision::Break;
159 }
160 --indent_level;
161 return IterationDecision::Continue;
162 };
163 int root_count = model.row_count();
164 for (int root_index = 0; root_index < root_count; ++root_index) {
165 if (traverse_index(model.index(root_index, model.tree_column(), ModelIndex())) == IterationDecision::Break)
166 break;
167 }
168}
169
170void TreeView::paint_event(PaintEvent& event)
171{
172 Frame::paint_event(event);
173 Painter painter(*this);
174 painter.add_clip_rect(frame_inner_rect());
175 painter.add_clip_rect(event.rect());
176 painter.fill_rect(event.rect(), palette().color(background_role()));
177
178 if (!model())
179 return;
180 auto& model = *this->model();
181
182 painter.translate(frame_inner_rect().location());
183 painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
184
185 auto visible_content_rect = this->visible_content_rect();
186 int tree_column = model.tree_column();
187 int tree_column_x_offset = this->tree_column_x_offset();
188
189 int y_offset = header_height();
190
191 int painted_row_index = 0;
192
193 traverse_in_paint_order([&](const ModelIndex& index, const Gfx::Rect& a_rect, const Gfx::Rect& a_toggle_rect, int indent_level) {
194 if (!a_rect.intersects_vertically(visible_content_rect))
195 return IterationDecision::Continue;
196
197 auto rect = a_rect.translated(0, y_offset);
198 auto toggle_rect = a_toggle_rect.translated(0, y_offset);
199
200#ifdef DEBUG_ITEM_RECTS
201 painter.fill_rect(rect, Color::WarmGray);
202#endif
203
204 bool is_selected_row = selection().contains(index);
205
206 Color text_color = palette().color(foreground_role());
207 if (is_selected_row)
208 text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
209
210 Color background_color;
211 Color key_column_background_color;
212 if (is_selected_row) {
213 background_color = is_focused() ? palette().selection() : palette().inactive_selection();
214 key_column_background_color = is_focused() ? palette().selection() : palette().inactive_selection();
215 } else {
216 if (alternating_row_colors() && (painted_row_index % 2)) {
217 background_color = Color(220, 220, 220);
218 key_column_background_color = Color(200, 200, 200);
219 } else {
220 background_color = palette().color(background_role());
221 key_column_background_color = Color(220, 220, 220);
222 }
223 }
224
225 Gfx::Rect row_rect { 0, rect.y(), frame_inner_rect().width(), rect.height() };
226 painter.fill_rect(row_rect, background_color);
227
228 int x_offset = 0;
229 for (int column_index = 0; column_index < model.column_count(); ++column_index) {
230 if (is_column_hidden(column_index))
231 continue;
232 auto column_metadata = model.column_metadata(column_index);
233 int column_width = this->column_width(column_index);
234 auto& font = column_metadata.font ? *column_metadata.font : this->font();
235
236 painter.draw_rect(toggle_rect, text_color);
237
238 if (column_index != tree_column) {
239 Gfx::Rect cell_rect(horizontal_padding() + x_offset, rect.y(), column_width, item_height());
240 auto cell_index = model.sibling(index.row(), column_index, index.parent());
241
242 if (auto* delegate = column_data(column_index).cell_painting_delegate.ptr()) {
243 delegate->paint(painter, cell_rect, palette(), model, cell_index);
244 } else {
245 auto data = model.data(cell_index);
246
247 if (data.is_bitmap()) {
248 painter.blit(cell_rect.location(), data.as_bitmap(), data.as_bitmap().rect());
249 } else if (data.is_icon()) {
250 if (auto bitmap = data.as_icon().bitmap_for_size(16))
251 painter.blit(cell_rect.location(), *bitmap, bitmap->rect());
252 } else {
253 if (!is_selected_row)
254 text_color = model.data(cell_index, Model::Role::ForegroundColor).to_color(palette().color(foreground_role()));
255 painter.draw_text(cell_rect, data.to_string(), font, column_metadata.text_alignment, text_color, Gfx::TextElision::Right);
256 }
257 }
258 } else {
259 // It's the tree column!
260 Gfx::Rect icon_rect = { rect.x(), rect.y(), icon_size(), icon_size() };
261 auto icon = model.data(index, Model::Role::Icon);
262 if (icon.is_icon()) {
263 if (auto* bitmap = icon.as_icon().bitmap_for_size(icon_size())) {
264 if (m_hovered_index.is_valid() && m_hovered_index.parent() == index.parent() && m_hovered_index.row() == index.row())
265 painter.blit_brightened(icon_rect.location(), *bitmap, bitmap->rect());
266 else
267 painter.blit(icon_rect.location(), *bitmap, bitmap->rect());
268 }
269 }
270 Gfx::Rect text_rect = {
271 icon_rect.right() + 1 + icon_spacing(), rect.y(),
272 rect.width() - icon_size() - icon_spacing(), rect.height()
273 };
274 auto node_text = model.data(index, Model::Role::Display).to_string();
275 painter.draw_text(text_rect, node_text, Gfx::TextAlignment::Center, text_color);
276 auto index_at_indent = index;
277 for (int i = indent_level; i > 0; --i) {
278 auto parent_of_index_at_indent = index_at_indent.parent();
279 bool index_at_indent_is_last_in_parent = index_at_indent.row() == model.row_count(parent_of_index_at_indent) - 1;
280 Gfx::Point a { tree_column_x_offset + horizontal_padding() + indent_width_in_pixels() * i - icon_size() / 2, rect.y() - 2 };
281 Gfx::Point b { a.x(), a.y() + item_height() - 1 };
282 if (index_at_indent_is_last_in_parent)
283 b.set_y(rect.center().y());
284 if (!(i != indent_level && index_at_indent_is_last_in_parent))
285 painter.draw_line(a, b, Color::MidGray);
286
287 if (i == indent_level) {
288 Gfx::Point c { a.x(), rect.center().y() };
289 Gfx::Point d { c.x() + icon_size() / 2, c.y() };
290 painter.draw_line(c, d, Color::MidGray);
291 }
292 index_at_indent = parent_of_index_at_indent;
293 }
294
295 if (!toggle_rect.is_empty()) {
296 auto& metadata = ensure_metadata_for_index(index);
297 if (metadata.open)
298 painter.blit(toggle_rect.location(), *m_collapse_bitmap, m_collapse_bitmap->rect());
299 else
300 painter.blit(toggle_rect.location(), *m_expand_bitmap, m_expand_bitmap->rect());
301 }
302 }
303 x_offset += column_width + horizontal_padding() * 2;
304 }
305
306 return IterationDecision::Continue;
307 });
308
309 // Untranslate the painter vertically and do the column headers.
310 painter.translate(0, vertical_scrollbar().value());
311 paint_headers(painter);
312}
313
314void TreeView::scroll_into_view(const ModelIndex& a_index, Orientation orientation)
315{
316 if (!a_index.is_valid())
317 return;
318 Gfx::Rect found_rect;
319 traverse_in_paint_order([&](const ModelIndex& index, const Gfx::Rect& rect, const Gfx::Rect&, int) {
320 if (index == a_index) {
321 found_rect = rect;
322 return IterationDecision::Break;
323 }
324 return IterationDecision::Continue;
325 });
326 ScrollableWidget::scroll_into_view(found_rect, orientation);
327}
328
329void TreeView::did_update_model()
330{
331 m_view_metadata.clear();
332 AbstractTableView::did_update_model();
333}
334
335void TreeView::did_update_selection()
336{
337 AbstractView::did_update_selection();
338 ASSERT(model());
339 auto index = selection().first();
340 if (!index.is_valid())
341 return;
342#if 0
343 bool opened_any = false;
344 for (auto current = index; current.is_valid(); current = current.parent()) {
345 auto& metadata_for_ancestor = ensure_metadata_for_index(current);
346 if (!metadata_for_ancestor.open) {
347 metadata_for_ancestor.open = true;
348 opened_any = true;
349 }
350 }
351 if (opened_any)
352 update_content_size();
353 update();
354#endif
355 if (activates_on_selection())
356 activate(index);
357}
358
359void TreeView::keydown_event(KeyEvent& event)
360{
361 if (!model())
362 return;
363 auto cursor_index = selection().first();
364
365 if (event.key() == KeyCode::Key_Space) {
366 if (model()->row_count(cursor_index))
367 toggle_index(cursor_index);
368 return;
369 }
370
371 if (event.key() == KeyCode::Key_Up) {
372 ModelIndex previous_index;
373 ModelIndex found_index;
374 traverse_in_paint_order([&](const ModelIndex& index, const Gfx::Rect&, const Gfx::Rect&, int) {
375 if (index == cursor_index) {
376 found_index = previous_index;
377 return IterationDecision::Break;
378 }
379 previous_index = index;
380 return IterationDecision::Continue;
381 });
382 if (found_index.is_valid()) {
383 selection().set(found_index);
384 scroll_into_view(selection().first(), Orientation::Vertical);
385 update();
386 }
387 return;
388 }
389 if (event.key() == KeyCode::Key_Down) {
390 ModelIndex previous_index;
391 ModelIndex found_index;
392 traverse_in_paint_order([&](const ModelIndex& index, const Gfx::Rect&, const Gfx::Rect&, int) {
393 if (previous_index == cursor_index) {
394 found_index = index;
395 return IterationDecision::Break;
396 }
397 previous_index = index;
398 return IterationDecision::Continue;
399 });
400 if (found_index.is_valid()) {
401 selection().set(found_index);
402 scroll_into_view(selection().first(), Orientation::Vertical);
403 update();
404 }
405 return;
406 }
407
408 auto open_tree_node = [&](bool open, MetadataForIndex& metadata) {
409 metadata.open = open;
410 update_column_sizes();
411 update_content_size();
412 update();
413 };
414
415 if (event.key() == KeyCode::Key_Left) {
416 if (cursor_index.is_valid() && model()->row_count(cursor_index)) {
417 auto& metadata = ensure_metadata_for_index(cursor_index);
418 if (metadata.open) {
419 open_tree_node(false, metadata);
420 return;
421 }
422 }
423 if (cursor_index.is_valid() && cursor_index.parent().is_valid()) {
424 selection().set(cursor_index.parent());
425 scroll_into_view(selection().first(), Orientation::Vertical);
426 return;
427 }
428 }
429
430 if (event.key() == KeyCode::Key_Right) {
431 if (cursor_index.is_valid() && model()->row_count(cursor_index)) {
432 auto& metadata = ensure_metadata_for_index(cursor_index);
433 if (!metadata.open) {
434 open_tree_node(true, metadata);
435 return;
436 }
437
438 selection().set(model()->index(0, model()->tree_column(), cursor_index));
439 scroll_into_view(selection().first(), Orientation::Vertical);
440 return;
441 }
442 }
443
444 if (event.key() == KeyCode::Key_Return) {
445 if (cursor_index.is_valid() && model()->row_count(cursor_index)) {
446 auto& metadata = ensure_metadata_for_index(cursor_index);
447 open_tree_node(!metadata.open, metadata);
448 return;
449 }
450 }
451}
452
453int TreeView::item_count() const
454{
455 int count = 0;
456 traverse_in_paint_order([&](const ModelIndex&, const Gfx::Rect&, const Gfx::Rect&, int) {
457 ++count;
458 return IterationDecision::Continue;
459 });
460 return count;
461}
462
463void TreeView::update_column_sizes()
464{
465 if (!size_columns_to_fit_content())
466 return;
467
468 if (!model())
469 return;
470
471 auto& model = *this->model();
472 int column_count = model.column_count();
473 int row_count = model.row_count();
474 int tree_column = model.tree_column();
475 int tree_column_x_offset = 0;
476
477 for (int column = 0; column < column_count; ++column) {
478 if (column == tree_column)
479 continue;
480 if (is_column_hidden(column))
481 continue;
482 int header_width = header_font().width(model.column_name(column));
483 int column_width = header_width;
484
485 for (int row = 0; row < row_count; ++row) {
486 auto cell_data = model.data(model.index(row, column));
487 int cell_width = 0;
488 if (cell_data.is_bitmap()) {
489 cell_width = cell_data.as_bitmap().width();
490 } else {
491 cell_width = font().width(cell_data.to_string());
492 }
493 column_width = max(column_width, cell_width);
494 }
495 auto& column_data = this->column_data(column);
496 column_data.width = max(column_data.width, column_width);
497 column_data.has_initialized_width = true;
498
499 if (column < tree_column)
500 tree_column_x_offset += column_width;
501 }
502
503 int tree_column_header_width = header_font().width(model.column_name(tree_column));
504 int tree_column_width = tree_column_header_width;
505 traverse_in_paint_order([&](const ModelIndex&, const Gfx::Rect& rect, const Gfx::Rect&, int) {
506 tree_column_width = max(rect.right() - tree_column_x_offset, tree_column_width);
507 return IterationDecision::Continue;
508 });
509
510 auto& column_data = this->column_data(tree_column);
511 column_data.width = max(column_data.width, tree_column_width);
512 column_data.has_initialized_width = true;
513}
514
515int TreeView::tree_column_x_offset() const
516{
517 int tree_column = model()->tree_column();
518 int offset = 0;
519 for (int i = 0; i < tree_column; ++i) {
520 if (!is_column_hidden(i)) {
521 offset += column_width(i);
522 offset += horizontal_padding();
523 }
524 }
525 return offset;
526}
527
528}