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