rust-glass 0.4.0

GPU rendered Liquid Glass style UI framework with an immediate mode API
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Scroll areas: vertical, horizontal, both, and long lists that lay out
//! only the visible rows.

use std::ops::Range;

use crate::animation::{POINTS, Spring, Tuning};
use crate::color::Color;
use crate::context::{Id, Sense};
use crate::geometry::{Rect, Vec2, vec2};
use crate::material::Corner;
use crate::paint::Feather;
use crate::ui::Ui;
use crate::widgets::press::rubber_band;

/// Scrolling with smooth wheel steps, elastic ends and overlay scroll bars.
/// Vertical by default; [`Self::horizontal`] lays the content out in a row
/// and [`Self::both`] scrolls on two axes. `fade` dissolves content at the
/// edges, which keeps floating glass legible without a solid bar behind it.
///
/// Long lists draw only what is visible with [`Self::show_rows`].
pub struct ScrollArea {
    height: Option<f32>,
    width: Option<f32>,
    x: bool,
    y: bool,
    content_width: Option<f32>,
    fade: Feather,
    inset_top: f32,
    inset_bottom: f32,
    bar_inset: f32,
    id: &'static str,
}

#[derive(Clone, Copy, Default)]
struct Axis {
    offset: Spring,
    target: f32,
    content: f32,
    grab: f32,
}

#[derive(Clone, Copy, Default)]
struct State {
    axes: [Axis; 2],
    bar: Spring,
    last_move: f64,
}

impl Default for ScrollArea {
    fn default() -> Self {
        Self::new()
    }
}

