Skip to main content

rust_glass/
context.rs

1//! The state of one window: input, theme, layers, widget memory and the
2//! measurements glass adapts to.
3
4use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::hash::{Hash, Hasher};
7
8use crate::accessibility::{Access, Action, LayerInfo, Node, Role};
9use crate::animation::{Spring, Spring2d, SpringRect, Tuning};
10use crate::color::Color;
11use crate::geometry::{Rect, Vec2, vec2};
12use crate::input::{Event, Input, Key};
13use crate::material::Glass;
14use crate::paint::{ImageId, Paint, Painter};
15use crate::text::{TextEngine, TextStyle, Weight};
16use crate::theme::{Surface, Theme};
17
18/// Identifies a widget across frames, so it can keep state such as an
19/// animation or a scroll position.
20///
21/// Ids are hashes. Widgets added to a [`Ui`](crate::Ui) get one from their
22/// position automatically. Give your own with [`Id::new`] when the widget
23/// can move in the layout, for example in a list that reorders.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct Id(pub u64);
26
27impl Id {
28    /// Creates an id from any hashable value.
29    pub fn new(source: impl Hash) -> Self {
30        let mut h = std::hash::DefaultHasher::new();
31        source.hash(&mut h);
32        Id(h.finish())
33    }
34    /// Derives a child id, for a part of this widget.
35    pub fn with(self, source: impl Hash) -> Self {
36        let mut h = std::hash::DefaultHasher::new();
37        self.0.hash(&mut h);
38        source.hash(&mut h);
39        Id(h.finish())
40    }
41}
42
43/// Where a layer sits in the stack. Later orders draw on top and get input
44/// first. Within one order, the layer used or clicked last is on top.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub enum Order {
47    /// Behind everything, such as a wallpaper.
48    Background,
49    /// The app content.
50    Content,
51    /// Floating bars: toolbars, tab bars and sidebars.
52    Bar,
53    /// Floating windows.
54    Window,
55    /// Alerts and sheets, which block everything below.
56    Modal,
57    /// Menus and other popups.
58    Popup,
59    /// Toasts.
60    Toast,
61    /// Tooltips and items being dragged.
62    Tooltip,
63}
64
65/// What a widget reacts to.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum Sense {
68    /// Only hovering. It still blocks the widgets below it.
69    Hover,
70    /// Clicks, reported when the button is released over the widget.
71    Click,
72    /// Clicks reported as soon as the button goes down, for controls that
73    /// select, such as rows of a sidebar. Like a sidebar on macOS, the
74    /// selection does not wait for the release.
75    Press,
76    /// Clicks and drags.
77    Drag,
78}
79
80/// The mouse cursor shape. Set [`Context::cursor`] while drawing a widget.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
82pub enum Cursor {
83    /// The arrow.
84    #[default]
85    Default,
86    /// A hand, for things that can be clicked.
87    Pointer,
88    /// A text cursor.
89    Text,
90    /// For things that can be dragged.
91    Grab,
92    /// A horizontal resize arrow.
93    ResizeHorizontal,
94    /// The widget is disabled.
95    NotAllowed,
96}
97
98/// What happened to a widget this frame.
99#[derive(Clone, Copy, Debug)]
100pub struct Response {
101    /// The widget's id.
102    pub id: Id,
103    /// Where the widget is.
104    pub rect: Rect,
105    /// The pointer is over the widget and nothing else is being dragged.
106    pub hovered: bool,
107    /// The pointer is down and the press started on this widget.
108    pub held: bool,
109    /// The press started on this widget this frame.
110    pub pressed: bool,
111    /// A press that started on this widget ended this frame.
112    pub released: bool,
113    /// The widget was clicked, with the pointer, the keyboard or a screen
114    /// reader.
115    pub clicked: bool,
116    /// The press this frame is the second of a double click.
117    pub double_clicked: bool,
118    /// The secondary button was pressed over the widget.
119    pub secondary_clicked: bool,
120    /// The widget has keyboard focus.
121    pub focused: bool,
122    /// The value the widget edits changed this frame.
123    pub changed: bool,
124    /// How far the pointer moved while held.
125    pub delta: Vec2,
126    /// Pointer position, if the pointer is in the window.
127    pub pointer: Option<Vec2>,
128}
129
130impl Response {
131    /// A response where nothing happened.
132    pub(crate) fn idle(id: Id, rect: Rect, pointer: Option<Vec2>) -> Self {
133        Response {
134            id,
135            rect,
136            hovered: false,
137            held: false,
138            pressed: false,
139            released: false,
140            clicked: false,
141            double_clicked: false,
142            secondary_clicked: false,
143            focused: false,
144            changed: false,
145            delta: Vec2::ZERO,
146            pointer,
147        }
148    }
149    /// Returns [`Response::clicked`].
150    pub fn clicked(&self) -> bool {
151        self.clicked
152    }
153    /// Returns [`Response::changed`].
154    pub fn changed(&self) -> bool {
155        self.changed
156    }
157    /// Returns [`Response::hovered`].
158    pub fn hovered(&self) -> bool {
159        self.hovered
160    }
161}
162
163#[derive(Clone, Copy)]
164struct Hit {
165    id: Id,
166    rect: Rect,
167    layer: usize,
168    sense: Sense,
169    /// Axes a scroll area takes wheel input for: bit 0 x, bit 1 y.
170    scroll: u8,
171}
172
173struct Layer {
174    id: Id,
175    order: Order,
176    z: u64,
177    used: u64,
178}
179
180/// What is behind a glass element, smoothed.
181#[derive(Clone, Copy, Debug, Default)]
182struct Adapt {
183    mean: f32,
184    dev: f32,
185    known: bool,
186    is_dark: bool,
187    dark: Spring,
188    boost: Spring,
189    used: u64,
190    used_time: f64,
191}
192
193/// How a glass element should look over what is behind it. Returned by
194/// [`Context::backdrop`] and [`Context::prepare_glass`].
195#[derive(Clone, Copy, Debug)]
196pub struct Backdrop {
197    /// 0 for light glass with dark labels, 1 for dark glass with light labels.
198    pub darkness: f32,
199    /// Extra shadow over busy content, from 0 to 1.
200    pub shadow_boost: f32,
201}
202
203impl Backdrop {
204    /// Returns the surface for content drawn on this glass.
205    pub fn surface(&self) -> Surface {
206        Surface::Glass { dark: self.darkness }
207    }
208}
209
210/// A request from the UI to the window host, handled after the frame.
211#[derive(Clone, Debug)]
212pub enum HostCommand {
213    /// Put text on the clipboard.
214    Copy(String),
215    /// Open a web address in the default browser.
216    OpenUrl(String),
217    /// Close the window and end [`run`](crate::run).
218    Close,
219    /// Hide the window. The app keeps running and can show it again.
220    Hide,
221    /// Show the window and bring it to the front.
222    Show,
223}
224
225/// Wakes the window from another thread, for example when a download
226/// finishes. Get one from [`Context::waker`]. Cloning is cheap.
227#[derive(Clone)]
228pub struct Waker(pub(crate) std::sync::Arc<dyn Fn() + Send + Sync>);
229
230impl Waker {
231    /// Asks the window for a new frame. Safe to call from any thread.
232    pub fn wake(&self) {
233        (self.0)();
234    }
235}
236
237impl std::fmt::Debug for Waker {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.write_str("Waker")
240    }
241}
242
243pub(crate) struct ImageUpload {
244    pub id: ImageId,
245    pub w: u32,
246    pub h: u32,
247    pub rgba: Vec<u8>,
248}
249
250/// The state of one window. Every widget reads and writes it.
251///
252/// [`App::update`](crate::App::update) gets it each frame. Most code reaches
253/// it through [`Ui::ctx`](crate::Ui::ctx).
254pub struct Context {
255    /// Input of the current frame.
256    pub input: Input,
257    /// Appearance and accessibility settings.
258    pub theme: Theme,
259    pub(crate) paint: Paint,
260    /// Text layout and fonts.
261    pub text: TextEngine,
262    /// Seconds since the app started.
263    pub time: f64,
264    /// Seconds since the last frame, at most 1/24 so an idle gap does not
265    /// turn into one big animation step.
266    pub dt: f32,
267    /// Number of the current frame.
268    pub frame: u64,
269    /// The window, in points. Its top left corner is `(0, 0)`.
270    pub screen: Rect,
271    /// Physical pixels per point, from the display scale.
272    pub pixels_per_point: f32,
273    /// Color behind everything.
274    pub clear_color: Color,
275    /// How far glass may be simplified to keep up with the display. Windows
276    /// start with [`Quality::Auto`](crate::Quality::Auto), which steps down
277    /// only on a GPU that cannot keep up.
278    pub quality: crate::Quality,
279    /// Mouse cursor for this frame. Widgets set it while hovered.
280    pub cursor: Cursor,
281    /// Requests to the window host, handled after the frame.
282    pub host_commands: Vec<HostCommand>,
283    pub(crate) uploads: Vec<ImageUpload>,
284    pub(crate) removed_images: Vec<ImageId>,
285    /// Caret of the focused text field, where an input method shows its
286    /// candidates. The field sets it every frame it has focus.
287    pub ime_area: Option<Rect>,
288    next_image: u32,
289    /// State by id: the value, and the frame and time it was last used.
290    states: HashMap<(Id, TypeId), Stored>,
291    retention: f64,
292    hidden: u32,
293    repaint_at: Option<f64>,
294    waker: Option<Waker>,
295    layers: Vec<Layer>,
296    z_top: u64,
297    hits: Vec<Hit>,
298    prev_hits: Vec<Hit>,
299    pub(crate) hovered: Option<Id>,
300    scroll_target: [Option<Id>; 2],
301    pub(crate) active: Option<Id>,
302    pub(crate) focus: Option<Id>,
303    focus_by_key: bool,
304    focus_list: Vec<Id>,
305    focus_seen: bool,
306    /// A widget that got focus from the keyboard or a screen reader and should
307    /// be scrolled into view, with the frames left to find it.
308    pub(crate) reveal: Option<(Id, u8)>,
309    /// Where that widget was drawn this frame.
310    pub(crate) reveal_rect: Option<Rect>,
311    adapt: HashMap<u64, Adapt>,
312    repaint: bool,
313    relayout: bool,
314    light: Spring,
315    tilt: Vec2,
316    scroll_energy: f32,
317    toasts: Vec<crate::widgets::toast::ToastState>,
318    open_popups: HashMap<Id, bool>,
319    access: Access,
320    drawn: Vec<usize>,
321    drag: Option<Drag>,
322    morphs: HashMap<Id, Morph>,
323}
324
325/// A widget's state, with the frame and time it was last used.
326type Stored = (Box<dyn Any>, u64, f64);
327
328/// An element shown by one view after another. See [`Context::morph`].
329#[derive(Clone, Copy)]
330struct Morph {
331    view: Id,
332    shape: SpringRect,
333    /// Where the view put the element in the last frame.
334    target: Rect,
335    moving: bool,
336    seen: u64,
337}
338
339/// Something picked up with [`Ui::drag_source`](crate::Ui::drag_source).
340struct Drag {
341    source: Id,
342    payload: Box<dyn Any>,
343    /// Pointer position inside the item when it was picked up.
344    grab: Vec2,
345    size: Vec2,
346}
347
348impl Default for Context {
349    fn default() -> Self {
350        Self::new()
351    }
352}
353
354impl Context {
355    /// Creates the state of a window with the default theme.
356    pub fn new() -> Self {
357        Self {
358            input: Input::new(),
359            theme: Theme::default(),
360            paint: Paint::default(),
361            text: TextEngine::new(),
362            time: 0.0,
363            dt: 0.0,
364            frame: 0,
365            screen: Rect::default(),
366            pixels_per_point: 1.0,
367            clear_color: Color::gray(0.85),
368            quality: crate::Quality::Auto,
369            cursor: Cursor::Default,
370            host_commands: Vec::new(),
371            uploads: Vec::new(),
372            removed_images: Vec::new(),
373            ime_area: None,
374            next_image: 1,
375            states: HashMap::new(),
376            retention: 300.0,
377            hidden: 0,
378            repaint_at: None,
379            waker: None,
380            layers: Vec::new(),
381            z_top: 0,
382            hits: Vec::new(),
383            prev_hits: Vec::new(),
384            hovered: None,
385            scroll_target: [None; 2],
386            active: None,
387            focus: None,
388            focus_by_key: false,
389            focus_list: Vec::new(),
390            focus_seen: false,
391            reveal: None,
392            reveal_rect: None,
393            adapt: HashMap::new(),
394            repaint: false,
395            relayout: false,
396            light: Spring::default(),
397            tilt: Vec2::ZERO,
398            scroll_energy: 0.0,
399            toasts: Vec::new(),
400            open_popups: HashMap::new(),
401            access: Access::default(),
402            drawn: Vec::new(),
403            drag: None,
404            morphs: HashMap::new(),
405        }
406    }
407
408    // ----- frame -----
409
410    /// Starts a frame of `size` points at `pixels_per_point`, `time` seconds after
411    /// the start, with the input `events`. The window host and
412    /// [`Headless`](crate::headless::Headless) call it for you.
413    pub fn begin_frame(&mut self, size: Vec2, ppp: f32, time: f64, events: &[Event]) {
414        // A long idle gap must not turn into one huge animation step.
415        self.dt = ((time - self.time) as f32).clamp(0.0, 1.0 / 24.0);
416        self.time = time;
417        self.frame += 1;
418        self.pixels_per_point = ppp;
419        self.screen = Rect::from_min_size(Vec2::ZERO, size);
420        self.cursor = Cursor::Default;
421        self.repaint = false;
422        self.relayout = false;
423        self.repaint_at = None;
424        self.hidden = 0;
425        self.ime_area = None;
426        self.reveal_rect = None;
427        self.input.begin(events, time);
428        self.access.nodes.clear();
429        self.access.requests.clear();
430        for e in events {
431            if let Event::Access(id, a) = e {
432                self.access_request(*id, a.clone());
433            }
434        }
435        self.paint.begin(ppp);
436        self.paint.glass_tint = self.theme.glass_tint;
437        self.paint.reduce_transparency = self.theme.reduce_transparency;
438        self.paint.increase_contrast = self.theme.increase_contrast;
439        self.text.begin_frame(ppp, time);
440
441        std::mem::swap(&mut self.hits, &mut self.prev_hits);
442        self.hits.clear();
443        self.hovered = None;
444        self.scroll_target = [None; 2];
445        if let Some(p) = self.input.pointer {
446            let key = |h: &Hit, i: usize| {
447                let l = &self.layers[h.layer];
448                (l.order, l.z, i)
449            };
450            type Best = Option<((Order, u64, usize), Hit)>;
451            let mut best: Best = None;
452            let mut best_scroll: [Best; 2] = [None; 2];
453            for (i, h) in self.prev_hits.iter().enumerate() {
454                if !h.rect.contains(p) {
455                    continue;
456                }
457                let k = key(h, i);
458                if h.scroll == 0 {
459                    if best.as_ref().is_none_or(|b| k > b.0) {
460                        best = Some((k, *h));
461                    }
462                    continue;
463                }
464                for (axis, slot) in best_scroll.iter_mut().enumerate() {
465                    if h.scroll & (1 << axis) != 0 && slot.as_ref().is_none_or(|b| k > b.0) {
466                        *slot = Some((k, *h));
467                    }
468                }
469            }
470            // A scroll area below an opaque layer does not scroll.
471            let top = best.map(|(k, _)| (k.0, k.1));
472            for (axis, s) in best_scroll.iter().enumerate() {
473                if let Some((ks, s)) = s
474                    && top.is_none_or(|t| (ks.0, ks.1) >= t)
475                {
476                    self.scroll_target[axis] = Some(s.id);
477                }
478            }
479            if let Some((_, h)) = best {
480                self.hovered = Some(h.id);
481                if self.input.pressed {
482                    if h.sense != Sense::Hover {
483                        self.active = Some(h.id);
484                    }
485                    // Raise the clicked window.
486                    self.z_top += 1;
487                    let z = self.z_top;
488                    self.layers[h.layer].z = z;
489                }
490            }
491        }
492        if self.input.pressed {
493            self.focus_by_key = false;
494            if self.hovered != self.focus {
495                self.focus = None;
496            }
497        }
498        if self.drag.is_some() && self.input.take_key(Key::Escape) {
499            self.drag = None;
500            self.active = None;
501        }
502        if self.input.take_key(Key::Tab) {
503            self.move_focus(if self.input.modifiers.shift { -1 } else { 1 });
504        }
505        self.focus_list.clear();
506        self.focus_seen = false;
507
508        // The virtual light stays put, except for device tilt and a hint of
509        // movement while scrolling.
510        let mut target = self.tilt.x + self.scroll_energy * 0.22;
511        self.scroll_energy *= (-self.dt * 9.0).exp();
512        if self.theme.reduce_motion {
513            target = 0.0;
514        }
515        if self.light.step(target, Tuning::new(0.55, 1.0), self.dt) {
516            self.repaint = true;
517        }
518    }
519
520    /// Ends the frame and builds the draw list. The window host and
521    /// [`Headless`](crate::headless::Headless) call it for you.
522    pub fn end_frame(&mut self) {
523        // A focused widget is revealed once. Give up on one that is not drawn.
524        self.reveal = match self.reveal {
525            Some(_) if self.reveal_rect.is_some() => None,
526            Some((id, frames)) if frames > 0 => Some((id, frames - 1)),
527            _ => None,
528        };
529        crate::widgets::toast::show_toasts(self);
530        if self.input.released || !self.input.down {
531            self.active = None;
532            if self.drag.take().is_some() {
533                self.repaint = true;
534            }
535        }
536        if self.drag.is_some() {
537            self.repaint = true;
538        }
539        if self.focus.is_some() && !self.focus_seen {
540            self.focus = None;
541        }
542        // Forget the state of widgets that have not been drawn for a while.
543        // Both the frames and the time must have passed, so a window that
544        // draws all the time, such as one with a level meter, keeps the state
545        // of a page it left a moment ago.
546        if self.frame.is_multiple_of(600) {
547            let (f, now, keep) = (self.frame, self.time, self.retention);
548            self.states.retain(|_, v| f - v.1 < 1200 || now - v.2 < keep);
549            self.adapt.retain(|_, a| f - a.used < 1200 || now - a.used_time < keep);
550            self.morphs.retain(|_, m| f - m.seen < 1200);
551        }
552        let mut order: Vec<usize> =
553            (0..self.layers.len()).filter(|&i| self.layers[i].used == self.frame).collect();
554        order.sort_by_key(|&i| (self.layers[i].order, self.layers[i].z, i));
555        self.paint.flatten(&order);
556        self.drawn = order;
557        let a = self.light.value;
558        let d = &mut self.paint.data;
559        d.clear = self.clear_color.to_array();
560        d.light = [a.sin(), -a.cos()];
561        d.time = self.time as f32;
562        d.ppp = self.pixels_per_point;
563        d.quality = self.quality;
564        if self.input.pending() || self.text.needs_rebuild() {
565            self.repaint = true;
566        }
567        // Glyphs drawn before the atlas grew point at the old layout of it.
568        if self.text.take_grown() {
569            self.relayout = true;
570        }
571    }
572
573    /// Asks for another frame as soon as possible. Call it every frame while
574    /// something animates. An idle window draws nothing.
575    pub fn request_repaint(&mut self) {
576        self.repaint = true;
577    }
578    /// Returns `true` if another frame was asked for.
579    pub fn wants_repaint(&self) -> bool {
580        self.repaint
581    }
582    /// Asks for a frame once `delay` has passed, such as the next blink of a
583    /// caret or the next reading of a meter. The window sleeps until then.
584    /// The earliest request of a frame wins.
585    ///
586    /// ```
587    /// # use rust_glass::prelude::*;
588    /// # fn f(ctx: &mut Context) {
589    /// // A meter that updates 25 times a second.
590    /// ctx.request_repaint_after(std::time::Duration::from_millis(40));
591    /// # }
592    /// ```
593    pub fn request_repaint_after(&mut self, delay: std::time::Duration) {
594        let at = self.time + delay.as_secs_f64();
595        self.repaint_at = Some(self.repaint_at.map_or(at, |old| old.min(at)));
596    }
597    /// Returns when a frame was asked for with [`Self::request_repaint_after`],
598    /// in seconds since the start like [`Self::time`].
599    pub fn repaint_deadline(&self) -> Option<f64> {
600        self.repaint_at
601    }
602    /// Returns a [`Waker`] that asks for a frame from another thread, or
603    /// `None` without a window, as in [`Headless`](crate::headless::Headless).
604    pub fn waker(&self) -> Option<Waker> {
605        self.waker.clone()
606    }
607    pub(crate) fn set_waker(&mut self, waker: Waker) {
608        self.waker = Some(waker);
609    }
610    /// Keeps the state of widgets that are not drawn for at least `keep`.
611    /// State is dropped only when both this time and 1200 frames have passed
612    /// since it was last used. The default is five minutes.
613    pub fn set_retention(&mut self, keep: std::time::Duration) {
614        self.retention = keep.as_secs_f64();
615    }
616    /// Tells the host that sizes used for layout this frame were guesses. The
617    /// frame runs again before it is shown.
618    ///
619    /// Call it too when input changed state that was already drawn earlier in
620    /// the same frame. A page drawn before the sidebar that switches it would
621    /// otherwise show the old page for one more frame. [`nav_list`](crate::prelude::nav_list)
622    /// does this for you.
623    pub fn request_relayout(&mut self) {
624        if self.hidden == 0 {
625            self.relayout = true;
626        }
627    }
628
629    /// Runs `f` without showing anything it draws. Layout, text shaping,
630    /// animations and widget state work as usual, but nothing is painted,
631    /// nothing reacts to the pointer, and nothing takes focus or appears to
632    /// screen readers. Use it to prepare a page before it is shown, so its
633    /// first frame is as fast as the ones after it.
634    ///
635    /// ```
636    /// # use rust_glass::prelude::*;
637    /// # fn settings(ui: &mut Ui) {}
638    /// # fn f(ctx: &mut Context, area: Rect) {
639    /// // Same region id as when the page is shown, so it shares the state.
640    /// ctx.hidden(|ctx| region(ctx, "settings", area, settings));
641    /// # }
642    /// ```
643    pub fn hidden<R>(&mut self, f: impl FnOnce(&mut Context) -> R) -> R {
644        let saved = self.enter_hidden();
645        let out = f(self);
646        self.leave_hidden(saved);
647        out
648    }
649    pub(crate) fn enter_hidden(&mut self) -> (bool, bool, Option<f64>) {
650        self.hidden += 1;
651        (self.repaint, self.relayout, self.repaint_at)
652    }
653    pub(crate) fn leave_hidden(&mut self, saved: (bool, bool, Option<f64>)) {
654        self.hidden -= 1;
655        // What is not shown asks for no frames.
656        (self.repaint, self.relayout, self.repaint_at) = saved;
657    }
658    /// Returns `true` inside [`Self::hidden`].
659    pub fn is_hidden(&self) -> bool {
660        self.hidden > 0
661    }
662    /// Returns `true` if the frame should run again before it is shown.
663    pub fn wants_relayout(&self) -> bool {
664        self.relayout
665    }
666
667    /// Sets the tilt of the device in radians. It turns the highlights on glass.
668    pub fn set_tilt(&mut self, tilt: Vec2) {
669        self.tilt = tilt;
670    }
671    /// Adds to the movement that briefly turns the highlights while scrolling.
672    pub fn add_scroll_energy(&mut self, v: f32) {
673        self.scroll_energy = (self.scroll_energy + v).clamp(-1.0, 1.0);
674    }
675
676    // ----- memory -----
677
678    /// Returns a copy of the state stored for `id`, or the default if there is
679    /// none.
680    pub fn get<T: Clone + Default + 'static>(&mut self, id: Id) -> T {
681        self.try_get(id).unwrap_or_default()
682    }
683    /// Returns a copy of the state stored for `id`, if there is any.
684    pub fn try_get<T: Clone + 'static>(&mut self, id: Id) -> Option<T> {
685        let (f, now) = (self.frame, self.time);
686        let (b, used, at) = self.states.get_mut(&(id, TypeId::of::<T>()))?;
687        (*used, *at) = (f, now);
688        b.downcast_ref::<T>().cloned()
689    }
690    /// Moves the state out, leaving nothing stored. Cheaper than [`Self::get`] for
691    /// large state. Put it back with [`Self::set`].
692    pub fn take<T: Default + 'static>(&mut self, id: Id) -> T {
693        match self.states.remove(&(id, TypeId::of::<T>())) {
694            Some((b, ..)) => b.downcast::<T>().map(|b| *b).unwrap_or_default(),
695            None => T::default(),
696        }
697    }
698    /// Stores state for `id`. State that is not used for a while is dropped,
699    /// see [`Self::set_retention`].
700    pub fn set<T: 'static>(&mut self, id: Id, value: T) {
701        let (f, now) = (self.frame, self.time);
702        // Overwrite the stored value in place, so state kept from frame to
703        // frame costs no allocation.
704        match self.states.entry((id, TypeId::of::<T>())) {
705            std::collections::hash_map::Entry::Occupied(mut e) => {
706                let (b, used, at) = e.get_mut();
707                match b.downcast_mut::<T>() {
708                    Some(v) => *v = value,
709                    None => *b = Box::new(value),
710                }
711                (*used, *at) = (f, now);
712            }
713            std::collections::hash_map::Entry::Vacant(e) => {
714                e.insert((Box::new(value), f, now));
715            }
716        }
717    }
718
719    /// Moves a value stored under `id` towards `target` on a spring and returns
720    /// it. Keeps asking for frames until it arrives.
721    pub fn animate(&mut self, id: Id, target: f32, tuning: Tuning) -> f32 {
722        let mut s: Spring = self.get(id);
723        if s.step(target, self.tuning(tuning), self.dt) {
724            self.repaint = true;
725        }
726        self.set(id, s);
727        s.value
728    }
729    /// Like [`Self::animate`], towards 1 when `on` and 0 when off.
730    pub fn animate_bool(&mut self, id: Id, on: bool, tuning: Tuning) -> f32 {
731        self.animate(id, on as u32 as f32, tuning)
732    }
733    /// Like [`Self::animate`], for a point. Returns the spring, so you can read
734    /// its velocity too.
735    pub fn animate_vec2(&mut self, id: Id, target: Vec2, tuning: Tuning) -> Spring2d {
736        let mut s: Spring2d = self.get(id);
737        if s.step(target, self.tuning(tuning), self.dt) {
738            self.repaint = true;
739        }
740        self.set(id, s);
741        s
742    }
743
744    /// Returns `tuning` as it should be used: unchanged, or short and without
745    /// overshoot when [`Theme::reduce_motion`] is on.
746    pub fn tuning(&self, tuning: Tuning) -> Tuning {
747        if self.theme.reduce_motion { Tuning::new(tuning.response.min(0.25), 1.0) } else { tuning }
748    }
749
750    // ----- layers -----
751
752    /// Returns the index of the layer `id`, created on first use. Layers draw in
753    /// [`Order`], and within an order the one used or clicked last is on top.
754    pub fn layer(&mut self, id: Id, order: Order) -> usize {
755        let i = match self.layers.iter().position(|l| l.id == id) {
756            // Content that is not shown does not raise or keep its layer.
757            Some(i) if self.hidden > 0 => {
758                self.paint.ensure_layer(i);
759                return i;
760            }
761            Some(i) => i,
762            None => {
763                self.z_top += 1;
764                // Reuse slots of layers that are gone.
765                let f = self.frame;
766                let l = Layer { id, order, z: self.z_top, used: f };
767                match self.layers.iter().position(|l| f - l.used > 240) {
768                    Some(i) => {
769                        self.layers[i] = l;
770                        i
771                    }
772                    None => {
773                        self.layers.push(l);
774                        self.layers.len() - 1
775                    }
776                }
777            }
778        };
779        if self.layers[i].used + 1 < self.frame {
780            // Reappearing layers go to the front of their order.
781            self.z_top += 1;
782            self.layers[i].z = self.z_top;
783        }
784        self.layers[i].order = order;
785        self.layers[i].used = self.frame;
786        self.paint.ensure_layer(i);
787        i
788    }
789
790    /// Returns a painter for `layer` that clips to `clip`.
791    pub fn painter(&mut self, layer: usize, clip: Rect) -> Painter<'_> {
792        self.paint.ensure_layer(layer);
793        Painter {
794            paint: &mut self.paint,
795            text: &mut self.text,
796            layer,
797            clip,
798            mask: 0,
799            opacity: 1.0,
800            hidden: self.hidden > 0,
801        }
802    }
803
804    /// Returns a painter for the whole window, behind all widgets.
805    pub fn background(&mut self) -> Painter<'_> {
806        let l = self.layer(Id::new("background"), Order::Background);
807        // The scene texture is padded; cover that too.
808        let r = self.screen.expand(64.0);
809        self.painter(l, r)
810    }
811
812    // ----- input -----
813
814    /// Registers `rect` on `layer` for input and returns what happened to it.
815    /// Parts outside `clip` do not react. Only the topmost widget under the
816    /// pointer is hovered.
817    pub fn interact(&mut self, id: Id, rect: Rect, clip: Rect, layer: usize, sense: Sense) -> Response {
818        if self.hidden > 0 {
819            return Response::idle(id, rect, None);
820        }
821        if self.reveal.is_some_and(|(wanted, _)| wanted == id) {
822            self.reveal_rect = Some(rect);
823        }
824        let visible = rect.intersect(clip);
825        if visible.is_positive() {
826            self.hits.push(Hit { id, rect: visible, layer, sense, scroll: 0 });
827        }
828        let hovered = self.hovered == Some(id) && (self.active.is_none() || self.active == Some(id));
829        let held = self.active == Some(id) && (self.input.down || self.input.released);
830        let focused = self.focus == Some(id);
831        let key_click = (focused
832            && self.focus_by_key
833            && matches!(sense, Sense::Click | Sense::Press)
834            && (self.input.key(Key::Enter) || self.input.key(Key::Space)))
835            || (sense != Sense::Hover && self.access_requested(id, &Action::Click));
836        let pointer_click = match sense {
837            Sense::Hover => false,
838            Sense::Press => held && self.input.pressed,
839            Sense::Click | Sense::Drag => held && self.input.released && hovered,
840        };
841        // The app reacts to a click after this frame has laid out what it
842        // showed before, so the next frame has to follow without waiting for
843        // more input.
844        if (pointer_click || key_click || (held && self.input.released)) && self.hidden == 0 {
845            self.repaint = true;
846        }
847        Response {
848            id,
849            rect,
850            hovered,
851            held: held && self.input.down,
852            pressed: held && self.input.pressed,
853            released: held && self.input.released,
854            clicked: pointer_click || key_click,
855            double_clicked: held && self.input.pressed && self.input.double_clicked,
856            secondary_clicked: hovered && self.input.secondary_clicked,
857            focused,
858            changed: false,
859            delta: if held { self.input.delta } else { Vec2::ZERO },
860            pointer: self.input.pointer,
861        }
862    }
863
864    /// Lets `id` take keyboard focus with Tab. Call it every frame the widget is
865    /// visible.
866    pub fn focusable(&mut self, id: Id) {
867        if self.hidden > 0 {
868            return;
869        }
870        self.focus_list.push(id);
871        if self.access.on
872            && let Some(n) = self.access.nodes.iter_mut().rev().find(|n| n.id == id)
873        {
874            n.focusable = true;
875        }
876        if self.focus == Some(id) {
877            self.focus_seen = true;
878        }
879    }
880    /// Gives keyboard focus to `id`, or takes it away with `None`.
881    pub fn set_focus(&mut self, id: Option<Id>) {
882        self.focus = id;
883        self.focus_seen = true;
884    }
885    /// Returns `true` if `id` has focus from the keyboard, which is when the focus
886    /// ring shows.
887    pub fn shows_focus(&self, id: Id) -> bool {
888        self.focus == Some(id) && self.focus_by_key
889    }
890    fn move_focus(&mut self, dir: i32) {
891        if self.focus_list.is_empty() {
892            return;
893        }
894        let n = self.focus_list.len() as i32;
895        let at = self.focus.and_then(|f| self.focus_list.iter().position(|x| *x == f));
896        let next = match at {
897            Some(i) => (i as i32 + dir).rem_euclid(n),
898            None if dir > 0 => 0,
899            None => n - 1,
900        };
901        self.focus = Some(self.focus_list[next as usize]);
902        self.focus_by_key = true;
903        self.reveal = self.focus.map(|id| (id, 3));
904    }
905
906    /// Registers a scroll area and returns the wheel movement it receives, on
907    /// both axes. `rect` is taken as given, without a clip. Inside a clipped
908    /// region use [`Ui::scroll_wheel`](crate::Ui::scroll_wheel), which cuts
909    /// it to the clip.
910    pub fn scroll_area(&mut self, id: Id, rect: Rect, layer: usize) -> Vec2 {
911        self.scroll_area_axes(id, rect, layer, true, true)
912    }
913
914    /// Registers a scroll area that scrolls on the given axes and returns the
915    /// wheel movement it receives. Movement on the other axis goes to the scroll
916    /// area around it, so a horizontal row inside a page leaves vertical scrolling
917    /// to the page.
918    pub fn scroll_area_axes(&mut self, id: Id, rect: Rect, layer: usize, x: bool, y: bool) -> Vec2 {
919        if self.hidden > 0 || !rect.is_positive() {
920            return Vec2::ZERO;
921        }
922        let scroll = x as u8 | (y as u8) << 1;
923        self.hits.push(Hit { id, rect, layer, sense: Sense::Hover, scroll });
924        let s = self.input.scroll;
925        vec2(
926            if x && self.scroll_target[0] == Some(id) { s.x } else { 0.0 },
927            if y && self.scroll_target[1] == Some(id) { s.y } else { 0.0 },
928        )
929    }
930
931    /// Returns `true` while `id` is being pressed or dragged.
932    pub fn is_active(&self, id: Id) -> bool {
933        self.active == Some(id)
934    }
935    /// Makes `id` the target of the current press or drag.
936    pub fn grab(&mut self, id: Id) {
937        self.active = Some(id);
938    }
939    /// Returns `true` while any widget is being pressed or dragged.
940    pub fn any_active(&self) -> bool {
941        self.active.is_some()
942    }
943
944    // ----- glass -----
945
946    /// Returns how the glass element `id` should look over what is behind it.
947    /// With `adaptive` set, small elements switch between light and dark with the
948    /// backdrop. Large surfaces keep the theme appearance.
949    pub fn backdrop(&mut self, id: Id, adaptive: bool) -> Backdrop {
950        let dark_theme = self.theme.dark;
951        let theme_adaptive = self.theme.adaptive;
952        let f = self.frame;
953        let dt = self.dt;
954        let now = self.time;
955        let a = self.adapt.entry(id.0).or_insert_with(|| Adapt {
956            mean: if dark_theme { 0.1 } else { 0.9 },
957            is_dark: dark_theme,
958            ..Default::default()
959        });
960        a.used = f;
961        a.used_time = now;
962        if !adaptive || !theme_adaptive {
963            a.is_dark = dark_theme;
964        } else if a.known {
965            // Hysteresis keeps the style stable over mid tones. Dark appearance
966            // only gives way to really bright content and the other way round.
967            let (to_dark, to_light) = if dark_theme { (0.62, 0.78) } else { (0.30, 0.44) };
968            if a.is_dark && a.mean > to_light {
969                a.is_dark = false;
970            } else if !a.is_dark && a.mean < to_dark {
971                a.is_dark = true;
972            }
973        }
974        let mut moving = a.dark.step(a.is_dark as u32 as f32, Tuning::new(0.32, 1.0), dt);
975        moving |= a.boost.step((a.dev * 4.0).min(1.0), Tuning::new(0.4, 1.0), dt);
976        let out =
977            Backdrop { darkness: a.dark.value.clamp(0.0, 1.0), shadow_boost: a.boost.value.clamp(0.0, 1.0) };
978        if moving {
979            self.repaint = true;
980        }
981        out
982    }
983
984    /// Feed measurements from the renderer. Returns true when a redraw would
985    /// look different.
986    pub(crate) fn apply_stats(&mut self, stats: &[(u64, f32, f32)]) -> bool {
987        let mut changed = false;
988        for &(k, mean, dev) in stats {
989            if let Some(a) = self.adapt.get_mut(&k) {
990                if !a.known {
991                    changed = true;
992                    a.known = true;
993                    // First measurement: adopt without a visible transition.
994                    if self.theme.adaptive && a.frame_young(self.frame) {
995                        a.dark = Spring::default();
996                    }
997                }
998                changed |= (a.mean - mean).abs() > 0.012 || (a.dev - dev).abs() > 0.02;
999                a.mean = mean;
1000                a.dev = dev;
1001            }
1002        }
1003        changed
1004    }
1005
1006    /// Adapts `glass` to what is behind it and has the backdrop measured for the
1007    /// next frame. Call it before painting glass you build yourself.
1008    pub fn prepare_glass(&mut self, id: Id, glass: &mut Glass, adaptive: bool) -> Backdrop {
1009        let a = self.backdrop(id, adaptive);
1010        glass.darkness = a.darkness;
1011        glass.shadow_boost = a.shadow_boost;
1012        glass.stat_key = Some(id.0);
1013        a
1014    }
1015
1016    // ----- accessibility -----
1017
1018    /// Turns collecting the accessibility tree on or off. The window host turns it
1019    /// on when a screen reader asks for the tree.
1020    pub fn set_accessibility(&mut self, on: bool) {
1021        self.access.on = on;
1022        self.repaint = true;
1023    }
1024    /// Returns `true` while the accessibility tree is collected.
1025    pub fn accessibility(&self) -> bool {
1026        self.access.on
1027    }
1028
1029    /// Describes an element for screen readers. Returns `None` while none is
1030    /// listening, so building labels costs nothing then.
1031    /// [`Ui::access`](crate::Ui::access) fills in the layer for you.
1032    pub fn access_node(&mut self, id: Id, role: Role, rect: Rect, layer: usize) -> Option<&mut Node> {
1033        if !self.access.on || self.hidden > 0 {
1034            return None;
1035        }
1036        let mut n = Node::new(id, role, rect);
1037        n.layer = layer;
1038        n.focusable = self.focus_list.contains(&id);
1039        self.access.nodes.push(n);
1040        self.access.nodes.last_mut()
1041    }
1042
1043    /// Labels the node `id` described this frame, for widgets without text of
1044    /// their own, such as sliders.
1045    pub fn access_label(&mut self, id: Id, label: impl Into<String>) {
1046        if let Some(n) = self.access.nodes.iter_mut().rev().find(|n| n.id == id) {
1047            n.label = label.into();
1048        }
1049    }
1050
1051    /// Labels every node described since `from` (an index into
1052    /// [`Self::access_nodes`]) that has no label yet. Settings rows use it to name
1053    /// the switch or slider at their end.
1054    pub fn access_label_since(&mut self, from: usize, label: &str) {
1055        for n in self.access.nodes.iter_mut().skip(from) {
1056            if n.label.is_empty() && n.role != Role::Label {
1057                n.label = label.to_string();
1058            }
1059        }
1060    }
1061
1062    /// Returns the nodes described so far this frame.
1063    pub fn access_nodes(&self) -> &[Node] {
1064        &self.access.nodes
1065    }
1066
1067    /// Returns `true` if a screen reader asked for `action` on `id` this frame.
1068    pub fn access_requested(&self, id: Id, action: &Action) -> bool {
1069        self.access.requests.iter().any(|(i, x)| *i == id && x == action)
1070    }
1071
1072    /// Returns the text a screen reader wants to put into the field `id`.
1073    pub fn take_access_text(&mut self, id: Id) -> Option<String> {
1074        let i =
1075            self.access.requests.iter().position(|(i, a)| *i == id && matches!(a, Action::SetValue(_)))?;
1076        match self.access.requests.remove(i).1 {
1077            Action::SetValue(s) => Some(s),
1078            _ => None,
1079        }
1080    }
1081
1082    /// Returns the value a screen reader wants to give the slider or stepper `id`.
1083    pub fn take_access_number(&mut self, id: Id) -> Option<f64> {
1084        let i =
1085            self.access.requests.iter().position(|(i, a)| *i == id && matches!(a, Action::SetNumber(_)))?;
1086        match self.access.requests.remove(i).1 {
1087            Action::SetNumber(v) => Some(v),
1088            _ => None,
1089        }
1090    }
1091
1092    fn access_request(&mut self, id: Id, a: Action) {
1093        self.repaint = true;
1094        match &a {
1095            Action::Focus => {
1096                self.focus = Some(id);
1097                self.focus_by_key = true;
1098                self.reveal = Some((id, 3));
1099            }
1100            Action::Blur => {
1101                if self.focus == Some(id) {
1102                    self.focus = None;
1103                }
1104            }
1105            // Steps arrive as arrow keys, which every adjustable widget handles.
1106            Action::Increment | Action::Decrement => {
1107                self.focus = Some(id);
1108                self.focus_by_key = true;
1109                let k = if a == Action::Increment { Key::Right } else { Key::Left };
1110                self.input.keys.push((k, Default::default()));
1111            }
1112            Action::ReplaceSelection(t) => {
1113                self.focus = Some(id);
1114                self.input.text.push_str(t);
1115            }
1116            Action::Click | Action::SetValue(_) | Action::SetNumber(_) => {}
1117        }
1118        self.access.requests.push((id, a));
1119    }
1120
1121    /// Returns the full accessibility tree of the last frame for AccessKit.
1122    pub fn access_update(&self, title: &str) -> accesskit::TreeUpdate {
1123        let layers: Vec<LayerInfo> = self
1124            .drawn
1125            .iter()
1126            .map(|&i| LayerInfo { index: i, id: self.layers[i].id, order: self.layers[i].order })
1127            .collect();
1128        crate::accessibility::tree(
1129            &self.access.nodes,
1130            &layers,
1131            self.focus,
1132            self.pixels_per_point,
1133            self.screen,
1134            title,
1135        )
1136    }
1137
1138    // ----- morphing between views -----
1139
1140    /// Moves an element from the view that showed it before to the view that
1141    /// shows it now, such as a cover that grows from a grid into a detail
1142    /// page.
1143    ///
1144    /// Call it every frame the element is drawn, with the same `key` from
1145    /// every view, the `view` that draws it, and where that view puts it.
1146    /// Draw the element at the returned rectangle. While the view stays the
1147    /// same, the result is `rect`. When the view changes, it travels from the
1148    /// old place to `rect` on a spring. An element that was not drawn for 20
1149    /// seconds starts over where it is.
1150    ///
1151    /// ```
1152    /// # use rust_glass::prelude::*;
1153    /// # fn f(ui: &mut Ui, image: ImageId, open: bool) {
1154    /// let key = Id::new(("cover", 7));
1155    /// let (view, place) = if open {
1156    ///     (Id::new("detail"), rect(40.0, 40.0, 320.0, 320.0))
1157    /// } else {
1158    ///     (Id::new("grid"), ui.allocate(vec2(120.0, 120.0)))
1159    /// };
1160    /// let shown = ui.ctx.morph(key, view, place);
1161    /// ui.painter().image(shown, 14.0, image, rect(0.0, 0.0, 1.0, 1.0), Color::WHITE);
1162    /// # }
1163    /// ```
1164    pub fn morph(&mut self, key: Id, view: Id, rect: Rect) -> Rect {
1165        let frame = self.frame;
1166        let fresh = Morph { view, shape: SpringRect::new(rect), target: rect, moving: false, seen: frame };
1167        let mut morph = match self.morphs.get(&key) {
1168            Some(m) if frame - m.seen < 1200 => *m,
1169            _ => fresh,
1170        };
1171        if morph.view != view {
1172            morph.view = view;
1173            morph.moving = true;
1174        } else if morph.moving {
1175            // The view moved its place while the element travels to it, as
1176            // when the page scrolls. Carry the element along, so it does not
1177            // trail behind or drift once it seems to have arrived.
1178            let carried = rect.center() - morph.target.center();
1179            morph.shape.center.x.value += carried.x;
1180            morph.shape.center.y.value += carried.y;
1181        }
1182        morph.target = rect;
1183        let shown = if morph.moving {
1184            let center = self.tuning(Tuning::new(0.38, 0.86));
1185            let size = self.tuning(Tuning::new(0.38, 0.94));
1186            let springing = morph.shape.step(rect, center, size, self.dt);
1187            // Done once it is a fraction of a point away and nearly still,
1188            // rather than when the spring has died out completely.
1189            let s = &morph.shape;
1190            let off = (s.rect().min - rect.min).abs().max((s.rect().max - rect.max).abs());
1191            let speed = s.center.velocity().abs().max(s.size.velocity().abs());
1192            morph.moving = springing && (off.x.max(off.y) > 0.25 || speed.x.max(speed.y) > 8.0);
1193            self.repaint = true;
1194            if morph.moving { morph.shape.rect() } else { rect }
1195        } else {
1196            morph.shape = SpringRect::new(rect);
1197            rect
1198        };
1199        morph.seen = frame;
1200        self.morphs.insert(key, morph);
1201        shown
1202    }
1203
1204    /// Returns `true` while the element `key` travels between views.
1205    pub fn is_morphing(&self, key: Id) -> bool {
1206        self.morphs.get(&key).is_some_and(|m| m.moving)
1207    }
1208
1209    // ----- drag and drop -----
1210
1211    /// Picks up `payload`. [`Ui::drag_source`](crate::Ui::drag_source) calls it
1212    /// for you.
1213    pub fn start_drag(&mut self, source: Id, payload: Box<dyn Any>, grab: Vec2, size: Vec2) {
1214        self.drag = Some(Drag { source, payload, grab, size });
1215        self.active = Some(source);
1216        self.repaint = true;
1217    }
1218    /// Returns the id of the widget being dragged.
1219    pub fn dragged_id(&self) -> Option<Id> {
1220        self.drag.as_ref().map(|d| d.source)
1221    }
1222    /// Returns the payload being dragged, if it has type `P`.
1223    pub fn dragged<P: Clone + 'static>(&self) -> Option<P> {
1224        self.drag.as_ref()?.payload.downcast_ref::<P>().cloned()
1225    }
1226    /// Returns where the dragged item is drawn: at the pointer, keeping the
1227    /// offset where it was grabbed.
1228    pub fn drag_rect(&self) -> Option<Rect> {
1229        let d = self.drag.as_ref()?;
1230        let p = self.input.pointer?;
1231        Some(Rect::from_min_size(p - d.grab, d.size))
1232    }
1233    /// Returns `true` while a payload of type `P` is dragged over `rect`.
1234    pub fn drag_over<P: 'static>(&self, rect: Rect) -> bool {
1235        self.hidden == 0
1236            && self.drag.as_ref().is_some_and(|d| d.payload.is::<P>())
1237            && self.input.pointer.is_some_and(|p| rect.contains(p))
1238    }
1239    /// Returns the payload when it is released over `rect`. Only the first caller
1240    /// gets it.
1241    pub fn take_drop<P: 'static>(&mut self, rect: Rect) -> Option<P> {
1242        if !self.input.released || !self.drag_over::<P>(rect) {
1243            return None;
1244        }
1245        let d = self.drag.take()?;
1246        self.repaint = true;
1247        d.payload.downcast::<P>().ok().map(|b| *b)
1248    }
1249
1250    // ----- misc -----
1251
1252    /// Adds an image of `width` by `height` pixels in RGBA order, 8 bits per
1253    /// channel, and returns its id. Draw it with [`Ui::image`](crate::Ui::image)
1254    /// or [`Painter::image`](crate::Painter::image).
1255    pub fn add_image(&mut self, width: u32, height: u32, rgba: Vec<u8>) -> ImageId {
1256        let id = ImageId(self.next_image);
1257        self.next_image += 1;
1258        self.uploads.push(ImageUpload { id, w: width, h: height, rgba });
1259        id
1260    }
1261
1262    /// Frees an image added with [`Self::add_image`]. Drawing it afterwards shows
1263    /// nothing.
1264    pub fn remove_image(&mut self, id: ImageId) {
1265        self.removed_images.push(id);
1266    }
1267
1268    /// Hides the window. The app keeps running; [`Self::show_window`] brings
1269    /// it back.
1270    pub fn hide_window(&mut self) {
1271        self.host_commands.push(HostCommand::Hide);
1272    }
1273    /// Shows the window and brings it to the front.
1274    pub fn show_window(&mut self) {
1275        self.host_commands.push(HostCommand::Show);
1276    }
1277
1278    /// Puts `text` on the clipboard.
1279    pub fn copy_text(&mut self, text: impl Into<String>) {
1280        self.host_commands.push(HostCommand::Copy(text.into()));
1281    }
1282
1283    /// Returns the size of `text` in one line at `size` points.
1284    pub fn measure(&mut self, text: &str, size: f32, weight: Weight) -> Vec2 {
1285        self.text.layout(text, &TextStyle::new(size).weight(weight)).size
1286    }
1287
1288    /// Shows a short message at the top of the window for a few seconds.
1289    pub fn toast(&mut self, icon: Option<crate::icon::Icon>, text: impl Into<String>) {
1290        self.toasts.push(crate::widgets::toast::ToastState::new(icon, text.into()));
1291    }
1292    pub(crate) fn take_toasts(&mut self) -> Vec<crate::widgets::toast::ToastState> {
1293        std::mem::take(&mut self.toasts)
1294    }
1295    pub(crate) fn put_toasts(&mut self, t: Vec<crate::widgets::toast::ToastState>) {
1296        self.toasts = t;
1297    }
1298
1299    /// Returns `true` if the popup `id` is open.
1300    pub fn popup_open(&self, id: Id) -> bool {
1301        self.open_popups.get(&id).copied().unwrap_or(false)
1302    }
1303    /// Opens or closes the popup `id`.
1304    pub fn set_popup(&mut self, id: Id, open: bool) {
1305        self.open_popups.insert(id, open);
1306        self.repaint = true;
1307    }
1308    /// Opens the popup `id` if it is closed, and closes it if it is open.
1309    pub fn toggle_popup(&mut self, id: Id) {
1310        let o = !self.popup_open(id);
1311        self.set_popup(id, o);
1312    }
1313
1314    /// Returns `true` if the pointer was pressed this frame outside `rect`.
1315    pub fn pressed_outside(&self, rect: Rect) -> bool {
1316        self.input.pressed && self.input.pointer.is_some_and(|p| !rect.contains(p))
1317    }
1318
1319    /// Returns the pointer position, or `fallback` while the pointer is outside
1320    /// the window.
1321    pub fn pointer_or(&self, fallback: Vec2) -> Vec2 {
1322        self.input.pointer.unwrap_or(fallback)
1323    }
1324}
1325
1326impl Adapt {
1327    fn frame_young(&self, frame: u64) -> bool {
1328        self.used + 4 >= frame
1329    }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    use super::*;
1335    use crate::geometry::rect;
1336
1337    fn frame(ctx: &mut Context, ev: &[Event], f: impl FnOnce(&mut Context)) {
1338        let t = ctx.time + 1.0 / 60.0;
1339        ctx.begin_frame(vec2(200.0, 200.0), 1.0, t, ev);
1340        f(ctx);
1341        ctx.end_frame();
1342    }
1343
1344    #[test]
1345    fn topmost_layer_gets_the_click() {
1346        let mut c = Context::new();
1347        let (low, high) = (Id::new("low"), Id::new("high"));
1348        let mut got = (false, false);
1349        let mut run = |c: &mut Context, ev: &[Event]| {
1350            frame(c, ev, |c| {
1351                let a = c.layer(Id::new("a"), Order::Content);
1352                let b = c.layer(Id::new("b"), Order::Popup);
1353                let r = rect(0.0, 0.0, 100.0, 100.0);
1354                got.1 |= c.interact(high, r, r, b, Sense::Click).clicked;
1355                got.0 |= c.interact(low, r, r, a, Sense::Click).clicked;
1356            });
1357        };
1358        run(&mut c, &[Event::PointerMoved(vec2(10.0, 10.0))]);
1359        run(&mut c, &[Event::PointerDown]);
1360        run(&mut c, &[Event::PointerUp]);
1361        assert_eq!(got, (false, true));
1362    }
1363
1364    #[test]
1365    fn tab_moves_focus_and_space_clicks() {
1366        let mut c = Context::new();
1367        let (a, b) = (Id::new("a"), Id::new("b"));
1368        let mut clicked = None;
1369        let mut run = |c: &mut Context, ev: &[Event]| {
1370            frame(c, ev, |c| {
1371                let l = c.layer(Id::new("l"), Order::Content);
1372                for id in [a, b] {
1373                    c.focusable(id);
1374                    if c.interact(id, rect(0.0, 0.0, 9.0, 9.0), Rect::EVERYTHING, l, Sense::Click).clicked {
1375                        clicked = Some(id);
1376                    }
1377                }
1378            });
1379        };
1380        run(&mut c, &[]);
1381        run(&mut c, &[Event::Key(Key::Tab)]);
1382        run(&mut c, &[Event::Key(Key::Tab)]);
1383        run(&mut c, &[Event::Key(Key::Space)]);
1384        assert_eq!(clicked, Some(b));
1385    }
1386
1387    #[test]
1388    fn glass_flips_with_hysteresis() {
1389        let mut c = Context::new();
1390        let id = Id::new("g");
1391        let settle = |c: &mut Context, luma: f32| {
1392            let mut d = 0.0;
1393            for _ in 0..120 {
1394                c.apply_stats(&[(id.0, luma, 0.0)]);
1395                frame(c, &[], |c| d = c.backdrop(id, true).darkness);
1396            }
1397            d
1398        };
1399        assert_eq!(settle(&mut c, 0.9), 0.0);
1400        assert_eq!(settle(&mut c, 0.36), 0.0);
1401        assert_eq!(settle(&mut c, 0.1), 1.0);
1402        assert_eq!(settle(&mut c, 0.36), 1.0);
1403        assert_eq!(settle(&mut c, 0.6), 0.0);
1404    }
1405
1406    #[test]
1407    fn morph_follows_its_view_and_travels_to_a_new_one() {
1408        let mut c = Context::new();
1409        let key = Id::new("cover");
1410        let (grid, detail) = (Id::new("grid"), Id::new("detail"));
1411        let small = rect(10.0, 10.0, 50.0, 50.0);
1412        let large = rect(100.0, 100.0, 200.0, 200.0);
1413        let mut shown = Rect::default();
1414        frame(&mut c, &[], |c| shown = c.morph(key, grid, small));
1415        assert_eq!(shown, small);
1416        // Same view, new place: follows at once, as when a list scrolls.
1417        let moved = small.translate(vec2(0.0, 30.0));
1418        frame(&mut c, &[], |c| shown = c.morph(key, grid, moved));
1419        assert_eq!(shown, moved);
1420        // Another view: travels there.
1421        frame(&mut c, &[], |c| shown = c.morph(key, detail, large));
1422        assert!(shown.width() < large.width() && shown.min.x < large.min.x, "{shown:?}");
1423        assert!(c.is_morphing(key));
1424        for _ in 0..120 {
1425            frame(&mut c, &[], |c| shown = c.morph(key, detail, large));
1426        }
1427        assert_eq!(shown, large);
1428        assert!(!c.is_morphing(key));
1429    }
1430}