1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! The persistent node store: what a node keeps from one rebuild to the next.
//!
//! The tree is rebuilt from nothing every frame, so anything that must outlive
//! a frame — the pointer's hover and press, the layout cache, last frame's
//! rectangle — lives here, keyed by the node's [`NodeKey`], in a slab whose
//! slots a frame's nodes point into. A node no frame touched is pruned at
//! layout, and its slot goes back on the free list.
use std::collections::HashMap;
use glam::Vec2;
use taffy::{Cache, Layout};
use super::focus::{Behavior, Engagement, NavStep};
use super::style::{NavId, NodeStyle};
use super::widgets::{WidgetKind, WidgetState};
use crate::draw_list::ClipRect;
use crate::style::{Candidates, Declaration, InheritedId, PseudoClasses};
/// A node's identity across rebuilds.
///
/// `hash(parent key, explicit id or call site and occurrence)` — see
/// [`crate::tree`]'s key rules. Opaque apart from equality: two frames that
/// build the same node from the same place under the same parent give it the
/// same key, and nothing else about the number means anything.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeKey(pub(crate) u64);
/// The pointer's relation to one node, and its focus and engagement, resolved
/// against last frame's rectangles when a frame begins.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Interaction {
/// The pointer is over this node or over a node inside it, and no press
/// outside it is captured.
pub hovered: bool,
/// This node captured the press that is held.
pub pressed: bool,
/// This node captured a press that was released over it this frame, or
/// it is focused and was accepted without engaging.
pub clicked: bool,
/// This node holds its context's focus.
pub focused: bool,
/// Where this node's engagement is this frame.
pub engagement: Engagement,
/// The navigation step this engaged node took from focus this frame.
pub captured: Option<NavStep>,
}
/// Everything one node keeps between frames.
#[derive(Clone, Debug)]
pub(crate) struct StoredNode {
pub key: NodeKey,
/// The key of the node it was built under last, for walking a hover or a
/// capture up to the nodes that contain it.
pub parent: Option<NodeKey>,
/// The frame that last built this node. Anything older is pruned.
pub last_touched_frame: u64,
/// [`super::NodeStyle::layout_hash`] as last built.
pub style_hash: u64,
/// The keys of its children, in order, as last built.
pub child_hash: u64,
/// What a span measures from — its text and size, or its image — as last
/// built. Zero for a block.
pub content_hash: u64,
/// Taffy's per-node layout cache, which survives a rebuild unless one of
/// the three hashes above moved here or in a descendant.
pub cache: Cache,
/// Taffy's layout before rounding, relative to the parent. Kept here rather
/// than in the frame because a cache hit on an ancestor skips writing it.
pub unrounded: Layout,
/// Last layout's border box, in screen pixels; a paragraph's run's, the
/// box round its fragments.
pub rect: (Vec2, Vec2),
/// A paragraph's run's line fragments, in screen pixels, as last laid
/// out: what it is hit on in place of `rect`. Empty for every other node.
pub fragments: Vec<(Vec2, Vec2)>,
/// The clip its ancestors' `overflow: hidden` put it under.
pub clip: ClipRect,
/// Its place in last frame's build order: within one layer, a higher one
/// is drawn on top.
pub paint_order: usize,
/// The layer it was drawn in last frame: 0 for the tree, `n` for the
/// `n`th open pop-up, which is drawn over every lower layer whatever the
/// paint order says. See `popup.rs`.
pub layer: usize,
/// Whether it had a box last frame: `display: none` here or above is never
/// hit.
pub hittable: bool,
/// Whether it was drawn last frame where the pointer passes through it — a
/// tooltip's layer — so it is never hit, whatever `hittable` says.
pub inert: bool,
/// Whether its builder asked for a tooltip on it last frame
/// ([`super::Ui::tooltip`]): what makes it a tooltip's subject.
pub tooltip: bool,
/// Whether its builder asked for a context menu on it last frame
/// ([`super::Ui::context_menu`]): what a secondary press or `ui_menu`
/// opens one on.
pub context_menu: bool,
pub interaction: Interaction,
/// How it takes part in focus, as its builder declared it last.
pub behavior: Behavior,
/// The widget state its builder declared last — `:checked`, `:open` —
/// which the cascade matches beside the interaction's pseudo-classes.
pub state: PseudoClasses,
/// What a widget keeps on this node between frames; see
/// [`super::widgets`].
pub widget: WidgetState,
/// What its builder built it as this frame, for the accessibility tree.
pub kind: WidgetKind,
/// Its selector's `#id`, hashed, for a `nav-*` property to find.
pub id: Option<NavId>,
/// The node focused inside it last, for a scope root.
pub remembered: Option<NodeKey>,
/// How far its children are scrolled, subtracted from where they are laid
/// out. Set by the caller, and by the tree for an `overflow: scroll` block
/// that brings the focused node into view.
pub scroll_offset: Vec2,
/// How far an `overflow: scroll` block's content lets it scroll, as last
/// laid out; zero for any other block.
pub scroll_max: Vec2,
/// The candidate rules for its selector, and what they were gathered for.
pub candidates: Option<StoredCandidates>,
/// What its resolved style was keyed by last; see `resolve.rs`.
pub style_key: u64,
/// The inline declarations it was resolved with last.
pub inline: Vec<Declaration>,
/// Its resolved style as of `style_key`.
pub resolved: NodeStyle,
/// What it passed to its children as of `style_key`.
pub inherited: InheritedId,
}
/// A node's candidate rules, with the selector and stylesheet generation they
/// were gathered for.
#[derive(Clone, Debug)]
pub(crate) struct StoredCandidates {
pub selector: String,
pub span: bool,
pub generation: u64,
pub candidates: Candidates,
}
impl StoredNode {
fn new(key: NodeKey, frame: u64) -> Self {
Self {
key,
parent: None,
last_touched_frame: frame,
style_hash: 0,
child_hash: 0,
content_hash: 0,
cache: Cache::new(),
unrounded: Layout::new(),
rect: (Vec2::ZERO, Vec2::ZERO),
fragments: Vec::new(),
clip: ClipRect::NONE,
paint_order: 0,
layer: 0,
hittable: false,
inert: false,
tooltip: false,
context_menu: false,
interaction: Interaction::default(),
behavior: Behavior::NONE,
state: PseudoClasses::NONE,
widget: WidgetState::None,
kind: WidgetKind::None,
id: None,
remembered: None,
scroll_offset: Vec2::ZERO,
scroll_max: Vec2::ZERO,
candidates: None,
style_key: 0,
inline: Vec::new(),
resolved: NodeStyle::DEFAULT,
inherited: InheritedId::ROOT,
}
}
/// Last layout's content box, in screen pixels: the border box less the
/// border and the padding the layout resolved.
pub fn content_box(&self) -> (Vec2, Vec2) {
let (border, padding) = (self.unrounded.border, self.unrounded.padding);
(
self.rect.0 + Vec2::new(border.left + padding.left, border.top + padding.top),
self.rect.1 - Vec2::new(border.right + padding.right, border.bottom + padding.bottom),
)
}
/// Where it was drawn last frame, lowest first: its layer, then its paint
/// order within the layer. What every "topmost" is decided by.
pub fn stacking(&self) -> (usize, usize) {
(self.layer, self.paint_order)
}
/// Whether `pos` is inside the part of last frame's box — or of one of a
/// run's fragments — its clip let through. Half-open, so two boxes that
/// share an edge never both claim the pixel on it.
pub fn contains(&self, pos: Vec2) -> bool {
let inside = |&(min, max): &(Vec2, Vec2)| {
let visible = self.clip.intersect(ClipRect { min, max });
pos.cmpge(visible.min).all() && pos.cmplt(visible.max).all()
};
let hit = if self.fragments.is_empty() {
inside(&self.rect)
} else {
self.fragments.iter().any(inside)
};
self.hittable && !self.inert && hit
}
}
/// The slab of [`StoredNode`]s and the index from key to slot.
#[derive(Clone, Debug, Default)]
pub(crate) struct NodeStore {
slots: Vec<Option<StoredNode>>,
index: HashMap<NodeKey, usize>,
free: Vec<usize>,
}
impl NodeStore {
/// The slot holding `key`, if it is stored.
pub fn find(&self, key: NodeKey) -> Option<usize> {
self.index.get(&key).copied()
}
/// A fresh slot for `key`, touched in `frame`. The caller has checked that
/// `key` is not stored.
pub fn insert(&mut self, key: NodeKey, frame: u64) -> usize {
let node = Some(StoredNode::new(key, frame));
let slot = if let Some(slot) = self.free.pop() {
self.slots[slot] = node;
slot
} else {
self.slots.push(node);
self.slots.len() - 1
};
self.index.insert(key, slot);
slot
}
/// The node in `slot`.
///
/// # Panics
///
/// If the slot is free: every slot a frame node names was touched this
/// frame, and nothing prunes a touched slot.
pub fn get(&self, slot: usize) -> &StoredNode {
self.slots[slot]
.as_ref()
.expect("a frame node's slot is live until the next prune")
}
/// See [`NodeStore::get`].
pub fn get_mut(&mut self, slot: usize) -> &mut StoredNode {
self.slots[slot]
.as_mut()
.expect("a frame node's slot is live until the next prune")
}
/// The stored node for `key`.
pub fn by_key(&self, key: NodeKey) -> Option<&StoredNode> {
self.find(key).map(|slot| self.get(slot))
}
/// Every stored node.
pub fn iter(&self) -> impl Iterator<Item = &StoredNode> {
self.slots.iter().flatten()
}
/// Every stored node, mutably.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut StoredNode> {
self.slots.iter_mut().flatten()
}
/// Drops every node `frame` did not touch, and returns how many went.
pub fn prune(&mut self, frame: u64) -> usize {
let mut pruned = 0;
for (slot, entry) in self.slots.iter_mut().enumerate() {
if entry
.as_ref()
.is_some_and(|node| node.last_touched_frame != frame)
&& let Some(node) = entry.take()
{
self.index.remove(&node.key);
self.free.push(slot);
pruned += 1;
}
}
pruned
}
/// How many nodes are stored.
pub fn len(&self) -> usize {
self.index.len()
}
/// The topmost node whose visible box holds `pos`, and the keys of every
/// node that contains it, innermost first.
pub fn hit_chain(&self, pos: Vec2) -> Vec<NodeKey> {
let target = self
.iter()
.filter(|node| node.contains(pos))
.max_by_key(|node| node.stacking());
self.ancestry(target.map(|node| node.key))
}
/// Whether `key` is `ancestor` or was built under it, walking the same
/// chain [`NodeStore::ancestry`] does without collecting it.
pub fn is_within(&self, key: NodeKey, ancestor: NodeKey) -> bool {
let mut next = Some(key);
let mut steps = 0;
while let Some(key) = next {
if key == ancestor {
return true;
}
// The same bound `ancestry` walks under.
steps += 1;
if steps > self.len() {
break;
}
next = self.by_key(key).and_then(|node| node.parent);
}
false
}
/// `key` and the keys of every node it was built under, innermost first.
pub fn ancestry(&self, key: Option<NodeKey>) -> Vec<NodeKey> {
let mut chain = Vec::new();
let mut next = key;
while let Some(key) = next {
// A cycle cannot be built — a parent is always opened before its
// child in the same frame — but a chain longer than the store would
// be one, and walking it forever is the worse failure.
if chain.len() > self.len() {
break;
}
chain.push(key);
next = self.by_key(key).and_then(|node| node.parent);
}
chain
}
}