impl ScrollArea {
    /// Vertical scrolling.
    pub fn new() -> Self {
        Self {
            height: None,
            width: None,
            x: false,
            y: true,
            content_width: None,
            fade: Feather::default(),
            inset_top: 0.0,
            inset_bottom: 0.0,
            bar_inset: 4.0,
            id: "scroll",
        }
    }
    /// Horizontal scrolling. Children are placed side by side and centered
    /// on the height of the area. Vertical wheel movement passes to the area
    /// around it; shift with the wheel or a sideways swipe scrolls this one.
    pub fn horizontal() -> Self {
        Self { x: true, y: false, ..Self::new() }
    }
    /// Scrolling on both axes, for content larger than the view both ways.
    /// Children are stacked vertically in a column [`Self::content_width`]
    /// wide, or as wide as they need when that is not set.
    pub fn both() -> Self {
        Self { x: true, ..Self::new() }
    }
    /// Names the area. Needed when one `Ui` holds more than one scroll area.
    pub fn id(mut self, id: &'static str) -> Self {
        self.id = id;
        self
    }
    /// Sets the height. The default is the height left in the layout.
    pub fn height(mut self, height: f32) -> Self {
        self.height = Some(height);
        self
    }
    /// Sets the width. The default is the width left in the layout.
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }
    /// Width of the column the content is laid out in. A vertical area
    /// centers a narrower column and keeps the scroll bar at its own edge, so
    /// a readable column in a wide window still scrolls from the window edge.
    /// For [`Self::both`] it is the width of the content.
    pub fn content_width(mut self, w: f32) -> Self {
        self.content_width = Some(w);
        self
    }
    /// Distance of the scroll bars from the edges of the area, in points.
    /// The default is 4.
    pub fn bar_inset(mut self, inset: f32) -> Self {
        self.bar_inset = inset.max(0.0);
        self
    }
    /// Dissolve content over this distance at the top and bottom.
    pub fn fade(mut self, top: f32, bottom: f32) -> Self {
        self.fade.top = top;
        self.fade.bottom = bottom;
        self
    }
    /// Dissolve content over this distance at the left and right.
    pub fn fade_sides(mut self, left: f32, right: f32) -> Self {
        self.fade.left = left;
        self.fade.right = right;
        self
    }
    /// Space kept free for floating bars. Content scrolls below them.
    pub fn insets(mut self, top: f32, bottom: f32) -> Self {
        self.inset_top = top;
        self.inset_bottom = bottom;
        self
    }

    /// Shows the area with the content drawn by `f`.
    pub fn show<R>(self, ui: &mut Ui, f: impl FnOnce(&mut Ui) -> R) -> R {
        self.show_inner(ui, |ui, _| f(ui))
    }

    /// A vertical list of `count` rows, each `row_height` tall, of which only
    /// the visible ones are laid out. `f` gets the range of rows to draw and
    /// must give each row exactly `row_height`.
    ///
    /// ```
    /// # use rust_glass::prelude::*;
    /// # fn f(ui: &mut Ui, names: &[String]) {
    /// ScrollArea::new().height(300.0).show_rows(ui, 28.0, names.len(), |ui, rows| {
    ///     for i in rows {
    ///         ui.label(&names[i]);
    ///     }
    /// });
    /// # }
    /// ```
    pub fn show_rows<R>(
        self,
        ui: &mut Ui,
        row_height: f32,
        count: usize,
        f: impl FnOnce(&mut Ui, Range<usize>) -> R,
    ) -> R {
        let inset = self.inset_top;
        self.show_inner(ui, |ui, visible| {
            let stride = row_height + ui.spacing;
            let top = (visible.min.y - inset).max(0.0);
            let first = ((top / stride).floor() as usize).min(count);
            let n = (visible.height() / stride).ceil() as usize + 2;
            let last = (first + n).min(count);
            ui.space(first as f32 * stride);
            let out = f(ui, first..last);
            let total = (count as f32 * stride - ui.spacing).max(0.0);
            ui.reserve(vec2(0.0, total));
            out
        })
    }

    /// `f` gets the visible part of the content, relative to its top left.
    fn show_inner<R>(self, ui: &mut Ui, f: impl FnOnce(&mut Ui, Rect) -> R) -> R {
        let id = ui.make_id(self.id);
        let h = self.height.unwrap_or_else(|| ui.available_height());
        let w = self.width.unwrap_or_else(|| ui.available_width());
        let view = ui.allocate(vec2(w, h));
        let mut s: State = ui.ctx.get(id);
        let dt = ui.ctx.dt;
        let on = [self.x, self.y];
        let size = [w, h];
        let max = [0, 1].map(|a| (s.axes[a].content - size[a]).max(0.0));
        let wheel = ui.ctx.scroll_area_axes(id, view.intersect(ui.clip), ui.layer, self.x, self.y);
        let wheel = [wheel.x, wheel.y];
        let limit = if ui.ctx.theme.reduce_motion { 0.5 } else { 46.0 };
        let mut shown = [0.0; 2];
        for a in 0..2 {
            let ax = &mut s.axes[a];
            if !on[a] {
                *ax = Axis::default();
                continue;
            }
            if wheel[a] != 0.0 {
                ax.target -= wheel[a];
                s.last_move = ui.ctx.time;
                ui.ctx.add_scroll_energy(wheel[a] * 0.004);
            }
            // Past the ends the target is pulled back, so it gives and returns.
            let over = ax.target - ax.target.clamp(0.0, max[a]);
            if over != 0.0 {
                ax.target = ax.target.clamp(0.0, max[a]) + rubber_band(over, limit);
                let back = (-dt * 11.0).exp();
                let o = ax.target - ax.target.clamp(0.0, max[a]);
                ax.target = ax.target.clamp(0.0, max[a]) + if o.abs() < 0.4 { 0.0 } else { o * back };
                ui.ctx.request_repaint();
            }
            if ax.offset.step_within(ax.target, Tuning::new(0.17, 1.0), dt, POINTS) {
                s.last_move = ui.ctx.time;
                ui.ctx.request_repaint();
            }
            shown[a] = (ax.offset.value * ui.ctx.pixels_per_point).round() / ui.ctx.pixels_per_point;
        }
        let off = [s.axes[0].offset.value, s.axes[1].offset.value];

        let (old_clip, old_mask) = (ui.clip, ui.mask);
        // Room for shadows and for glass that swells under a press, on the
        // sides that do not scroll.
        let room = vec2(if self.x { 0.0 } else { 30.0 }, if self.y { 0.0 } else { 30.0 });
        let sides = view.expand2(room);
        ui.clip = ui.clip.intersect(sides);
        let edge = |o: f32, m: f32| (o / 24.0).clamp(0.0, 1.0) * (m > 0.5) as u32 as f32;
        let feather = Feather {
            left: self.fade.left * edge(off[0], max[0]),
            right: self.fade.right * edge(max[0] - off[0], max[0]),
            top: self.fade.top * edge(off[1], max[1]),
            bottom: self.fade.bottom * edge(max[1] - off[1], max[1]),
        };
        if self.fade.left + self.fade.right + self.fade.top + self.fade.bottom > 0.0 {
            ui.mask = ui.painter().add_mask(sides, 0.0, false, feather);
        }
        // A vertical area centers a column narrower than itself.
        let column = match self.content_width {
            Some(cw) if !self.x => cw.min(view.width()),
            _ => view.width(),
        };
        let indent = ((view.width() - column) * 0.5).max(0.0);
        let min = vec2(view.min.x - shown[0] + indent, view.min.y - shown[1] + self.inset_top);
        let visible = Rect::from_min_size(vec2(off[0], off[1]), view.size());
        let revealing = ui.ctx.reveal.is_some() && ui.ctx.reveal_rect.is_none();
        let (out, used) = if self.x && !self.y {
            let body = Rect { min, max: vec2(min.x + 1.0e5, view.max.y - self.inset_bottom) };
            ui.row_sized(id, body, |ui| f(ui, visible))
        } else {
            let width = if self.x { self.content_width.unwrap_or(1.0e5) } else { column };
            let body = Rect { min, max: vec2(min.x + width, min.y + 1.0e5) };
            ui.in_rect_sized(id, body, |ui| f(ui, visible))
        };
        ui.clip = old_clip;
        ui.mask = old_mask;
        // A widget inside got focus from the keyboard or a screen reader:
        // scroll just far enough to show it.
        if revealing && let Some(target) = ui.ctx.reveal_rect {
            const MARGIN: f32 = 12.0;
            let shown = [
                (view.min.x + MARGIN, view.max.x - MARGIN),
                (view.min.y + self.inset_top + MARGIN, view.max.y - self.inset_bottom - MARGIN),
            ];
            let wanted = [(target.min.x, target.max.x), (target.min.y, target.max.y)];
            for a in 0..2 {
                let ((start, end), (low, high)) = (shown[a], wanted[a]);
                let shift = if low < start {
                    low - start
                } else if high > end {
                    (high - end).min(low - start)
                } else {
                    0.0
                };
                if on[a] && shift != 0.0 {
                    s.axes[a].target = (s.axes[a].target + shift).clamp(0.0, max[a]);
                    s.last_move = ui.ctx.time;
                    ui.ctx.request_repaint();
                }
            }
        }
        let content = [used.x, used.y + self.inset_top + self.inset_bottom];
        for a in 0..2 {
            if on[a] && (content[a] - s.axes[a].content).abs() > 0.5 {
                s.axes[a].content = content[a];
                ui.ctx.request_repaint();
            }
        }

        // Scroll bars.
        let recent = ui.ctx.time - s.last_move < 0.9;
        let mut engaged = false;
        let mut bars = Vec::new();
        for a in 0..2 {
            if !on[a] || max[a] <= 1.0 {
                continue;
            }
            let (t0, t1) = if a == 1 {
                (view.min.y + self.inset_top.max(6.0), view.max.y - self.inset_bottom.max(6.0))
            } else {
                (view.min.x + 6.0, view.max.x - if on[1] && max[1] > 1.0 { 14.0 } else { 6.0 })
            };
            let ax = &mut s.axes[a];
            let track = t1 - t0;
            // An area too short for a bar shows none.
            if track < 8.0 {
                continue;
            }
            let len = (size[a] / ax.content * track).clamp(28.0f32.min(track), track);
            let over = (off[a] - off[a].clamp(0.0, max[a])).abs();
            let len = (len - over * 0.6).max(12.0);
            let start = t0 + (track - len) * (off[a] / max[a]).clamp(0.0, 1.0);
            let reach = 10.0 + self.bar_inset;
            let hit = if a == 1 {
                Rect { min: vec2(view.max.x - reach, start), max: vec2(view.max.x, start + len) }
            } else {
                Rect { min: vec2(start, view.max.y - reach), max: vec2(start + len, view.max.y) }
            };
            let r = ui.interact(id.with(("bar", a)), hit, Sense::Drag);
            let p0 = if a == 1 { ui.ctx.input.press_origin.y } else { ui.ctx.input.press_origin.x };
            if r.pressed {
                ax.grab = p0 - start;
            }
            if r.held
                && let Some(p) = r.pointer
            {
                let p = if a == 1 { p.y } else { p.x };
                ax.target = ((p - ax.grab - t0) / (track - len).max(1.0)).clamp(0.0, 1.0) * max[a];
                ax.offset.set(ax.target);
            }
            engaged |= r.hovered || r.held;
            bars.push((a, r.id, r.hovered || r.held, start, len));
        }
        if s.bar.step((recent || engaged) as u32 as f32, Tuning::new(0.3, 1.0), dt) {
            ui.ctx.request_repaint();
        } else if recent {
            // The bars rest until they start to fade.
            let left = 0.9 - (ui.ctx.time - s.last_move);
            ui.ctx.request_repaint_after(std::time::Duration::from_secs_f64(left.max(0.001)));
        }
        let c = Color::black(0.38).lerp(Color::white(0.45), ui.surface.darkness());
        let alpha = s.bar.value;
        for (a, bar_id, hot, start, len) in bars {
            let wide = ui.ctx.animate_bool(bar_id.with("wide"), hot, Tuning::SNAP);
            let bw = 4.0 + 3.0 * wide;
            let i = self.bar_inset;
            let r = if a == 1 {
                Rect { min: vec2(view.max.x - i - bw, start), max: vec2(view.max.x - i, start + len) }
            } else {
                Rect { min: vec2(start, view.max.y - i - bw), max: vec2(start + len, view.max.y - i) }
            };
            ui.painter().fill(r, Corner::Capsule, c.fade(alpha));
        }
        ui.ctx.set(id, s);
        out
    }
}

