Skip to main content

egui_pop_fit/
group.rs

1//! Groups: runs of consecutive elements packed apart from the rest, like
2//! the controls of an HTML `fieldset` under its legend.
3
4use crate::layout::{GridRect, PointRect};
5use core::ops::Range;
6
7/// A run of consecutive elements packed apart from the rest.
8///
9/// Packing stays dense within a group, but order is strict across groups:
10/// a group starts on a new band of rows below everything before it, and
11/// nothing after it moves up into one of its gaps. Loose elements (in no
12/// group) between two groups form a band of their own, packed densely
13/// too.
14///
15/// A group may hold groups, to any depth, as long as each lies wholly
16/// within its parent's members. An empty group holds nothing and draws no
17/// frame, but still splits the loose elements around it into two bands:
18/// it is a barrier.
19#[derive(Clone, Debug, PartialEq, Eq, Hash)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct Group {
22    /// The caller's key for the group.
23    pub key: u64,
24    /// Its elements, as a range of indices into the element slice.
25    pub range: Range<usize>,
26    /// Whether its first element is a header (a legend), placed alone on
27    /// the group's first band, before its other members.
28    pub header: bool,
29}
30
31impl Group {
32    /// A group of the elements in `range`, with no header.
33    pub fn new(key: u64, range: Range<usize>) -> Group {
34        Group {
35            key,
36            range,
37            header: false,
38        }
39    }
40
41    /// The same group with its first element as its header.
42    pub fn with_header(mut self) -> Group {
43        self.header = true;
44        self
45    }
46
47    /// An empty group at `index`: a barrier between the elements before
48    /// it and from it on.
49    pub fn barrier(key: u64, index: usize) -> Group {
50        Group::new(key, index..index)
51    }
52
53    /// The index of its header element, if it has one.
54    pub(crate) fn header_index(&self) -> Option<usize> {
55        (self.header && !self.range.is_empty()).then_some(self.range.start)
56    }
57
58    /// The first index of its members (after its header).
59    pub(crate) fn members_start(&self) -> usize {
60        self.range.start + usize::from(self.header_index().is_some())
61    }
62}
63
64/// The result for one group.
65#[derive(Clone, Copy, Debug, PartialEq)]
66#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
67pub struct GroupPlacement {
68    /// The group's key.
69    pub key: u64,
70    /// The index, in the layout's groups, of the group holding it.
71    pub parent: Option<usize>,
72    /// Its band, in twelfths: the grid's whole width, from the top of its
73    /// first placed element (its header, if any) to the bottom of its
74    /// lowest one. `None` when nothing of it is placed.
75    pub rect: Option<GridRect>,
76    /// Its band, in points.
77    pub points: Option<PointRect>,
78    /// The row, in twelfths, its members' pins count from: just below its
79    /// header.
80    pub body_top: u32,
81    /// Set when the group was ignored: it reaches past the elements, or
82    /// it crosses another group's boundary or header. Its elements are
83    /// laid out as if it were not there.
84    pub ignored: bool,
85}
86
87/// A node of the group tree: an element, or a group of nodes.
88#[derive(Debug)]
89pub(crate) enum Node {
90    Element(usize),
91    Group {
92        /// Its index in the caller's groups.
93        index: usize,
94        header: Option<usize>,
95        children: Vec<Node>,
96    },
97}
98
99/// The tree of `count` elements under `groups`, and which groups were
100/// ignored. Each group's parent is the innermost valid group holding it.
101pub(crate) fn tree(count: usize, groups: &[Group]) -> (Vec<Node>, Vec<Option<usize>>, Vec<bool>) {
102    let mut order: Vec<usize> = (0..groups.len()).collect();
103    // Outer before inner: by start, then by the larger end.
104    order.sort_by_key(|&g| {
105        let r = &groups[g].range;
106        (r.start, core::cmp::Reverse(r.end), g)
107    });
108    let mut parent = vec![None; groups.len()];
109    let mut ignored = vec![false; groups.len()];
110    let mut stack: Vec<usize> = Vec::new();
111    for &g in &order {
112        let r = &groups[g].range;
113        if r.start > r.end || r.end > count {
114            ignored[g] = true;
115            continue;
116        }
117        // Close the groups that end before this one starts.
118        while let Some(&top) = stack.last() {
119            if r.start >= groups[top].range.end && !inside(&groups[g], &groups[top]) {
120                stack.pop();
121            } else {
122                break;
123            }
124        }
125        match stack.last() {
126            Some(&top) if !inside(&groups[g], &groups[top]) => ignored[g] = true,
127            top => {
128                parent[g] = top.copied();
129                stack.push(g);
130            }
131        }
132    }
133    let nodes = children(0, count, None, &order, groups, &parent, &ignored);
134    (nodes, parent, ignored)
135}
136
137/// Whether `g` lies within `outer`'s members.
138fn inside(g: &Group, outer: &Group) -> bool {
139    g.range.start >= outer.members_start() && g.range.end <= outer.range.end
140}
141
142/// The nodes for elements `lo..hi`, whose groups have parent `parent`.
143fn children(
144    lo: usize,
145    hi: usize,
146    parent: Option<usize>,
147    order: &[usize],
148    groups: &[Group],
149    parents: &[Option<usize>],
150    ignored: &[bool],
151) -> Vec<Node> {
152    let mut kids = order
153        .iter()
154        .copied()
155        .filter(|&g| !ignored[g] && parents[g] == parent)
156        .peekable();
157    let mut nodes = Vec::new();
158    let mut i = lo;
159    loop {
160        if let Some(&g) = kids.peek()
161            && groups[g].range.start <= i
162        {
163            kids.next();
164            let group = &groups[g];
165            nodes.push(Node::Group {
166                index: g,
167                header: group.header_index(),
168                children: children(
169                    group.members_start(),
170                    group.range.end,
171                    Some(g),
172                    order,
173                    groups,
174                    parents,
175                    ignored,
176                ),
177            });
178            i = i.max(group.range.end);
179            continue;
180        }
181        if i < hi {
182            nodes.push(Node::Element(i));
183            i += 1;
184        } else {
185            break;
186        }
187    }
188    nodes
189}