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