/// Scroll position of the area `id` inside `ui`, for saving and restoring.
pub fn scroll_offset(ui: &mut Ui, id: &'static str) -> Vec2 {
    let id: Id = ui.make_id(id);
    let s: State = ui.ctx.get(id);
    vec2(s.axes[0].target, s.axes[1].target)
}

/// Jump the area `id` inside `ui` to `offset`. Call before the area is shown.
pub fn set_scroll_offset(ui: &mut Ui, id: &'static str, offset: Vec2) {
    let id: Id = ui.make_id(id);
    let mut s: State = ui.ctx.get(id);
    for (a, v) in [offset.x, offset.y].into_iter().enumerate() {
        s.axes[a].target = v.max(0.0);
        s.axes[a].offset.set(v.max(0.0));
    }
    ui.ctx.set(id, s);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::Context;
    use crate::geometry::rect;
    use crate::widgets::panel::region;

    #[test]
    fn an_area_shorter_than_its_bar_does_not_panic() {
        let mut ctx = Context::new();
        for t in 0..3 {
            ctx.begin_frame(vec2(400.0, 300.0), 1.0, t as f64 / 60.0, &[]);
            region(&mut ctx, "page", rect(0.0, 0.0, 400.0, 300.0), |ui| {
                ScrollArea::new().height(20.0).show(ui, |ui| {
                    for _ in 0..20 {
                        ui.label("Row");
                    }
                });
            });
            ctx.end_frame();
        }
    }

    #[test]
    fn a_narrow_column_is_centered_with_the_bar_at_the_edge() {
        let mut ctx = Context::new();
        let mut at = Rect::default();
        for t in 0..3 {
            ctx.begin_frame(vec2(1000.0, 300.0), 1.0, t as f64 / 60.0, &[]);
            region(&mut ctx, "page", rect(0.0, 0.0, 1000.0, 300.0), |ui| {
                ScrollArea::new().content_width(400.0).show(ui, |ui| {
                    at = ui.label("Row").rect;
                });
            });
            ctx.end_frame();
        }
        assert_eq!(at.min.x, 300.0);
    }

    #[test]
    fn masks_inside_a_fading_area_keep_its_fade() {
        let mut ctx = Context::new();
        let mut selected = 0;
        ctx.begin_frame(vec2(400.0, 300.0), 1.0, 0.0, &[]);
        region(&mut ctx, "page", rect(0.0, 0.0, 400.0, 300.0), |ui| {
            ScrollArea::new().fade(20.0, 20.0).height(100.0).show(ui, |ui| {
                for _ in 0..10 {
                    ui.segmented(&mut selected, &["One", "Two"]);
                }
            });
        });
        ctx.end_frame();
        let masks = &ctx.paint.data.masks;
        // The first mask is the fade of the area, the rest belong to the
        // segmented controls and must be combined with it.
        assert!(masks.len() > 1);
        assert_eq!(masks[0].parent, 0);
        assert!(masks[1..].iter().all(|m| m.parent == 1));
    }
}