Skip to main content

taut/
scroll.rs

1//! Scroll boxes, as the app reads and drives them: how far one is scrolled, scrolling to a
2//! place, staying at the end as content grows (a chat, a log), bringing a box or a long list's
3//! row into view. Also a box's available size (to fit content to), the wheel over an app's own
4//! box, and long lists of rows of varying height.
5//!
6//! Requests are carried out where the library scrolls boxes, after layout (`Ui::scroll`): so
7//! they use this run's positions, and the window is described once more before anything is
8//! drawn. What the person does to a box comes before the app's request that it stay at its end:
9//! scrolled back, it stays where put.
10use crate::geom::Size;
11use crate::id::{ById, Id, hash};
12use crate::layout::{Length, NONE};
13use crate::ui::{Measure, Response, Ui};
14use std::ops::Range;
15
16/// The rows `first..end` of `count` rows (each `tall(row)` high) that show in a view `shown`
17/// high, `above` from the list's top; and the first one's top and the last one's bottom.
18fn rows_in_view(tall: impl Fn(usize) -> f64, count: usize, above: f64, shown: f64) -> ([usize; 2], [f64; 2]) {
19    let (mut first, mut top) = (0, 0.0);
20    while first < count && top + tall(first) <= above {
21        (first, top) = (first + 1, top + tall(first));
22    }
23    let (mut end, mut bottom) = (first, top);
24    while end < count && bottom < above + shown {
25        (end, bottom) = (end + 1, bottom + tall(end));
26    }
27    ([first, end], [top, bottom])
28}
29
30/// Tells a box's available size request apart from its own id.
31const AVAILABLE: u64 = 0x726f_6f6d;
32
33/// How far a scroll box is scrolled ([`Ui::scroll_state`]).
34#[derive(Clone, Copy, Debug, Default, PartialEq)]
35pub struct ScrollState {
36    /// How far it is scrolled: across and down, in units from its start.
37    pub offset: [f32; 2],
38    /// How far it can scroll each way: to where its content's end shows.
39    pub max_offset: [f32; 2],
40}
41
42impl ScrollState {
43    /// Whether it shows its content's vertical end (as one with no more content than it shows
44    /// does).
45    pub fn at_end(&self) -> bool {
46        self.offset[1] >= self.max_offset[1] - 0.5
47    }
48}
49
50/// Where the app asked a box to scroll: a place per axis, or `NAN` to leave that axis; and
51/// whether the person's scrolling goes first.
52#[derive(Clone, Copy)]
53pub(crate) struct ScrollRequest {
54    to: [f32; 2],
55    yields: bool,
56}
57
58impl ScrollRequest {
59    /// Where the box goes along `axis` for this request, the person having scrolled it `by`
60    /// meanwhile: nothing where the request leaves that axis.
61    pub(crate) fn to(&self, axis: usize, by: f32) -> Option<f32> {
62        (!self.to[axis].is_nan() && !(self.yields && by != 0.0)).then_some(self.to[axis])
63    }
64}
65
66/// A box that stays at its end ([`Ui::stick_to_bottom`]): whether the last run left it there,
67/// and whether this run asked again.
68struct End {
69    id: Id,
70    at: bool,
71    asked: bool,
72}
73
74/// A long list of rows of varying height as this run describes it: the box holding its rows,
75/// the key of its kept heights, the first visible row and whether it starts above the view (and
76/// the box scrolling the list, to keep the view still when that row's height changes).
77#[derive(Clone, Copy)]
78pub(crate) struct VariableList {
79    rows: u32,
80    id: Id,
81    first: usize,
82    cut: bool,
83    within: u32,
84    /// The height assumed for a row never laid out.
85    about: f32,
86}
87
88/// What the app asked of scroll boxes and of the next text box, until done; and what is kept of
89/// boxes staying at their end and of long lists with rows of varying height.
90#[derive(Default)]
91pub(crate) struct Asks {
92    /// Where boxes are to scroll, by id.
93    pub scroll_requests: Vec<(Id, ScrollRequest)>,
94    /// The box to bring into view; 0 for none.
95    pub into_view: Id,
96    /// The row the next long list is to show, kept for the run (rows measured meanwhile may
97    /// move it out of view again); and whether a list took it in this pass.
98    row: Option<usize>,
99    row_taken: bool,
100    ends: Vec<End>,
101    /// The long lists of varying row height described in this pass; and each row's last
102    /// laid-out height (0 until laid out), by list id.
103    pub lists: Vec<VariableList>,
104    heights: ById<Vec<f32>>,
105    /// The next multi-line text box leaves Enter to the app
106    /// ([`enter_submits`](Ui::enter_submits)).
107    pub enter_left: bool,
108    /// Code set by the first call needing it, so a program that never asks carries none of it
109    /// (as `paint::Shows` does for drawings): after layout, measuring rows of varying height
110    /// ([`variable_rows`](Ui::variable_rows)); before scrolling, bringing a box into view
111    /// ([`scroll_into_view`](Ui::scroll_into_view)); after scrolling, noting whether a box
112    /// staying at its end is there ([`stick_to_bottom`](Ui::stick_to_bottom)); and at the end
113    /// of a run, forgetting what was not asked (both).
114    pub measured: Option<fn(&mut Ui)>,
115    pub bring: Option<fn(&mut Ui)>,
116    pub ended: Option<fn(&mut Ui, u32, Id, f32)>,
117    forget: Option<fn(&mut Asks)>,
118    /// Which boxes are spell checked, what is known of their words, and the code for it:
119    /// nothing until a box asks ([`check_spelling`](Ui::check_spelling)).
120    pub spelling: crate::spell::Spelling,
121}
122
123impl Asks {
124    /// Where box `id` was asked to scroll, if it was: the request is then done.
125    pub(crate) fn take_scroll_request(&mut self, id: Id) -> Option<ScrollRequest> {
126        let at = self.scroll_requests.iter().position(|(asked, _)| *asked == id)?;
127        Some(self.scroll_requests.swap_remove(at).1)
128    }
129    /// As the app starts describing the window again.
130    pub(crate) fn begin(&mut self) {
131        self.lists.clear();
132        self.row_taken = false;
133    }
134    /// At the end of a run: requests for boxes not described are dropped; a box no longer
135    /// asking to stay at its end is forgotten, as are the heights of a long list not described.
136    pub(crate) fn settled(&mut self) {
137        (self.into_view, self.row) = (0, None);
138        self.scroll_requests.clear();
139        if let Some(forget) = self.forget {
140            forget(self);
141        }
142    }
143    /// What `settled` forgets of boxes staying at their end, and of long lists.
144    fn forget(&mut self) {
145        self.ends.retain_mut(|end| std::mem::take(&mut end.asked));
146        let lists = &self.lists;
147        self.heights.retain(|id, _| lists.iter().any(|list| list.id == *id));
148    }
149}
150
151/// Scrolling: to a place, to a box, kept at the end; and lists of rows of varying height.
152impl Ui {
153    /// How far `of`'s box (a scroll box described this run) is scrolled and can scroll, as of
154    /// the last layout. Zero for a box that does not scroll.
155    pub fn scroll_state(&self, of: &Response) -> ScrollState {
156        let Some(at) = self.box_of(of.id).filter(|at| self.tree.places.len() > *at as usize) else { return ScrollState::default() };
157        let most = [0, 1].map(|axis| if self.tree.scrolls(at, axis) { self.tree.scroll_end(at, axis) } else { 0.0 });
158        ScrollState { offset: self.tree.specs[at as usize].offset, max_offset: most }
159    }
160    /// Scrolls `of`'s box (a scroll box) to `to`: across and down, in units from its start, as
161    /// [`ScrollState::offset`] gives them. `f32::INFINITY` goes to that axis's end, `f32::NAN`
162    /// leaves it: `[f32::NAN, 0.0]` goes back to the top. Done before anything is drawn.
163    pub fn scroll_to(&mut self, of: &Response, to: [f32; 2]) {
164        self.asks.scroll_requests.push((of.id, ScrollRequest { to, yields: false }));
165    }
166    /// Keeps `of`'s box (scrolling vertically) at its end while it is there, as its content
167    /// grows: a chat, a log, a program's output. It starts at its end. Scrolled back by the
168    /// person, it stays where put as more comes; scrolled to the end again, it stays there
169    /// again ([`ui.scroll_to(&box, [f32::NAN, f32::INFINITY])`](Ui::scroll_to) takes it there).
170    /// Say it every run, as long as the box should do so.
171    pub fn stick_to_bottom(&mut self, of: &Response) {
172        let end = match self.asks.ends.iter_mut().find(|end| end.id == of.id) {
173            Some(end) => end,
174            None => {
175                self.asks.ends.push(End { id: of.id, at: true, asked: false });
176                self.asks.ends.last_mut().expect("just put in")
177            }
178        };
179        end.asked = true;
180        if end.at {
181            self.asks.scroll_requests.push((of.id, ScrollRequest { to: [f32::NAN, f32::INFINITY], yields: true }));
182        }
183        self.asks.ended = Some(Ui::note_end);
184        self.asks.forget = Some(Asks::forget);
185    }
186    /// After a box that may stay at its end (`at`, id `id`) scrolled to `offset`: whether it is
187    /// at its end now, for the next run.
188    fn note_end(&mut self, at: u32, id: Id, offset: f32) {
189        let end = self.tree.scroll_end(at, 1);
190        self.asks.ends.iter_mut().filter(|end| end.id == id).for_each(|kept| kept.at = offset >= end - 0.5);
191    }
192    /// Scrolls the boxes around box `id` so it shows (its start, if it is larger than the
193    /// view). The box must be described this run; it comes into view before anything is drawn.
194    /// (A long list's row out of view is not described: use
195    /// [`scroll_to_row`](Self::scroll_to_row).)
196    pub fn scroll_into_view(&mut self, id: Id) {
197        self.asks.into_view = id;
198        self.asks.bring = Some(Ui::bring_into_view);
199    }
200    /// Brings the requested box into view once described: see `show`.
201    fn bring_into_view(&mut self) {
202        let id = self.asks.into_view;
203        let Some(at) = self.tree.specs.iter().position(|spec| spec.id == id).filter(|_| id != 0) else { return };
204        self.asks.into_view = 0;
205        self.show(at as u32, self.tree.rect_of(at as u32));
206    }
207    /// Has the next long list (`rows`, `list`, [`variable_rows`](Self::variable_rows),
208    /// [`variable_list`](Self::variable_list)) bring row `row` into view: a search hit, a new
209    /// item.
210    pub fn scroll_to_row(&mut self, row: usize) {
211        self.asks.row = Some(row);
212    }
213    /// The row a long list should bring into view, if one was asked for and no earlier list
214    /// took it this pass.
215    pub(crate) fn row_asked(&mut self) -> Option<usize> {
216        let asked = self.asks.row.filter(|_| !self.asks.row_taken);
217        self.asks.row_taken |= asked.is_some();
218        asked
219    }
220    /// Scrolls box `within`, which shows `shown` of a long list from `above` down, so the
221    /// stretch from `top` that is `high` tall shows. Gives back the list's new top in view.
222    /// (Rows out of view are not described, so the list is laid out for this at once and
223    /// described again before drawing.)
224    pub(crate) fn list_into_view(&mut self, within: u32, above: f64, shown: f32, top: f64, high: f64) -> f64 {
225        let to = match () {
226            _ if top < above => top,
227            _ if top + high > above + shown as f64 => (top + high - shown as f64).min(top),
228            _ => return above,
229        };
230        let spec = &mut self.tree.specs[within as usize];
231        spec.offset[1] = (spec.offset[1] as f64 + to - above).max(0.0) as f32;
232        self.scrolls.insert(spec.id, spec.offset);
233        self.again = true;
234        to
235    }
236
237    /// The space inside the open box: its size less its padding (across, also less its scroll
238    /// bar's track; down, no more than the window shows when no ancestor scrolls vertically).
239    /// Its content can be fitted to it: a picture as large as fits, as many items as fit, a
240    /// chart as wide as the box. It is this run's layout: where that differs from the last
241    /// run's, the window is described again before drawing. (Before the box's first layout, it
242    /// is the window's size.)
243    pub fn available_size(&mut self) -> Size {
244        let Some(open) = self.open.last() else { return self.size() };
245        let (at, id) = (open.at, hash((self.tree.specs[open.at as usize].id, AVAILABLE)));
246        // A box never asked before is laid out in this pass, to be sure.
247        let read = match self.rooms.get(&id) {
248            Some(read) => *read,
249            None => {
250                self.stale = true;
251                [self.size().w, self.size().h, 0.0]
252            }
253        };
254        self.measures.push(Measure { at, within: at, id, read });
255        Size { w: read[0], h: read[1] }
256    }
257
258    /// How far the wheel turned over `of`'s box since the last run, across and down, in units
259    /// (as scroll boxes take it): for the app's own drawing, a map, a picture. It is consumed,
260    /// so nothing scrolls by it; nothing where it did not turn there (or where a scroll box
261    /// inside, under the pointer, takes it). (Control+wheel zooms: [`ui.zoom`](Ui::zoom).)
262    pub fn wheel_delta(&mut self, of: &Response) -> Option<[f32; 2]> {
263        let (wheel, pointer) = (self.input.wheel, self.input.pointer?);
264        if !of.contains_pointer || wheel == [0.0; 2] {
265            return None;
266        }
267        let r = of.rect;
268        let inside = |s: &crate::visible_boxes::Scroller| s.rect.x >= r.x && s.rect.y >= r.y && s.rect.right() <= r.right() && s.rect.bottom() <= r.bottom() && s.id != of.id;
269        if self.visible_boxes.scrollers.iter().any(|s| inside(s) && s.visible.contains(pointer) && (self.tree.overflows(s.at, 0) || self.tree.overflows(s.at, 1))) {
270            return None;
271        }
272        self.input.wheel = [0.0; 2];
273        self.again = true;
274        Some(wheel)
275    }
276
277    /// Starts `count` rows of a long list, each as tall as its content (wrapping messages, log
278    /// lines), inside a scroll box, and gives back the indices of those in view. Describe just
279    /// those, one box each, then [`close`](Self::close) the rows. A row not laid out yet is
280    /// assumed the others' average height (`about` before any was); after that the list keeps
281    /// its measured height and remeasures it whenever it shows. 100,000 rows cost what a
282    /// screenful does, plus a pass over their heights. (Where a row starting above the view
283    /// changes height, the view is kept still.)
284    #[cfg_attr(debug_assertions, track_caller)]
285    pub fn variable_rows(&mut self, count: usize, about: f32) -> Range<usize> {
286        let (id, page) = (self.next_id(), self.open.first().map_or(0, |open| open.at));
287        // The nearest enclosing box scrolling vertically: what it shows is in view.
288        let within = self.open.iter().rev().map(|open| open.at).find(|at| self.tree.specs[*at as usize].frame.scroll[1]).unwrap_or(page);
289        let read = self.rooms.get(&id).copied().unwrap_or([0.0, self.size().h, 0.0]);
290        let mut heights = std::mem::take(self.asks.heights.entry(id).or_default());
291        heights.resize(count, 0.0);
292        // A row not laid out yet is assumed the average height.
293        let (known, sum) = heights.iter().filter(|high| **high > 0.0).fold((0, 0.0), |(known, sum), high| (known + 1, sum + *high as f64));
294        let about = if known > 0 { sum / known as f64 } else { about.max(1.0) as f64 };
295        let tall = |row: usize| if heights[row] > 0.0 { heights[row] as f64 } else { about };
296        let mut above = self.tree.specs[within as usize].offset[1] as f64 - read[2] as f64;
297        if let Some(row) = self.row_asked().filter(|row| *row < count) {
298            let top: f64 = (0..row).map(tall).sum();
299            above = self.list_into_view(within, above, read[1], top, tall(row));
300        }
301        let ([first, end], [top, bottom]) = rows_in_view(tall, count, above, read[1] as f64);
302        let total = bottom + (end..count).map(tall).sum::<f64>();
303        self.asks.heights.insert(id, heights);
304        // A box as tall as all rows, so the scroll bar is right; in it, empty room for the rows
305        // above the visible ones, then those.
306        let rows = self.tree.specs.len() as u32;
307        // Where the whole list shows, where it starts in its scroll box does not matter: only
308        // that box's room is measured. A few rows at the bottom of their box then move down as
309        // one is added, without describing again.
310        let fits = first == 0 && end == count && bottom <= read[1] as f64;
311        self.measures.push(Measure { at: if fits { within } else { rows }, within, id, read });
312        self.column().h(Length::Px(total as f32)).open();
313        self.el().h(Length::Px(top as f32)).show();
314        // Rows count their places from the first row overall, so a row keeps its identity
315        // wherever the list is scrolled.
316        if let Some(open) = self.open.last_mut() {
317            open.children += first as u32;
318        }
319        self.asks.lists.push(VariableList { rows, id, first, cut: top < above, within, about: about as f32 });
320        self.asks.measured = Some(Ui::measure_rows);
321        self.asks.forget = Some(Asks::forget);
322        first..end
323    }
324    /// Starts a long list of rows of varying height in a scroll box of its own:
325    /// [`variable_rows`](Self::variable_rows) and the box around them. Describe the rows it
326    /// gives back, then [`close`](Self::close) it.
327    #[cfg_attr(debug_assertions, track_caller)]
328    pub fn variable_list(&mut self, count: usize, about: f32) -> Range<usize> {
329        self.column().grow().scroll().open();
330        self.join_next = true;
331        self.variable_rows(count, about)
332    }
333    /// After layout: each visible row's height in lists of varying row height. Where any
334    /// differs from what the list had, the window is described again; and where the row
335    /// starting above the view changed, the list's scroll box scrolls by as much, so the view
336    /// stays still.
337    fn measure_rows(&mut self) {
338        for at in 0..self.asks.lists.len() {
339            let (grew, VariableList { cut, within, .. }) = (self.measure_list(at), self.asks.lists[at]);
340            if cut && grew != 0.0 && within != NONE {
341                let spec = &mut self.tree.specs[within as usize];
342                spec.offset[1] = (spec.offset[1] + grew).max(0.0);
343                self.scrolls.insert(spec.id, spec.offset);
344            }
345        }
346    }
347    /// The heights of the visible rows of this pass's list `at`, kept with the list. Gives back
348    /// how much taller its first visible row came out than the list had it.
349    fn measure_list(&mut self, at: usize) -> f32 {
350        let Ui { tree, asks, again, .. } = self;
351        let list = &asks.lists[at];
352        let Some(heights) = asks.heights.get_mut(&list.id) else { return 0.0 };
353        let mut first = 0.0;
354        for (nth, child) in tree.children(list.rows).skip(1).enumerate() {
355            let (high, row) = (tree.places[child as usize].dim[1], list.first + nth);
356            let Some(kept) = heights.get_mut(row).filter(|kept| (**kept - high).abs() >= 0.5) else { continue };
357            // Compared against its assumed height: a row laid out for the first time at the
358            // average height describes nothing again.
359            let was = if *kept > 0.0 { *kept } else { list.about };
360            first = if nth == 0 { high - was } else { first };
361            *again |= (was - high).abs() >= 0.5;
362            *kept = high;
363        }
364        first
365    }
366
367    /// Where box `id` is in this run's box list: an open one at once, any other by searching.
368    pub(crate) fn box_of(&self, id: Id) -> Option<u32> {
369        if let Some(open) = self.open.iter().rev().find(|open| self.tree.specs[open.at as usize].id == id) {
370            return Some(open.at);
371        }
372        self.tree.specs.iter().rposition(|spec| spec.id == id).map(|at| at as u32)
373    }
374}