Blender V5.3
tree_view.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BKE_context.hh"
10
11#include "BLT_translation.hh"
12
13#include "GPU_immediate.hh"
14#include "GPU_state.hh"
15
16#include "interface_intern.hh"
17
19#include "UI_view2d.hh"
20
21#include "BLI_listbase.hh"
23#include "BLI_string.hh"
24
25#include "UI_tree_view.hh"
26
27namespace blender::ui {
28
29#define UI_TREEVIEW_INDENT short(0.7f * UI_UNIT_X)
30#define MIN_ROWS 4
31
33{
34 return UI_UNIT_Y;
35}
37{
38 const uiStyle *style = style_get_dpi();
39 return unpadded_item_height() + style->buttonspacey;
40}
41
42/* ---------------------------------------------------------------------- */
43
45 std::unique_ptr<AbstractTreeViewItem> item)
46{
47 children_.append(std::move(item));
48
49 /* The first item that will be added to the root sets this. */
50 if (root_ == nullptr) {
51 root_ = this;
52 }
53 AbstractTreeView &tree_view = static_cast<AbstractTreeView &>(*root_);
54 AbstractTreeViewItem &added_item = *children_.last();
55 added_item.root_ = root_;
56 tree_view.register_item(added_item);
57
58 if (root_ != this) {
59 /* Any item that isn't the root can be assumed to the a #AbstractTreeViewItem. Not entirely
60 * nice to static_cast this, but well... */
61 added_item.parent_ = static_cast<AbstractTreeViewItem *>(this);
62 }
63
64 return added_item;
65}
66
68{
69 for (const auto &child : children_) {
70 bool skip = false;
71 if (flag_is_set(options, IterOptions::SkipFiltered) && !child->is_filtered_visible()) {
72 skip = true;
73 }
74
75 if (!skip) {
76 iter_fn(*child);
77 }
78
79 if (flag_is_set(options, IterOptions::SkipCollapsed) && child->is_collapsed()) {
80 continue;
81 }
82
83 child->foreach_item_recursive(iter_fn, options);
84 }
85}
86
88{
89 for (AbstractTreeViewItem *item = parent_; item; item = item->parent_) {
90 iter_fn(*item);
91 }
92}
93
95{
96 std::ranges::sort(children_,
97 [](const std::unique_ptr<AbstractTreeViewItem> &a,
98 const std::unique_ptr<AbstractTreeViewItem> &b) {
99 StringRefNull a_name = a->label();
100 StringRefNull b_name = b->label();
101 return BLI_strcasecmp_natural(a_name.c_str(), b_name.c_str()) < 0;
102 });
103
104 for (std::unique_ptr<AbstractTreeViewItem> &item : children_) {
105 item->sort_alpha();
106 }
107}
108
110{
111 std::ranges::reverse(children_);
112 if (order == TreeViewSortOrder::InvertNested) {
113 for (auto &child : children_) {
114 child->foreach_sort_invert(order);
115 }
116 }
117}
118/* ---------------------------------------------------------------------- */
119
120void AbstractTreeView::foreach_view_item(FunctionRef<void(AbstractViewItem &)> iter_fn) const
121{
122 /* Implementation for the base class virtual function. More specialized iterators below. */
123
124 this->foreach_item_recursive(iter_fn);
125}
126
131
133{
134 for (const auto &child : children_) {
135 iter_fn(*child);
136 }
137}
138
140{
141 AbstractViewItem *active_item = nullptr;
142 AbstractViewItem *first_visible_item = nullptr;
143 this->foreach_item(
144 [&](AbstractViewItem &item) {
145 if (item.is_active()) {
146 active_item = &item;
147 }
148 if (!first_visible_item) {
149 first_visible_item = &item;
150 }
151 },
153
154 return active_item ? active_item : first_visible_item;
155}
156
157AbstractViewItem *AbstractTreeView::navigate_left(AbstractViewItem *from)
158{
159 AbstractTreeViewItem *tree_item = dynamic_cast<AbstractTreeViewItem *>(from);
160 if (!tree_item->is_collapsible() || tree_item->is_collapsed()) {
161 return tree_item->get_parent();
162 }
163 tree_item->set_collapsed(true);
164 return from;
165}
166
167AbstractViewItem *AbstractTreeView::navigate_right(AbstractViewItem *from)
168{
169 AbstractTreeViewItem *active_item = dynamic_cast<AbstractTreeViewItem *>(from);
170 if (!active_item->is_collapsible() || active_item->is_collapsed()) {
171 active_item->set_collapsed(false);
172 return active_item;
173 }
174 return active_item->get_child();
175}
176
177AbstractViewItem *AbstractTreeView::navigate_up(AbstractViewItem *from)
178{
179 AbstractViewItem *next_item = nullptr;
180 bool found_active = false;
181 this->foreach_item(
182 [&](AbstractViewItem &item) {
183 found_active |= item.is_active();
184 if (!found_active) {
185 /* Store the element which is just before the active. */
186 next_item = &item;
187 }
188 },
190 return found_active ? next_item : from;
191}
192
193AbstractViewItem *AbstractTreeView::navigate_down(AbstractViewItem *from)
194{
195 AbstractViewItem *next_item = nullptr;
196 bool found_active = false;
197 this->foreach_item(
198 [&](AbstractViewItem &item) {
199 if (found_active) {
200 /* Store the element next to the active. */
201 next_item = &item;
202 found_active = false;
203 }
204 found_active = item.is_active();
205 },
207 return next_item ? next_item : from;
208}
209
210void AbstractTreeView::page_scroll(bContext * /*C*/, PageScrollDirection direction)
211{
212 if (this->is_fully_visible() || !this->supports_scrolling()) {
213 return;
214 }
215
216 const int visible_rows = this->tot_visible_row_count().value_or(0);
217
218 switch (direction) {
220 *this->scroll_value_ = std::max(0, *this->scroll_value_ - visible_rows);
221 break;
223 *this->scroll_value_ = std::min(this->last_tot_items_, *this->scroll_value_ + visible_rows);
224 break;
226 *this->scroll_value_ = 0;
227 break;
229 *this->scroll_value_ = this->last_tot_items_;
230 break;
231 }
232}
233
235{
236 BLI_assert_msg(default_rows >= MIN_ROWS,
237 "Default value is smaller than the minimum rows. Limit is required to prevent "
238 "resizing below specific height.");
239 custom_height_ = std::make_unique<int>(default_rows * padded_item_height());
240}
241
242std::optional<uiViewState> AbstractTreeView::persistent_state() const
243{
245
246 SET_FLAG_FROM_TEST(state.flag, *show_display_options_, UI_VIEW_SHOW_FILTER_OPTIONS);
247 SET_FLAG_FROM_TEST(state.flag, *sort_alpha_, UI_VIEW_SORT_ALPHA);
248 SET_FLAG_FROM_TEST(state.flag, *invert_search_filter_, UI_VIEW_FILTER_INVERT);
249 STRNCPY(state.search_string, search_string_.get());
250
251 if (!custom_height_ && !scroll_value_) {
252 return {};
253 }
254
255 if (custom_height_) {
256 state.custom_height = *custom_height_ * UI_INV_SCALE_FAC;
257 }
258 if (scroll_value_) {
259 state.scroll_offset = *scroll_value_;
260 }
261 state.invert_sort_type = uint8_t(*invert_sort_type_);
262 return state;
263}
264
266{
267 if (state.custom_height) {
268 set_default_rows(std::max(
270 }
271 if (state.scroll_offset) {
272 scroll_value_ = std::make_shared<int>(state.scroll_offset);
273 }
274
275 *show_display_options_ = (state.flag & UI_VIEW_SHOW_FILTER_OPTIONS) != 0;
276 *sort_alpha_ = (state.flag & UI_VIEW_SORT_ALPHA) != 0;
277 *invert_search_filter_ = (state.flag & UI_VIEW_FILTER_INVERT) != 0;
278 BLI_strncpy(search_string_.get(), state.search_string, UI_MAX_NAME_STR);
279 *invert_sort_type_ = TreeViewSortOrder(state.invert_sort_type);
280}
281
282int AbstractTreeView::count_visible_descendants(const AbstractTreeViewItem &parent) const
283{
284 if (parent.is_collapsed()) {
285 return 0;
286 }
287 int count = 0;
288 for (const auto &item : parent.children_) {
289 if (!item->is_filtered_visible()) {
290 continue;
291 }
292 count++;
293 count += count_visible_descendants(*item);
294 }
295
296 return count;
297}
298
299void AbstractTreeView::get_hierarchy_lines(const TreeViewOrItem &parent,
300 const float aspect,
301 Vector<std::pair<int2, int2>> &lines,
302 int &visible_item_index) const
303{
304 const int scroll_ofs = scroll_value_ ? *scroll_value_ : 0;
305 const int max_visible_row_count = tot_visible_row_count().value_or(
306 std::numeric_limits<int>::max());
307
308 for (const auto &item : parent.children_) {
309 if (!item->is_filtered_visible()) {
310 continue;
311 }
312
313 const int item_index = visible_item_index;
314 visible_item_index++;
315
316 if (!item->is_collapsible() || item->is_collapsed()) {
317 continue;
318 }
319 if (item->children_.is_empty()) {
320 BLI_assert(item->is_always_collapsible_);
321 continue;
322 }
323
324 /* Draw a hierarchy line for the descendants of this item. */
325
326 const AbstractTreeViewItem *first_descendant = item->children_.first().get();
327 const int descendant_count = count_visible_descendants(*item);
328
329 const int first_descendant_index = item_index + 1;
330 const int last_descendant_index = item_index + descendant_count;
331
332 {
333 const bool line_ends_above_visible = last_descendant_index < scroll_ofs;
334 if (line_ends_above_visible) {
335 /* We won't recurse into the child items even though they are present (just scrolled out of
336 * view). Still update the index to be the first following item. */
337 visible_item_index = last_descendant_index + 1;
338 continue;
339 }
340
341 const bool line_starts_below_visible = first_descendant_index >
342 (scroll_ofs + long(max_visible_row_count));
343 /* Can return here even, following items won't be in view anymore. */
344 if (line_starts_below_visible) {
345 return;
346 }
347 }
348
349 const int x = ((first_descendant->indent_width() + uiLayoutListItemPaddingWidth() -
350 (0.5f * UI_ICON_SIZE) + U.pixelsize + UI_SCALE_FAC) /
351 aspect);
352 const int ymax = std::max(0, first_descendant_index - scroll_ofs) * padded_item_height() /
353 aspect;
354 const int ymin = std::min(max_visible_row_count, last_descendant_index + 1 - scroll_ofs) *
355 padded_item_height() / aspect;
356 lines.append(std::make_pair(int2(x, ymax), int2(x, ymin)));
357
358 this->get_hierarchy_lines(*item, aspect, lines, visible_item_index);
359 }
360}
361
362void AbstractTreeView::sort_inverted()
363{
364 if (*invert_sort_type_ == TreeViewSortOrder::None) {
365 return;
366 }
367 this->foreach_sort_invert(*invert_sort_type_);
368}
369
371{
372 return *invert_sort_type_;
373}
375{
376 for (Button &but : block.buttons()) {
377 if (but.type != ButtonType::ViewItem) {
378 continue;
379 }
380 auto *view_item_but = static_cast<ButtonViewItem *>(&but);
381 if (&view_item_but->view_item->get_view() == &view) {
382 return view_item_but;
383 }
384 }
385 return nullptr;
386}
387
388void AbstractTreeView::draw_hierarchy_lines(const ARegion &region, const Block &block) const
389{
390 const float aspect = (region.v2d.flag & V2D_IS_INIT) ?
391 BLI_rctf_size_y(&region.v2d.cur) /
392 (BLI_rcti_size_y(&region.v2d.mask) + 1) :
393 1.0f;
394
395 ButtonViewItem *first_item_but = find_first_view_item_but(block, *this);
396 if (!first_item_but) {
397 return;
398 }
399
400 Vector<std::pair<int2, int2>> lines;
401 int index = 0;
402 get_hierarchy_lines(*this, aspect, lines, index);
403 if (lines.is_empty()) {
404 return;
405 }
406
407 GPUVertFormat *format = immVertexFormat();
408 uint pos = GPU_vertformat_attr_add(format, "pos", gpu::VertAttrType::SFLOAT_32_32);
411
412 GPU_line_width(1.0f / aspect);
414
415 rcti first_item_but_pixel_rect;
416 button_to_pixelrect(&first_item_but_pixel_rect, &region, &block, first_item_but);
417 int2 top_left{first_item_but_pixel_rect.xmin, first_item_but_pixel_rect.ymax};
418
419 for (const auto &line : lines) {
421 immVertex2f(pos, top_left.x + line.first.x, top_left.y - line.first.y);
422 immVertex2f(pos, top_left.x + line.second.x, top_left.y - line.second.y);
423 immEnd();
424 }
426
428}
429
430void AbstractTreeView::draw_overlays(const ARegion &region, const Block &block) const
431{
432 this->draw_hierarchy_lines(region, block);
433}
434
435void AbstractTreeView::update_children_from_old(const AbstractView &old_view)
436{
437 const AbstractTreeView &old_tree_view = dynamic_cast<const AbstractTreeView &>(old_view);
438
439 custom_height_ = old_tree_view.custom_height_;
440 scroll_value_ = old_tree_view.scroll_value_;
441 search_string_ = old_tree_view.search_string_;
442 show_display_options_ = old_tree_view.show_display_options_;
443 sort_alpha_ = old_tree_view.sort_alpha_;
444 invert_sort_type_ = old_tree_view.invert_sort_type_;
445 invert_search_filter_ = old_tree_view.invert_search_filter_;
446 update_children_from_old_recursive(*this, old_tree_view);
447}
448
449void AbstractTreeView::update_children_from_old_recursive(const TreeViewOrItem &new_items,
450 const TreeViewOrItem &old_items)
451{
452 /* This map can't find the exact old item for a new item. However, it can drastically reduce the
453 * number of items that need to be checked. */
455 for (const auto &old_item : old_items.children_) {
456 old_children_by_label.add(old_item->label_, old_item.get());
457 }
458
459 for (const auto &new_item : new_items.children_) {
460 const Span<AbstractTreeViewItem *> possible_old_children = old_children_by_label.lookup(
461 new_item->label_);
462 AbstractTreeViewItem *matching_old_item = find_matching_child(*new_item,
463 possible_old_children);
464 if (!matching_old_item) {
465 continue;
466 }
467
468 new_item->update_from_old(*matching_old_item);
469
470 /* Recurse into children of the matched item. */
471 update_children_from_old_recursive(*new_item, *matching_old_item);
472 }
473}
474
475AbstractTreeViewItem *AbstractTreeView::find_matching_child(
476 const AbstractTreeViewItem &lookup_item, const Span<AbstractTreeViewItem *> possible_items)
477{
478 for (auto *iter_item : possible_items) {
479 if (lookup_item.matches(*iter_item)) {
480 /* We have a matching item! */
481 return iter_item;
482 }
483 }
484
485 return nullptr;
486}
487
488std::optional<int> AbstractTreeView::tot_visible_row_count() const
489{
490 if (!custom_height_) {
491 return {};
492 }
493 const int calculate_rows = round_fl_to_int(float(*custom_height_) / padded_item_height());
494 /* Clamp value to prevent resizing below minimum number of rows. */
495 return math::max(MIN_ROWS, calculate_rows);
496}
497
499{
500 return custom_height_ && scroll_value_;
501}
502
504{
505 return this->tot_visible_row_count().value_or(0) >= last_tot_items_;
506}
507
509{
510 if (!supports_scrolling()) {
511 return;
512 }
513 /* Scroll value will be sanitized/clamped when drawing. */
514 *scroll_value_ += ((direction == ViewScrollDirection::UP) ? -1 : 1);
515}
516
517void AbstractTreeView::scroll_active_into_view(bContext * /*C*/, bool scroll_active_to_center)
518{
519 int index = 0;
520 const std::optional<int> visible_row_count = tot_visible_row_count();
521
522 if (!custom_height_) {
523 return;
524 }
525
526 if (!visible_row_count.has_value()) {
527 return;
528 }
529
530 if (!scroll_value_) {
531 scroll_value_ = std::make_unique<int>(0);
532 }
534 [&, this](AbstractTreeViewItem &item) {
535 if (item.is_active_) {
536 if (scroll_active_to_center) {
537 *scroll_value_ = std::clamp(
538 index - (*visible_row_count - 1) / 2, 0, (last_tot_items_ - *visible_row_count));
539 return;
540 }
541 if (index < *scroll_value_) {
542 *scroll_value_ = index;
543 return;
544 }
545 if (index > (*scroll_value_ + *visible_row_count - 1)) {
546 *scroll_value_ = std::max(0, index - *visible_row_count + 1);
547 return;
548 }
549 }
550 index++;
551 },
553}
554
555/* ---------------------------------------------------------------------- */
556
558 DropBehavior behavior)
559 : view_item_(view_item), behavior_(behavior)
560{
561}
562
564 const ARegion &region, const wmEvent &event) const
565{
567 return DropLocation::Into;
568 }
569
570 std::optional<rctf> win_rect = view_item_.get_win_rect(region);
571 if (!win_rect) {
573 return std::nullopt;
574 }
575 const float item_height = BLI_rctf_size_y(&*win_rect);
576
578
579 const int segment_count =
581 /* Divide into upper (insert before) and lower (insert after) half. */
582 2 :
583 /* Upper (insert before), middle (insert into) and lower (insert after) third. */
584 3;
585 const float segment_height = item_height / segment_count;
586
587 if (event.xy[1] < win_rect->ymin) {
588 return DropLocation::After;
589 }
590 if (event.xy[1] - win_rect->ymin > (item_height - segment_height)) {
592 }
593 if (event.xy[1] - win_rect->ymin <= segment_height) {
596 {
597 /* Special case: Dropping at the lower 3rd of an uncollapsed item should insert into it, not
598 * after. */
599 return DropLocation::Into;
600 }
601 return DropLocation::After;
602 }
603
605 return DropLocation::Into;
606}
607
608/* ---------------------------------------------------------------------- */
609
614
615void AbstractTreeViewItem::add_treerow_button(Block &block)
616{
617 /* For some reason a width > (UI_UNIT_X * 2) make the layout system use all available width. */
618 view_item_but_ = reinterpret_cast<ButtonViewItem *>(uiDefBut(&block,
620 "",
621 0,
622 0,
623 UI_UNIT_X * 10,
625 nullptr,
626 0,
627 0,
628 ""));
629
631}
632
633int AbstractTreeViewItem::indent_width() const
634{
635 return this->count_parents() * UI_TREEVIEW_INDENT;
636}
637
638void AbstractTreeViewItem::add_indent(Layout &row) const
639{
640 Block *block = row.block();
641 Layout &subrow = row.row(true);
642 subrow.fixed_size_set(true);
643
644 uiDefBut(block, ButtonType::Sepr, "", 0, 0, this->indent_width(), 0, nullptr, 0.0, 0.0, "");
645
646 const bool is_flat_list = root_ && root_->is_flat_;
647 if (!is_flat_list && !this->is_collapsible()) {
648 /* Indent items without collapsing icon some more within their parent. Makes it clear that they
649 * are actually nested and not just a row at the same level without a chevron. */
650 uiDefBut(block, ButtonType::Sepr, "", 0, 0, UI_TREEVIEW_INDENT, 0, nullptr, 0.0, 0.0, "");
651 }
652
653 /* Restore. */
654 block_layout_set_current(block, &row);
655}
656
657void AbstractTreeViewItem::collapse_chevron_click_fn(bContext *C,
658 void * /*but_arg1*/,
659 void * /*arg2*/)
660{
661 /* There's no data we could pass to this callback. It must be either the button itself or a
662 * consistent address to match buttons over redraws. So instead of passing it somehow, just
663 * lookup the hovered item via context here. */
664
665 const wmWindow *win = CTX_wm_window(C);
666 const ARegion *region = CTX_wm_region_popup(C) ? CTX_wm_region_popup(C) : CTX_wm_region(C);
667 AbstractViewItem *hovered_abstract_item = region_views_find_item_at(
668 *region, win->runtime->eventstate->xy);
669
670 auto *hovered_item = reinterpret_cast<AbstractTreeViewItem *>(hovered_abstract_item);
671 BLI_assert(hovered_item != nullptr);
672
673 hovered_item->toggle_collapsed_from_view(*C);
674 /* When collapsing an item with an active child, make this collapsed item active instead so the
675 * active item stays visible. */
676 if (hovered_item->has_active_child()) {
677 hovered_item->activate(*C);
678 }
679}
680
681void AbstractTreeViewItem::add_collapse_chevron(Block &block) const
682{
683 if (!this->is_collapsible()) {
684 return;
685 }
686
687 const BIFIconID icon = this->is_collapsed() ? ICON_RIGHTARROW : ICON_DOWNARROW_HLT;
688 Button *but = uiDefIconBut(
689 &block, ButtonType::ButToggle, icon, 0, 0, UI_TREEVIEW_INDENT, UI_UNIT_Y, nullptr, 0, 0, "");
690 button_func_set(but, collapse_chevron_click_fn, nullptr, nullptr);
691 /* To make drag toggle work. */
692 button_func_pushed_state_set(but, [this](const Button &) { return this->is_collapsed(); });
694}
695
696void AbstractTreeViewItem::add_rename_button(Layout &row)
697{
698 Block *block = row.block();
699 EmbossType previous_emboss = block_emboss_get(block);
700
701 row.row(false);
702 /* Enable emboss for the text button. */
704
706
707 block_emboss_set(block, previous_emboss);
708 block_layout_set_current(block, &row);
709}
710
711bool AbstractTreeViewItem::has_active_child() const
712{
713 bool found = false;
714 foreach_item_recursive([&found](const AbstractTreeViewItem &item) {
715 if (item.is_active()) {
716 found = true;
717 }
718 });
719
720 return found;
721}
722
724{
725 return true;
726}
727
732
734{
735 /* It is important to update the label after renaming, so #AbstractTreeViewItem::matches_single()
736 * recognizes the item. (It only compares labels by default.) */
737 label_ = new_name;
738 return true;
739}
740
742{
744
745 const AbstractTreeViewItem &old_tree_item = dynamic_cast<const AbstractTreeViewItem &>(old);
746 is_open_ = old_tree_item.is_open_;
747}
748
750{
751 return AbstractViewItem::should_be_filtered_visible(filter_string) !=
752 bool(*this->get_tree_view().invert_search_filter_);
753}
754
756{
757 return label_ == other.label_;
758}
759
760std::unique_ptr<DropTargetInterface> AbstractTreeViewItem::create_item_drop_target()
761{
762 return this->create_drop_target();
763}
764
765std::unique_ptr<TreeViewItemDropTarget> AbstractTreeViewItem::create_drop_target()
766{
767 return nullptr;
768}
769
770std::optional<std::string> AbstractTreeViewItem::debug_name() const
771{
772 return label_;
773}
774
776{
777 return dynamic_cast<AbstractTreeView &>(get_view());
778}
779
780std::optional<rctf> AbstractTreeViewItem::get_win_rect(const ARegion &region) const
781{
782 ButtonViewItem *item_but = view_item_button();
783 if (!item_but) {
784 return std::nullopt;
785 }
786
787 rctf win_rect;
788 block_to_window_rctf(&region, item_but->block, &win_rect, &item_but->rect);
789
790 return win_rect;
791}
792
794{
795 int i = 0;
796 for (AbstractTreeViewItem *parent = parent_; parent; parent = parent->parent_) {
797 i++;
798 }
799 return i;
800}
801
806
808{
809 for (const auto &child : children_) {
810 if (child->is_filtered_visible()) {
811 return child.get();
812 }
813 }
814 return nullptr;
815}
816
818{
820 /* Make sure the active item is always visible. */
822 return true;
823 }
824
825 return false;
826}
827
829{
830 BLI_assert_msg(get_tree_view().is_reconstructed(),
831 "State cannot be queried until reconstruction is completed");
832 return this->is_collapsible() && !is_open_;
833}
834
836{
837 return this->set_collapsed(is_open_);
838}
839
846
847bool AbstractTreeViewItem::set_collapsed(const bool collapsed)
848{
849 if (!this->is_collapsible()) {
850 return false;
851 }
852 if (collapsed == !is_open_) {
853 return false;
854 }
855
856 is_open_ = !collapsed;
857 return true;
858}
859
860void AbstractTreeViewItem::on_collapse_change(bContext & /*C*/, const bool /*is_collapsed*/)
861{
862 /* Do nothing by default. */
863}
864
866{
867 return std::nullopt;
868}
869
871{
872 BLI_assert_msg(this->get_tree_view().is_reconstructed() == false,
873 "Default state should only be set while building the tree");
875 /* Set the open state. Note that this may be overridden later by #should_be_collapsed(). */
876 is_open_ = true;
877}
878
880{
881 BLI_assert_msg(get_tree_view().is_reconstructed(),
882 "State can't be queried until reconstruction is completed");
884 return true;
885 }
886 if (children_.is_empty()) {
887 return false;
888 }
889 return this->supports_collapsing();
890}
891
893{
894 const bool prev_active_state = is_active();
896
897 if (prev_active_state != is_active()) {
898 this->get_tree_view().scroll_active_into_view_on_draw_ = true;
899 }
900
901 const std::optional<bool> should_be_collapsed = this->should_be_collapsed();
902 if (should_be_collapsed.has_value()) {
903 /* This reflects an external state change and therefore shouldn't call #on_collapse_change().
904 */
906 }
907}
908
910{
911 for (AbstractTreeViewItem *parent = parent_; parent; parent = parent->parent_) {
912 parent->set_collapsed(false);
913 }
914}
915
917{
918 const AbstractTreeViewItem &other_tree_item = dynamic_cast<const AbstractTreeViewItem &>(other);
919
920 if (!this->matches_single(other_tree_item)) {
921 return false;
922 }
923 if (this->count_parents() != other_tree_item.count_parents()) {
924 return false;
925 }
926
927 for (AbstractTreeViewItem *parent = parent_, *other_parent = other_tree_item.parent_;
928 parent && other_parent;
929 parent = parent->parent_, other_parent = other_parent->parent_)
930 {
931 if (!parent->matches_single(*other_parent)) {
932 return false;
933 }
934 }
935
936 return true;
937}
938
940{
941 BLI_assert(this->get_tree_view().search_string_ && this->get_tree_view().search_string_[0]);
942
945 item.is_filtered_visible_ = true;
946 item.set_collapsed(false);
947 });
948 }
949}
950
955
956/* ---------------------------------------------------------------------- */
957
958class TreeViewLayoutBuilder {
959 Block &block_;
960 bool add_box_ = true;
961
962 friend TreeViewBuilder;
963
964 public:
965 void build_from_tree(AbstractTreeView &tree_view);
966 void build_row(AbstractTreeViewItem &item) const;
967
968 Block &block() const;
969 Layout &current_layout() const;
970
971 private:
972 /* Created through #TreeViewBuilder (friend class). */
973 TreeViewLayoutBuilder(Layout &layout);
974};
975
976TreeViewLayoutBuilder::TreeViewLayoutBuilder(Layout &layout) : block_(*layout.block()) {}
977
979{
980 int item_count = 0;
981 tree_view.foreach_item([&](AbstractTreeViewItem &) { item_count++; },
984 return item_count;
985}
986
987static void set_sort_order_fn(bContext * /*C*/, void * /*but_arg1*/, void *arg2)
988{
989 TreeViewSortOrder &order = *static_cast<TreeViewSortOrder *>(arg2);
990 order = TreeViewSortOrder((uint8_t(order) + 1) % 3);
991}
992
994{
995 Layout &parent_layout = this->current_layout();
996 Block *block = parent_layout.block();
997
998 Layout &col = (add_box_ ? parent_layout.box() : parent_layout).column(true);
999
1000 /* Row for the tree-view and the scroll bar. */
1001 Layout &row = col.row(false);
1002
1003 const std::optional<int> visible_row_count = tree_view.tot_visible_row_count();
1004 const int tot_items = count_visible_items(tree_view);
1005 tree_view.last_tot_items_ = tot_items;
1006
1007 /* Column for the tree view. */
1008 row.column(true);
1009
1010 /* Clamp scroll-value to valid range. */
1011 if (tree_view.scroll_value_ && visible_row_count) {
1012 *tree_view.scroll_value_ = std::clamp(
1013 *tree_view.scroll_value_, 0, tot_items - *visible_row_count);
1014 }
1015
1016 if (tree_view.scroll_active_into_view_on_draw_) {
1017 tree_view.scroll_active_into_view(nullptr);
1018 }
1019
1020 const int first_visible_index = tree_view.scroll_value_ ? *tree_view.scroll_value_ : 0;
1021 const int max_visible_index = visible_row_count ? first_visible_index + *visible_row_count - 1 :
1022 std::numeric_limits<int>::max();
1023 int index = 0;
1024 tree_view.foreach_item(
1025 [&, this](AbstractTreeViewItem &item) {
1026 if ((index >= first_visible_index) && (index <= max_visible_index)) {
1027 if (item.is_filtered_visible()) {
1028 this->build_row(item);
1029 }
1030 }
1031 index++;
1032 },
1034
1035 if (tree_view.custom_height_) {
1036
1037 *tree_view.custom_height_ = visible_row_count.value_or(1) * padded_item_height();
1038 if (!tree_view.scroll_value_) {
1039 tree_view.scroll_value_ = std::make_unique<int>(0);
1040 }
1041
1042 Button *but = nullptr;
1043 if (visible_row_count && (tot_items > *visible_row_count)) {
1044 row.column(false);
1045 but = uiDefButV(block,
1047 "",
1048 0,
1049 0,
1051 *tree_view.custom_height_,
1052 tree_view.scroll_value_.get(),
1053 0,
1054 tot_items - *visible_row_count,
1055 "");
1056 auto *but_scroll = reinterpret_cast<ButtonScrollBar *>(but);
1057 but_scroll->visual_height = *visible_row_count;
1058 }
1059
1061
1062 /* Bottom */
1063 Layout &bottom = col.row(false);
1065 but = uiDefIconButBit(block,
1067 1,
1068 ICON_DISCLOSURE_TRI_DOWN,
1069 0,
1070 0,
1071 UI_UNIT_X,
1072 UI_UNIT_Y * 0.5,
1073 tree_view.show_display_options_.get(),
1074 0,
1075 0,
1076 TIP_(""));
1079 bottom.column(false);
1080
1083 ICON_GRIP,
1084 0,
1085 0,
1086 UI_UNIT_X * 10,
1087 UI_UNIT_Y * 0.5f,
1088 tree_view.custom_height_.get(),
1089 0,
1090 0,
1091 "");
1092
1093 if (*tree_view.show_display_options_) {
1094 Layout &filter_layout = col.row(true);
1096 but = uiDefBut(block,
1098 "",
1099 0,
1100 0,
1101 UI_UNIT_X * 10,
1102 UI_UNIT_Y,
1103 tree_view.search_string_.get(),
1104 0,
1106 "");
1109 def_but_icon(but, ICON_VIEWZOOM, UI_HAS_ICON);
1110 button_placeholder_set(but, IFACE_("Search"));
1111
1112 but = uiDefIconButBit(
1113 block,
1115 1,
1116 ICON_ARROW_LEFTRIGHT,
1117 0,
1118 0,
1119 UI_UNIT_X,
1120 UI_UNIT_Y,
1121 tree_view.invert_search_filter_.get(),
1122 0,
1123 0,
1124 TIP_("Invert search results (Show items that don't match the search string)"));
1126
1127 filter_layout.separator();
1128 but = uiDefIconButBit(block,
1130 1,
1131 ICON_SORTALPHA,
1132 0,
1133 0,
1134 UI_UNIT_X,
1135 UI_UNIT_Y,
1136 tree_view.sort_alpha_.get(),
1137 0,
1138 0,
1139 TIP_("Sort items alphabetically"));
1141
1142 int icon = ICON_SORT_DESC;
1143 switch (*tree_view.invert_sort_type_) {
1145 icon = ICON_DOWNARROW_HLT;
1146 break;
1148 icon = ICON_SORT_ASC;
1149 break;
1150 default:
1151 break;
1152 }
1153
1154 but = uiDefIconBut(block,
1156 icon,
1157 0,
1158 0,
1159 UI_UNIT_X,
1160 UI_UNIT_Y,
1161 nullptr,
1162 0,
1163 0,
1164 TIP_("Reverse the order of items"));
1165 button_func_set(but, set_sort_order_fn, nullptr, tree_view.invert_sort_type_.get());
1166 button_func_pushed_state_set(but, [&](const ui::Button & /*button*/) {
1167 return *tree_view.invert_sort_type_ != TreeViewSortOrder::None;
1168 });
1170 }
1171 }
1172
1173 block_layout_set_current(block, &parent_layout);
1174}
1175
1177{
1178 Block &block_ = block();
1179
1180 Layout &prev_layout = current_layout();
1181
1182 const int width = prev_layout.width();
1183 if (width < int(40 * UI_SCALE_FAC)) {
1184 return;
1185 }
1186
1187 EmbossType previous_emboss = block_emboss_get(&block_);
1188
1189 Layout &overlap = prev_layout.overlap();
1190
1191 if (!item.is_interactive_) {
1192 overlap.active_set(false);
1193 }
1194
1195 Layout *row = &overlap.row(false);
1196 /* Enable emboss for mouse hover highlight. Only emboss real items, otherwise
1197 * the list gets filled with empty slots (visible when list item background is non-transparent),
1198 * see: !160795 */
1200 /* Every item gets one! Other buttons can be overlapped on top. */
1201 item.add_treerow_button(block_);
1202
1203 /* After adding tree-row button (would disable hover highlighting). */
1205
1206 /* Add little margin to align actual contents vertically. */
1207 Layout &content_col = overlap.column(true);
1208 const int margin_top = (padded_item_height() - unpadded_item_height()) / 2;
1209 if (margin_top > 0) {
1210 uiDefBut(&block_, ButtonType::Label, "", 0, 0, UI_UNIT_X, margin_top, nullptr, 0, 0, "");
1211 }
1212 row = &content_col.row(true);
1213
1215 item.add_indent(*row);
1216 item.add_collapse_chevron(block_);
1217
1218 if (item.is_renaming()) {
1219 item.add_rename_button(*row);
1220 }
1221 else {
1222 item.build_row(*row);
1223 if (item.is_active_) {
1225 }
1226 }
1227
1229
1230 block_emboss_set(&block_, previous_emboss);
1231 block_layout_set_current(&block_, &prev_layout);
1232}
1233
1235{
1236 return block_;
1237}
1238
1240{
1241 return *block().curlayout;
1242}
1243
1244/* ---------------------------------------------------------------------- */
1245
1246void TreeViewBuilder::ensure_min_rows_items(AbstractTreeView &tree_view)
1247{
1248 const std::optional<int> visible_rows = tree_view.tot_visible_row_count();
1249 if (!visible_rows) {
1250 return;
1251 }
1252
1253 int tot_visible_items = 0;
1254 tree_view.foreach_item(
1255 [&tot_visible_items](AbstractTreeViewItem & /*item*/) { tot_visible_items++; },
1257
1258 if (tot_visible_items >= *visible_rows) {
1259 return;
1260 }
1261
1262 for (int i = 0; i < (*visible_rows - tot_visible_items); i++) {
1263 BasicTreeViewItem &new_item = tree_view.add_tree_item<BasicTreeViewItem>("");
1264 new_item.disable_interaction();
1265 }
1266}
1267
1269 AbstractTreeView &tree_view,
1270 Layout &layout,
1271 const bool add_box)
1272{
1273 Block &block = *layout.block();
1274
1276 if (region) {
1277 block_view_persistent_state_restore(*region, block, tree_view);
1278 }
1279
1280 tree_view.build_tree();
1281 tree_view.update_from_old(block);
1282 tree_view.change_state_delayed();
1283
1284 if (*tree_view.sort_alpha_) {
1285 tree_view.sort_alpha();
1286 }
1287
1288 /* Separately sorting alphabetically and inverting seems like redundant work that could be done
1289 * in one sort pass. But `std::sort` or `std::stable_sort` can't handle the case where only
1290 * inverting needs to be done (unless items also store their initial index) since they need to be
1291 * able to compare any two items to define their relative order. When doing alphabetic sorting
1292 * the inverting could be done as part of that, but then there would still have to be a separate
1293 * code path for inverting only.
1294 *
1295 * Inverting is rather cheap (`O(n)`) and works well with CPU caching, so it's all not worth the
1296 * extra complexity. */
1297 tree_view.sort_inverted();
1298
1299 {
1300 /* Setup search string to filter out elements with matching characters. */
1301 char string[UI_MAX_NAME_STR];
1302 BLI_strncpy_ensure_pad(string, tree_view.search_string_.get(), '*', sizeof(string));
1303 tree_view.filter(tree_view.search_string_ ? std::optional{string} : std::nullopt);
1304 }
1305 ensure_min_rows_items(tree_view);
1306
1307 /* Ensure the given layout is actually active. */
1308 block_layout_set_current(&block, &layout);
1309
1310 TreeViewLayoutBuilder builder(layout);
1311 builder.add_box_ = add_box;
1313 builder.build_from_tree(tree_view);
1315}
1316
1317/* ---------------------------------------------------------------------- */
1318
1323
1325{
1326 this->add_label(row);
1327}
1328
1330{
1331 const StringRefNull label = label_override.is_empty() ? StringRefNull(label_) : label_override;
1332 layout.label(label, icon);
1333}
1334
1335void BasicTreeViewItem::on_activate(bContext &C)
1336{
1337 if (activate_fn_) {
1338 activate_fn_(C, *this);
1339 }
1340}
1341
1346
1348{
1349 is_active_fn_ = is_active_fn;
1350}
1351
1352std::optional<bool> BasicTreeViewItem::should_be_active() const
1353{
1354 if (is_active_fn_) {
1355 return is_active_fn_();
1356 }
1357 return std::nullopt;
1358}
1359
1360} // namespace blender::ui
#define TIP_(msgid)
#define IFACE_(msgid)
#define UI_SCALE_FAC
#define UI_INV_SCALE_FAC
#define UI_ICON_SIZE
#define C
Definition RandGen.cpp:29
#define UI_UNIT_Y
#define UI_UNIT_X
#define UI_MAX_NAME_STR
#define V2D_SCROLL_WIDTH
Definition UI_view2d.hh:79
#define BLI_assert_unreachable()
#define SET_FLAG_FROM_TEST(value, test, flag)
#define BLI_assert(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
Span< Value > lookup(const Key &key) const
void add(const Key &key, const Value &value)
constexpr const char * c_str() const
constexpr StringRefNull()
constexpr bool is_empty() const
Abstract base class for defining a customizable tree-view item.
std::optional< rctf > get_win_rect(const ARegion &region) const
Definition tree_view.cc:780
void update_from_old(const AbstractViewItem &old) override
Definition tree_view.cc:741
AbstractTreeViewItem * get_child()
Definition tree_view.cc:807
AbstractTreeView & get_tree_view() const
Definition tree_view.cc:775
std::unique_ptr< DropTargetInterface > create_item_drop_target() final
Definition tree_view.cc:760
StringRef get_rename_string() const override
Definition tree_view.cc:728
bool matches(const AbstractViewItem &other) const override
Definition tree_view.cc:916
void toggle_collapsed_from_view(bContext &C)
Definition tree_view.cc:840
virtual void build_row(Layout &row)=0
virtual std::unique_ptr< TreeViewItemDropTarget > create_drop_target()
Definition tree_view.cc:765
virtual void on_collapse_change(bContext &C, bool is_collapsed)
Definition tree_view.cc:860
virtual std::optional< bool > should_be_collapsed() const
Definition tree_view.cc:865
AbstractTreeViewItem * get_parent()
Definition tree_view.cc:802
virtual bool set_collapsed(bool collapsed)
Definition tree_view.cc:847
virtual bool matches_single(const AbstractTreeViewItem &other) const
Definition tree_view.cc:755
bool should_be_filtered_visible(StringRefNull filter_string) const override
Definition tree_view.cc:749
std::optional< std::string > debug_name() const override
Definition tree_view.cc:770
virtual bool supports_collapsing() const
Definition tree_view.cc:723
bool rename(const bContext &C, StringRefNull new_name) override
Definition tree_view.cc:733
StringRefNull label() const
Definition tree_view.cc:951
void scroll(ViewScrollDirection direction) override
Definition tree_view.cc:508
void foreach_root_item(ItemIterFn iter_fn) const
Definition tree_view.cc:132
bool is_fully_visible() const override
Definition tree_view.cc:503
void scroll_active_into_view(bContext *C, bool scroll_active_to_center=false) override
Definition tree_view.cc:517
void persistent_state_apply(const uiViewState &state) override
Definition tree_view.cc:265
void draw_overlays(const ARegion &region, const Block &block) const override
Definition tree_view.cc:430
TreeViewSortOrder invert_sort_type_get() const
Definition tree_view.cc:370
void foreach_item(ItemIterFn iter_fn, IterOptions options=IterOptions::None) const
Definition tree_view.cc:127
std::optional< uiViewState > persistent_state() const override
Definition tree_view.cc:242
void set_default_rows(int default_rows)
Definition tree_view.cc:234
virtual void update_from_old(const AbstractViewItem &old)
virtual bool should_be_filtered_visible(StringRefNull filter_string) const
virtual std::optional< bool > should_be_active() const
ui::ButtonViewItem * view_item_button() const
ui::ButtonViewItem * view_item_but_
virtual bool supports_scrolling() const
virtual void change_state_delayed()
void register_item(AbstractViewItem &item)
void update_from_old(Block &new_block)
virtual AbstractViewItem * find_active_or_visible_item() const =0
void filter(std::optional< StringRef > filter_str)
void add_label(Layout &layout, StringRefNull label_override="")
BasicTreeViewItem(StringRef label, BIFIconID icon=ICON_NONE)
std::function< bool()> IsActiveFn
std::function< void(bContext &C, BasicTreeViewItem &new_active)> ActivateFn
void set_is_active_fn(IsActiveFn is_active_fn)
void set_on_activate_fn(ActivateFn fn)
void build_row(Layout &row) override
static void build_tree_view(const bContext &C, AbstractTreeView &tree_view, Layout &layout, bool add_box=true)
ItemT & add_tree_item(Args &&...args)
AbstractTreeViewItem * parent_
TreeViewItemContainer * root_
void foreach_item_recursive(ItemIterFn iter_fn, IterOptions options=IterOptions::None) const
Definition tree_view.cc:67
void foreach_sort_invert(TreeViewSortOrder order)
Definition tree_view.cc:109
Vector< std::unique_ptr< AbstractTreeViewItem > > children_
void foreach_parent(ItemIterFn iter_fn) const
Definition tree_view.cc:87
FunctionRef< void(AbstractTreeViewItem &)> ItemIterFn
AbstractTreeViewItem & view_item_
TreeViewItemDropTarget(AbstractTreeViewItem &view_item, DropBehavior behavior=DropBehavior::Insert)
Definition tree_view.cc:557
std::optional< DropLocation > choose_drop_location(const ARegion &region, const wmEvent &event) const override
Definition tree_view.cc:563
void build_from_tree(AbstractTreeView &tree_view)
Definition tree_view.cc:993
void build_row(AbstractTreeViewItem &item) const
CCL_NAMESPACE_BEGIN struct Options options
#define index(i)
const int state
T max(const T &a, const T &b)
static int unpadded_item_height()
Definition tree_view.cc:32
AbstractViewItem * region_views_find_item_at(const ARegion &region, const int xy[2])
void button_func_set(Button *but, std::function< void(bContext &)> func)
int uiLayoutListItemPaddingWidth()
void button_func_pushed_state_set(Button *but, std::function< bool(const Button &)> func)
void block_flag_enable(Block *block, int flag)
static int count_visible_items(AbstractTreeView &tree_view)
Definition tree_view.cc:978
Button * uiDefIconButV(Block *block, ButtonType type, int icon, int x, int y, short width, short height, T *poin, float min, float max, std::optional< StringRef > tip)
const uiStyle * style_get_dpi()
static int padded_item_height()
Definition tree_view.cc:36
EmbossType block_emboss_get(Block *block)
static void set_sort_order_fn(bContext *, void *, void *arg2)
Definition tree_view.cc:987
void button_flag_enable(Button *but, int64_t flag)
Button * uiDefBut(Block *block, ButtonTypeWithPointerType but_and_ptr_type, StringRef str, int x, int y, short width, short height, void *poin, float min, float max, std::optional< StringRef > tip)
void block_to_window_rctf(const ARegion *region, const Block *block, rctf *rct_dst, const rctf *rct_src)
Definition interface.cc:172
void button_placeholder_set(Button *but, StringRef placeholder_text)
void button_to_pixelrect(rcti *rect, const ARegion *region, const Block *block, const Button *but)
TreeViewItemContainer TreeViewOrItem
void block_emboss_set(Block *block, EmbossType emboss)
void block_flag_disable(Block *block, int flag)
void layout_list_set_labels_active(Layout *layout)
void button_flag_disable(Button *but, int64_t flag)
static ButtonViewItem * find_first_view_item_but(const Block &block, const AbstractTreeView &view)
Definition tree_view.cc:374
void def_but_icon(Button *but, const int icon, const int64_t flag)
Button * uiDefIconBut(Block *block, ButtonTypeWithPointerType but_and_ptr_type, int icon, int x, int y, short width, short height, void *poin, float min, float max, std::optional< StringRef > tip)
Button * uiDefIconButBit(Block *block, ButtonType type, int bit, int icon, int x, int y, short width, short height, T *poin, float min, float max, std::optional< StringRef > tip)
Button * uiDefButV(Block *block, ButtonType type, StringRef str, int x, int y, short width, short height, T *poin, float min, float max, std::optional< StringRef > tip)
void uiLayoutListItemAddPadding(Layout *layout)
void block_layout_set_current(Block *block, Layout *layout)
void block_view_persistent_state_restore(const ARegion &region, const Block &block, AbstractView &view)
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
char * STRNCPY(char(&dst)[N], const char *src)
void immEnd()
int char char int int int BLI_strcasecmp_natural(const char *s1, const char *s2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
unsigned int uint
Definition BKE_text.h:55
MINLINE int round_fl_to_int(float a)
GPUVertFormat * immVertexFormat()
void immBegin(GPUPrimType, uint vertex_len)
wmWindow * CTX_wm_window(const bContext *C)
void immUniformThemeColorAlpha(int color_id, float a)
void immUnbindProgram()
char char * BLI_strncpy_ensure_pad(char *__restrict dst, const char *__restrict src, char pad, size_t dst_maxncpy) ATTR_NONNULL(1
void GPU_line_width(float width)
Definition gpu_state.cc:151
@ GPU_BLEND_NONE
Definition GPU_state.hh:88
@ GPU_BLEND_ALPHA
Definition GPU_state.hh:90
void immBindBuiltinProgram(GPUBuiltinShader shader_id)
BLI_INLINE int BLI_rcti_size_y(const struct rcti *rct)
Definition BLI_rect.hh:207
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
VecBase< int32_t, 2 > int2
void immVertex2f(uint attr_id, float x, float y)
BLI_INLINE float BLI_rctf_size_y(const struct rctf *rct)
Definition BLI_rect.hh:215
unsigned char uint8_t
Definition BKE_text.h:79
@ UI_VIEW_SHOW_FILTER_OPTIONS
uint GPU_vertformat_attr_add(GPUVertFormat *format, StringRef name, gpu::VertAttrType type)
int BIFIconID
Definition ED_asset.hh:30
ARegion * CTX_wm_region_popup(const bContext *C)
void GPU_blend(GPUBlend blend)
Definition gpu_state.cc:44
ARegion * CTX_wm_region(const bContext *C)
std::string format(const std::string &fmt, Args &&...args)
Definition diagnostic.hh:43
PipelineCompute lines(lines_main)
std::ranges::transform_view< std::ranges::ref_view< const Vector< std::unique_ptr< Button > > >, Button &(*)(const std::unique_ptr< Button > &)> buttons() const
void label(StringRef name, int icon)
void active_set(bool active)
Layout & column(bool align)
void separator(float factor=1.0f, LayoutSeparatorType type=LayoutSeparatorType::Auto)
Layout & row(bool align)
void emboss_set(EmbossType emboss)
short buttonspacey
#define MIN_ROWS
Definition tree_view.cc:30
#define UI_TREEVIEW_INDENT
Definition tree_view.cc:29