Skip to main content

nsh_core/core/
pace.rs

1//! A turn that makes hundreds of views out of sight spreads them over
2//! frames, on every platform.
3//!
4//! A list row bound in the overscan, or a long reply staged into a chat,
5//! makes its whole subtree in one batch: hundreds of native views nobody
6//! sees yet, created, styled and committed by the platform in one frame
7//! (423 views took one 87 ms frame on macOS). Lists pace their overscan
8//! cells already ([`Core::take_paced_list_binds`]), one cell at a time;
9//! this paces the views inside them, and the content of scroll views.
10//!
11//! Once a turn has made [`PACE_AFTER`] views, a view about to be made
12//! under a scroll view or a list cell waits instead, culled as content
13//! culling holds views back (`cull.rs`): the core keeps laying it out and
14//! giving it a frame, and a command for it makes it at once
15//! ([`Core::uncull`]). After each layout, [`Core::sync_paced`] makes the
16//! waiting views that show (their frame meets the viewport of every scroll
17//! view and list around them) at once, a level at a time down to their
18//! leaves, so nothing visible is late; while the user scrolls, where the
19//! scroll is in its next frame counts as showing. The rest come in later
20//! turns, nearest the viewport first, at most [`PACE_VIEWS`] views or
21//! [`PACE_TIME`] a turn, in the turns of display frames only
22//! ([`Core::hold_paced_mounts`]); the core asks for a display frame while some
23//! wait ([`Core::has_paced_mounts`]). A list's cell that waits has made
24//! none of its views: the list places them with the cell (`update_lists`),
25//! so they are ranked by where they are when the cell is made, not last
26//! as views without a frame are.
27//!
28//! Content culling's own window ([`Core::sync_culled`]) keeps the same
29//! budget: the overscan it makes past [`PACE_AFTER`] waits for later turns
30//! too, what shows is made at once.
31//!
32//! Views not made yet are not in the platform's accessibility tree, as
33//! culled content is not: they are out of sight, and come within a few
34//! frames. Text selection and select-all read the core's nodes, not the
35//! native views. A test driver turns content culling off
36//! ([`Core::set_content_culling`]), which turns pacing off: what waits is
37//! made in the next commit, so its steps reach every view.
38//!
39//! Nothing waits that may show away from its frame or lays out on its own
40//! ([`Core::never_culled`]: sticky, followers, overlays, screens, modals,
41//! views scaled, rotated or moved by a value of no known bound), nor
42//! anything outside scroll views and lists, whose content shows wherever
43//! its frame is. A view translated by a bounded value (an entrance's slide,
44//! `animation/reach.rs`) waits like any other, its rectangle widened by
45//! how far it may move.
46
47use std::time::Duration;
48
49use super::{Core, Key, Kind, NO_KEY};
50use crate::{text::TextEngine, time::Instant};
51
52/// Views a turn makes before views out of sight start to wait.
53pub(super) const PACE_AFTER: usize = 64;
54
55/// Waiting views out of sight a turn makes at most. Most of a view's cost
56/// is the platform's (creating it, and the commit that sends its layer to
57/// the compositor): about 0.2 ms a view all told on macOS, so 32 keep a
58/// frame near 7 ms.
59pub(super) const PACE_VIEWS: usize = 32;
60
61/// The time a turn spends making waiting views out of sight.
62pub(super) const PACE_TIME: Duration = Duration::from_millis(4);
63
64/// What [`Core`] keeps for pacing.
65#[derive(Debug, Default)]
66pub(super) struct Pace {
67    /// Views made in this turn.
68    pub(super) made: usize,
69    /// Waiting views out of sight made in this turn.
70    paced: usize,
71    /// When the turn began making waiting views.
72    started: Option<Instant>,
73    /// The engine says when a turn begins ([`Core::begin_mount_turn`]):
74    /// otherwise each commit is one.
75    in_turn: bool,
76    /// Every view about to be made waits (while [`Core::sync_paced`]
77    /// makes one: its children are ranked on their own).
78    holding: bool,
79    /// Waiting views whose parent is made (by key; their ids tell a slot
80    /// taken by another node).
81    pub(super) waiting: Vec<(Key, crate::NodeId)>,
82    /// Content culling left views it would have made for the budget.
83    pub(super) culled_waiting: bool,
84}
85
86impl Pace {
87    /// Whether the turn may make another waiting view out of sight.
88    fn left(&self) -> bool {
89        self.paced < PACE_VIEWS && self.started.is_none_or(|s| s.elapsed() < PACE_TIME)
90    }
91}
92
93impl<M: TextEngine> Core<M> {
94    /// A turn of the engine begins: the commits up to the next one share
95    /// one budget of views. Without it, every commit is a turn.
96    pub fn begin_mount_turn(&mut self) {
97        self.pace.in_turn = true;
98        self.reset_pace();
99        self.reset_list_motion();
100    }
101
102    /// This turn is not a display frame's: waiting views out of sight stay
103    /// waiting, for the next frame's turn (what shows is still made at
104    /// once). Call after [`Core::begin_mount_turn`]. Without it, every
105    /// turn makes a slice of what waits, and the turns between two frames
106    /// (a timer, a message from the main thread) each commit one more.
107    pub fn hold_paced_mounts(&mut self) {
108        // Views waited when the turn began (`reset_pace`: content culling's
109        // flag is cleared by then, for its window to be worked out again).
110        if self.pace.made >= PACE_AFTER {
111            self.pace.paced = PACE_VIEWS;
112        }
113    }
114
115    /// Whether views wait to be made in a later turn: ask the platform for
116    /// a display frame, and commit in it.
117    pub fn has_paced_mounts(&self) -> bool {
118        !self.pace.waiting.is_empty() || self.pace.culled_waiting
119    }
120
121    /// The start of a commit: a new budget unless the engine counts turns.
122    pub(super) fn pace_commit(&mut self) {
123        if !self.pace.in_turn {
124            self.reset_pace();
125            self.reset_list_motion();
126        }
127    }
128
129    fn reset_pace(&mut self) {
130        // Views waiting from an earlier turn: this one has their budget
131        // only, nothing more made first.
132        self.pace.made = if self.has_paced_mounts() {
133            PACE_AFTER
134        } else {
135            0
136        };
137        self.pace.paced = 0;
138        self.pace.started = None;
139        if std::mem::take(&mut self.pace.culled_waiting) {
140            self.cull_dirty = true;
141        }
142    }
143
144    /// Whether content culling may make a view in its window that does not
145    /// show: within the budget. Counts it when it may.
146    pub(super) fn pace_overscan(&mut self) -> bool {
147        if !self.culls_content || self.pace.made < PACE_AFTER {
148            return true;
149        }
150        if self.pace.started.is_none() {
151            self.pace.started = Some(Instant::now());
152        }
153        if self.pace.left() {
154            self.pace.paced += 1;
155            true
156        } else {
157            self.pace.culled_waiting = true;
158            false
159        }
160    }
161
162    /// Holds back `child`, about to be made in its made parent, when the
163    /// turn has made enough views and it may wait; whether it was.
164    pub(super) fn pace_hold(&mut self, child: Key) -> bool {
165        if !self.culls_content
166            || (!self.pace.holding && self.pace.made < PACE_AFTER)
167            || self.nodes[child as usize].created
168            || self.never_culled(child)
169            || !self.paces_in(self.nodes[child as usize].parent)
170        {
171            return false;
172        }
173        let node = &mut self.nodes[child as usize];
174        node.culled = true;
175        let id = node.id;
176        self.pace.waiting.push((child, id));
177        true
178    }
179
180    /// Whether views made in `parent` may wait: it is in a scroll view or a
181    /// list's cell, whose content shows only within its viewport.
182    fn paces_in(&self, mut key: Key) -> bool {
183        // A terminal's views are its Cells, as cheap as the core's nodes.
184        if self.layout.grid().is_some() {
185            return false;
186        }
187        while key != NO_KEY {
188            let node = &self.nodes[key as usize];
189            if node.kind == Kind::Scroll || node.kind == Kind::Cell {
190                return true;
191            }
192            if node.is_layout_root() {
193                return false;
194            }
195            key = node.parent;
196        }
197        false
198    }
199
200    /// How far waiting `key`'s frame is from showing, in points: 0 when it
201    /// meets the viewport of every scroll view and list around it, or when
202    /// that cannot be told (it is empty, or a zoom or a transform of no
203    /// known reach is between it and the viewport), so it is made now; the
204    /// most when it has no frame (not laid out). A transform whose reach is
205    /// known (`Core::reach_of`) widens its rectangle by as much.
206    fn sight(&self, key: Key) -> f32 {
207        let node = &self.nodes[key as usize];
208        let f = node.frame;
209        let (x, y, w, h) = (f.origin.x.0, f.origin.y.0, f.size.width.0, f.size.height.0);
210        // Not laid out (a cell the list did not place): last, within the
211        // budget.
212        if !(x.is_finite() && y.is_finite()) {
213            return f32::MAX;
214        }
215        // Empty: what it holds may overflow it.
216        if w <= 0.0 || h <= 0.0 {
217            return 0.0;
218        }
219        // Widened by how far its transform may move it (`Core::reach_of`).
220        let Some((rx, ry)) = self.reach_of(key) else {
221            return 0.0;
222        };
223        let mut r = (x - rx, y - ry, x + w + rx, y + h + ry);
224        let mut far = 0.0f32;
225        let mut k = node.parent;
226        while k != NO_KEY {
227            let n = &self.nodes[k as usize];
228            let f = n.frame;
229            let moves = self.reach_of(k);
230            if !n.created
231                || !(f.origin.x.0.is_finite() && f.origin.y.0.is_finite())
232                || moves.is_none()
233            {
234                // Past the viewports met so far, nothing moves the view
235                // within them.
236                return far;
237            }
238            let (w, h) = (f.size.width.0, f.size.height.0);
239            let (mut ox, mut oy) = (0.0, 0.0);
240            if let Some(list) = n.list.as_ref().filter(|l| !l.parent) {
241                // A list's cells are placed in its content.
242                let inf = f32::INFINITY;
243                let view = if list.horizontal {
244                    ox = list.offset;
245                    (list.offset, -inf, list.offset + w, inf)
246                } else {
247                    oy = list.offset;
248                    (-inf, list.offset, inf, list.offset + h)
249                };
250                far = far.max(gap(r, view));
251            } else if n.kind == Kind::Scroll {
252                let Some(scroll) = n.scroll.as_deref() else {
253                    return far;
254                };
255                if scroll.behavior.zooms() {
256                    return far;
257                }
258                (ox, oy) = scroll.offset;
259                // Where the scroll goes in its next frames shows as soon.
260                let sight =
261                    scroll
262                        .lead(w, h, super::cull::SIGHT_STEPS)
263                        .widen((ox, oy, ox + w, oy + h));
264                far = far.max(gap(r, sight));
265            }
266            let (dx, dy) = (f.origin.x.0 - ox, f.origin.y.0 - oy);
267            // Its own transform moves all of it, its viewport included.
268            let (mx, my) = moves.unwrap_or_default();
269            r = (r.0 + dx - mx, r.1 + dy - my, r.2 + dx + mx, r.3 + dy + my);
270            if n.is_layout_root() && n.kind != Kind::Cell {
271                break;
272            }
273            k = n.parent;
274        }
275        far
276    }
277
278    /// Makes the waiting views that show, down to their leaves, then as
279    /// many of the others as the budget allows, nearest first; whether it
280    /// made any (their styles, texts and images go out in another round).
281    pub(super) fn sync_paced(&mut self) -> bool {
282        let mut made = false;
283        let mut ranked: Vec<(f32, Key)> = Vec::new();
284        loop {
285            let waiting = std::mem::take(&mut self.pace.waiting);
286            if waiting.is_empty() {
287                break;
288            }
289            ranked.clear();
290            for (key, id) in waiting {
291                let Some(node) = self.nodes.get(key as usize) else {
292                    continue;
293                };
294                // Made by now, gone, or its parent given up (its parent
295                // holds it back again when it is made). Taken out of its
296                // parent, or its parent released, it has none: it waits
297                // again when it is inserted somewhere.
298                if node.id != id
299                    || node.created
300                    || !node.culled
301                    || node.layout.is_none()
302                    || !self
303                        .nodes
304                        .get(node.parent as usize)
305                        .is_some_and(|parent| parent.created)
306                    || !self.in_tree(key)
307                {
308                    continue;
309                }
310                let far = if self.culls_content {
311                    self.sight(key)
312                } else {
313                    0.0
314                };
315                ranked.push((far, key));
316            }
317            ranked.sort_by(|a, b| a.0.total_cmp(&b.0));
318            let mut shown = false;
319            for &(far, key) in &ranked {
320                if far > 0.0 {
321                    if self.pace.started.is_none() {
322                        self.pace.started = Some(Instant::now());
323                    }
324                    if !self.pace.left() {
325                        let id = self.nodes[key as usize].id;
326                        self.pace.waiting.push((key, id));
327                        continue;
328                    }
329                    self.pace.paced += 1;
330                } else {
331                    shown = true;
332                }
333                // One view: its children wait, ranked in the next pass.
334                self.pace.holding = true;
335                let node = &self.nodes[key as usize];
336                let parent = node.parent;
337                // Held back in a view the layout walked past unmade (a
338                // list's cell, #1783): no frame, and nothing may lay the
339                // tree out again.
340                let unplaced = node.frame.origin.x.0.is_nan() && !node.is_layout_root();
341                self.make_culled(parent, key);
342                self.pace.holding = false;
343                if unplaced {
344                    self.emit_frames(key);
345                }
346                made = true;
347            }
348            // Only what shows goes down a level in this turn; the rest
349            // waits for the budget.
350            if !shown {
351                break;
352            }
353        }
354        made
355    }
356}
357
358/// How far rect `r` is from rect `view` (left, top, right, bottom), in
359/// points: 0 when they meet.
360fn gap(r: (f32, f32, f32, f32), view: (f32, f32, f32, f32)) -> f32 {
361    (view.0 - r.2)
362        .max(r.0 - view.2)
363        .max(view.1 - r.3)
364        .max(r.1 - view.3)
365        .max(0.0)
366}