Skip to main content

egui_pop_core/
inspect.rs

1//! The element picker behind devtools' inspect mode: while it is on, the
2//! widget under the pointer is outlined with a small label, a click
3//! picks it instead of reaching it, Tab and the arrows move between
4//! widgets and Enter picks, Escape leaves. A pick says what egui knows of
5//! the widget ([`Pick`]); the application side (`egui_pop_api`'s
6//! devtools) adds what it knows and shows it.
7//!
8//! The hit test reads the widget rectangles of the pass just drawn
9//! (egui's `ViewportState::this_pass`), in every window: the top-most
10//! layer holding a rectangle under the point, then the smallest such
11//! rectangle, the one drawn last on a tie. Every `Ui` registers a
12//! rectangle, so what paints without one of its own (a custom-painted
13//! cell, a mark on a canvas) is named by its nearest container, and the
14//! pick says so (`kind: "container"`). Names, roles and values come from
15//! the AccessKit tree of the same pass, switched on while the mode is.
16//!
17//! What draws a widget is recorded only while a context inspects:
18//! [`region`] (a zone's block, a panel: what the application side
19//! records around what it draws) and the kit's parts painted through a
20//! component's handler (with the state their box was taken in).
21//!
22//! ```
23//! use egui_pop_core::inspect;
24//!
25//! let ctx = egui::Context::default();
26//! inspect::start(&ctx);
27//! assert!(inspect::active(&ctx));
28//! inspect::stop(&ctx);
29//! assert!(!inspect::active(&ctx));
30//! ```
31
32use std::collections::HashMap;
33use std::sync::atomic::{AtomicUsize, Ordering};
34
35use egui::emath::TSTransform;
36use egui::{
37    Color32, Context, Event, FontId, Id, Key, LayerId, Order, Painter, Pos2, Rect, Stroke,
38    StrokeKind, Ui, ViewportId, WidgetRect,
39};
40use serde::Serialize;
41
42use crate::kit::{BoxStyle, State as KitState};
43use crate::state::{lock, shared};
44use crate::theme::Tokens;
45
46/// How many contexts are inspecting: what records parts and regions
47/// checks it first, so that nothing is locked while none is.
48static INSPECTING: AtomicUsize = AtomicUsize::new(0);
49
50/// A part of the interface the application drew around what it holds
51/// (a zone's block, a panel), recorded while a context inspects.
52#[derive(Clone, Debug, PartialEq, Serialize)]
53pub struct Region {
54    /// `block` or `panel`.
55    pub kind: String,
56    /// The block's or the panel's id.
57    pub id: String,
58    /// The zone a block is drawn in.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub zone: Option<String>,
61    /// The plugin that registered it.
62    pub owner: String,
63    #[serde(skip)]
64    layer: Option<LayerId>,
65    #[serde(skip)]
66    rect: Rect,
67}
68
69/// A part painted through a kit component's handler.
70#[derive(Clone, Debug, PartialEq, Serialize)]
71pub struct KitPart {
72    /// The component (`button`, `list-row`).
73    pub component: String,
74    /// The handler that drew it (`box`, `underline`).
75    pub shape: String,
76    /// The states its box was taken in (`hover+focus`, `rest`).
77    pub state: String,
78    /// The box: fill, border, radius, text.
79    pub fill: String,
80    pub border: String,
81    pub radius: f32,
82    pub text: String,
83    /// The part lies around the widget (a row around a cell) rather than
84    /// being the widget's own box.
85    pub around: bool,
86    #[serde(skip)]
87    layer: Option<LayerId>,
88    #[serde(skip)]
89    rect: Rect,
90}
91
92/// What the picker knows of a widget.
93#[derive(Clone, Debug, PartialEq, Serialize)]
94pub struct Pick {
95    /// egui's id, in hexadecimal.
96    pub id: String,
97    /// `widget`, or `container` when nothing smaller registered a
98    /// rectangle there: what is painted inside is named by the container
99    /// holding it.
100    pub kind: String,
101    /// The AccessKit role (`Button`, `Label`), when the widget has a
102    /// node.
103    pub role: Option<String>,
104    /// The accessible name.
105    pub label: Option<String>,
106    pub value: Option<String>,
107    pub description: Option<String>,
108    /// The nearest ancestor with a name, as `Role "name"`.
109    pub within: Option<String>,
110    /// What it senses: `click`, `drag`, `focusable`, `hover`.
111    pub sense: String,
112    pub enabled: bool,
113    pub focused: bool,
114    /// Its rectangle in the window, in points: x, y, width, height.
115    pub rect: [f32; 4],
116    /// The egui layer it is drawn on (`Middle 1A2B`).
117    pub layer: String,
118    #[serde(skip)]
119    pub viewport: ViewportId,
120    /// The application's parts around it, outermost first.
121    pub regions: Vec<Region>,
122    /// The kit part that drew its box, if one was painted through a
123    /// handler.
124    pub kit: Option<KitPart>,
125    /// `pointer`, `keyboard` or `accesskit`.
126    pub how: String,
127}
128
129/// What the input hook took for the end of the pass.
130#[derive(Clone, Copy, Debug, PartialEq)]
131enum Act {
132    Click(Pos2),
133    Next,
134    Previous,
135    Pick,
136    Node(u64),
137}
138
139#[derive(Debug, Default)]
140struct Window {
141    acts: Vec<Act>,
142    /// A press taken: its release is taken too.
143    pressed: bool,
144    regions: Vec<Region>,
145    parts: Vec<KitPart>,
146    /// Where a press reaches egui all the same ([`pass_through`]), from
147    /// the pass just drawn.
148    through: Vec<Rect>,
149}
150
151#[derive(Default)]
152struct State {
153    on: bool,
154    /// The platform's copy chord with Shift (egui-winit's `Copy` event)
155    /// is given back as the key it was, so that Ctrl+Shift+C can be
156    /// bound to the mode.
157    armed: bool,
158    /// Whether AccessKit was on when the mode started.
159    accesskit_before: Option<bool>,
160    windows: HashMap<ViewportId, Window>,
161    /// The modifiers held in each window, while armed.
162    held: HashMap<ViewportId, egui::Modifiers>,
163    /// The keyboard's widget, while it is the one shown.
164    cursor: Option<(ViewportId, Id)>,
165    /// The pointer's place when the keyboard last moved.
166    cursor_at: Option<Pos2>,
167    /// Picks not yet taken by the application side.
168    picked: Option<Pick>,
169    last: Option<Pick>,
170    left: bool,
171}
172
173impl std::fmt::Debug for State {
174    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        f.debug_struct("Inspect")
176            .field("on", &self.on)
177            .field("armed", &self.armed)
178            .field("last", &self.last.as_ref().map(|p| p.id.as_str()))
179            .finish_non_exhaustive()
180    }
181}
182
183fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
184    shared::<State>(ctx, "core.inspect")
185}
186
187/// Starts the mode in every window of `ctx`.
188pub fn start(ctx: &Context) {
189    ctx.add_plugin(Hook);
190    let accesskit = ctx.viewport(|vp| vp.this_pass.accesskit_state.is_some());
191    let st = state(ctx);
192    let mut s = lock(&st);
193    if s.on {
194        return;
195    }
196    s.on = true;
197    s.left = false;
198    s.cursor = None;
199    s.accesskit_before = Some(accesskit);
200    s.windows.clear();
201    drop(s);
202    INSPECTING.fetch_add(1, Ordering::SeqCst);
203    // Names and roles come from the AccessKit tree.
204    ctx.enable_accesskit();
205    ctx.request_repaint();
206}
207
208/// Leaves the mode.
209pub fn stop(ctx: &Context) {
210    let st = state(ctx);
211    let mut s = lock(&st);
212    leave(ctx, &mut s);
213}
214
215fn leave(ctx: &Context, s: &mut State) {
216    if !s.on {
217        return;
218    }
219    s.on = false;
220    s.left = true;
221    s.cursor = None;
222    s.windows.clear();
223    INSPECTING.fetch_sub(1, Ordering::SeqCst);
224    if s.accesskit_before.take() == Some(false) {
225        ctx.disable_accesskit();
226    }
227    ctx.request_repaint();
228}
229
230/// Whether the mode is on.
231pub fn active(ctx: &Context) -> bool {
232    INSPECTING.load(Ordering::SeqCst) > 0 && lock(&state(ctx)).on
233}
234
235/// Gives the platform's copy chord with Shift back as a key (Ctrl+Shift+C
236/// under egui-winit, which turns it into a copy event and swallows the
237/// key) while `on`: the devtools setting is, and the mode is bound to
238/// that chord.
239pub fn arm(ctx: &Context, on: bool) {
240    let st = state(ctx);
241    if lock(&st).armed == on {
242        return;
243    }
244    ctx.add_plugin(Hook);
245    lock(&st).armed = on;
246}
247
248/// Lets a press on `rect` of the window being drawn reach egui while
249/// the mode is on, instead of picking: the control toggling the mode (a
250/// menu bar button) then leaves it. Call it each pass the control is
251/// drawn.
252pub fn pass_through(ctx: &Context, rect: Rect) {
253    if INSPECTING.load(Ordering::SeqCst) == 0 {
254        return;
255    }
256    let viewport = ctx.viewport_id();
257    let st = state(ctx);
258    let mut s = lock(&st);
259    if s.on {
260        s.windows.entry(viewport).or_default().through.push(rect);
261    }
262}
263
264/// The pick made since the last call, if any.
265pub fn take_picked(ctx: &Context) -> Option<Pick> {
266    lock(&state(ctx)).picked.take()
267}
268
269/// Whether the mode was left (Escape, a pick) since the last call.
270pub fn take_left(ctx: &Context) -> bool {
271    std::mem::take(&mut lock(&state(ctx)).left)
272}
273
274/// The last pick.
275pub fn last(ctx: &Context) -> Option<Pick> {
276    lock(&state(ctx)).last.clone()
277}
278
279/// Records a part of the interface around what `ui` drew (call it once
280/// drawn): a zone's block or a panel, with the plugin owning it. Does
281/// nothing unless the mode is on.
282pub fn region(ui: &Ui, kind: &str, id: &str, zone: Option<&str>, owner: &str) {
283    if INSPECTING.load(Ordering::Relaxed) == 0 {
284        return;
285    }
286    let ctx = ui.ctx();
287    let viewport = ctx.viewport_id();
288    let st = state(ctx);
289    let mut s = lock(&st);
290    if !s.on {
291        return;
292    }
293    s.windows.entry(viewport).or_default().regions.push(Region {
294        kind: kind.into(),
295        id: id.into(),
296        zone: zone.map(String::from),
297        owner: owner.into(),
298        layer: Some(ui.layer_id()),
299        rect: ui.min_rect(),
300    });
301}
302
303/// Records a kit part painted (by `Component::paint`).
304pub(crate) fn painted(
305    painter: &Painter,
306    component: &str,
307    shape: &str,
308    state: KitState,
309    rect: Rect,
310    b: &BoxStyle,
311) {
312    if INSPECTING.load(Ordering::Relaxed) == 0 {
313        return;
314    }
315    let ctx = painter.ctx();
316    let viewport = ctx.viewport_id();
317    let st = self::state(ctx);
318    let mut s = lock(&st);
319    if !s.on {
320        return;
321    }
322    s.windows.entry(viewport).or_default().parts.push(KitPart {
323        component: component.into(),
324        shape: shape.into(),
325        state: state_name(state),
326        fill: hex(b.fill),
327        border: format!("{} {}", b.border_width, hex(b.border_color)),
328        radius: b.radius,
329        text: hex(b.text),
330        around: false,
331        layer: Some(painter.layer_id()),
332        rect,
333    });
334}
335
336/// A kit state's name: its flags joined with `+`, or `rest`.
337///
338/// <div class="warning">Experimental: may change in any release
339/// (docs/stability.md).</div>
340pub fn state_name(state: KitState) -> String {
341    let names: Vec<&str> = KitState::ORDER
342        .iter()
343        .filter(|(s, _)| state.contains(*s))
344        .map(|(_, n)| *n)
345        .collect();
346    if names.is_empty() {
347        "rest".into()
348    } else {
349        names.join("+")
350    }
351}
352
353/// A colour as `#rrggbbaa`.
354pub fn hex(c: Color32) -> String {
355    let [r, g, b, a] = c.to_srgba_unmultiplied();
356    format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
357}
358
359/// The egui plugin: takes the input while the mode is on, and picks at
360/// the end of each window's pass.
361struct Hook;
362
363impl egui::plugin::Plugin for Hook {
364    fn debug_name(&self) -> &'static str {
365        "egui_pop_core::inspect"
366    }
367
368    fn input_hook(&mut self, ctx: &Context, input: &mut egui::RawInput) {
369        let st = state(ctx);
370        let mut s = lock(&st);
371        if s.armed {
372            let mut held = s.held.get(&input.viewport_id).copied().unwrap_or_default();
373            give_back_the_chord(input, &mut held);
374            s.held.insert(input.viewport_id, held);
375        }
376        if !s.on {
377            return;
378        }
379        let viewport = input.viewport_id;
380        let mut leaving = false;
381        let w = s.windows.entry(viewport).or_default();
382        input.events.retain(|e| match e {
383            Event::PointerButton {
384                pos,
385                button,
386                pressed,
387                ..
388            } => {
389                if *pressed && w.through.iter().any(|r| r.contains(*pos)) {
390                    // The control leaving the mode (a toggle) is pressed.
391                    return true;
392                }
393                if *pressed {
394                    if *button == egui::PointerButton::Primary {
395                        w.acts.push(Act::Click(*pos));
396                    }
397                    w.pressed = true;
398                    false
399                } else {
400                    // A release whose press reached egui goes on.
401                    !std::mem::take(&mut w.pressed)
402                }
403            }
404            Event::Key {
405                key,
406                pressed,
407                modifiers,
408                ..
409            } => {
410                let act = match key {
411                    Key::Escape => {
412                        leaving |= *pressed;
413                        return false;
414                    }
415                    Key::Tab if modifiers.shift => Act::Previous,
416                    Key::Tab | Key::ArrowDown | Key::ArrowRight => Act::Next,
417                    Key::ArrowUp | Key::ArrowLeft => Act::Previous,
418                    Key::Enter => Act::Pick,
419                    _ => return true,
420                };
421                if *pressed {
422                    w.acts.push(act);
423                }
424                false
425            }
426            Event::AccessKitActionRequest(r) if r.action == egui::accesskit::Action::Click => {
427                w.acts.push(Act::Node(r.target_node.0));
428                false
429            }
430            _ => true,
431        });
432        if leaving {
433            leave(ctx, &mut s);
434        }
435    }
436
437    fn on_begin_pass(&mut self, ui: &mut Ui) {
438        let viewport = ui.ctx().viewport_id();
439        let st = state(ui.ctx());
440        let mut s = lock(&st);
441        if let Some(w) = s.windows.get_mut(&viewport) {
442            w.regions.clear();
443            w.parts.clear();
444            w.through.clear();
445        }
446    }
447
448    fn on_end_pass(&mut self, ui: &mut Ui) {
449        end_pass(ui.ctx());
450    }
451}
452
453/// egui-winit sends the copy chord as a copy event, its key swallowed;
454/// with Shift held it is given back as the key. `held`: the modifiers
455/// held, followed from event to event (they arrive as events).
456fn give_back_the_chord(input: &mut egui::RawInput, held: &mut egui::Modifiers) {
457    let mut out = Vec::with_capacity(input.events.len());
458    for e in input.events.drain(..) {
459        match &e {
460            Event::ModifiersChanged(m) => *held = *m,
461            Event::Key { modifiers, .. } | Event::PointerButton { modifiers, .. } => {
462                *held = *modifiers;
463            }
464            Event::WindowFocused(false) => *held = egui::Modifiers::NONE,
465            _ => {}
466        }
467        if e == Event::Copy && held.command && held.shift {
468            for pressed in [true, false] {
469                out.push(Event::Key {
470                    key: Key::C,
471                    physical_key: Some(Key::C),
472                    pressed,
473                    repeat: false,
474                    modifiers: *held,
475                });
476            }
477        } else {
478            out.push(e);
479        }
480    }
481    input.events = out;
482}
483
484/// An AccessKit node's role, name, value and description.
485type Node = (String, Option<String>, Option<String>, Option<String>);
486
487/// What a window's pass drew, read once at its end.
488struct Drawn {
489    widgets: Vec<(usize, WidgetRect)>,
490    nodes: HashMap<Id, Node>,
491    parents: HashMap<Id, Id>,
492    order: Vec<LayerId>,
493    transforms: HashMap<LayerId, TSTransform>,
494}
495
496impl Drawn {
497    fn read(ctx: &Context) -> Drawn {
498        let (widgets, nodes, parents) = ctx.viewport(|vp| {
499            let mut widgets = Vec::new();
500            for (_, list) in vp.this_pass.widgets.layers() {
501                for (i, w) in list.iter().enumerate() {
502                    widgets.push((i, *w));
503                }
504            }
505            let mut nodes = HashMap::new();
506            let mut parents = HashMap::new();
507            if let Some(a) = vp.this_pass.accesskit_state.as_ref() {
508                for (id, n) in &a.nodes {
509                    nodes.insert(
510                        *id,
511                        (
512                            format!("{:?}", n.role()),
513                            n.label().map(String::from),
514                            n.value().map(String::from),
515                            n.description().map(String::from),
516                        ),
517                    );
518                }
519                for (id, p) in &a.parent_map {
520                    parents.insert(*id, *p);
521                }
522            }
523            (widgets, nodes, parents)
524        });
525        let order: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
526        let mut transforms = HashMap::new();
527        for (_, w) in &widgets {
528            if let std::collections::hash_map::Entry::Vacant(e) = transforms.entry(w.layer_id)
529                && let Some(t) = ctx.layer_transform_to_global(w.layer_id)
530            {
531                e.insert(t);
532            }
533        }
534        Drawn {
535            widgets,
536            nodes,
537            parents,
538            order,
539            transforms,
540        }
541    }
542
543    fn global(&self, w: &WidgetRect) -> Rect {
544        match self.transforms.get(&w.layer_id) {
545            Some(t) => *t * w.interact_rect,
546            None => w.interact_rect,
547        }
548    }
549
550    /// Back to front: the layer's order, then its place among the areas.
551    fn rank(&self, layer: LayerId) -> (Order, i64) {
552        let at = self.order.iter().position(|l| *l == layer);
553        (layer.order, at.map_or(-1, |i| i as i64))
554    }
555
556    fn pickable(layer: LayerId) -> bool {
557        !matches!(layer.order, Order::Tooltip | Order::Debug)
558    }
559
560    /// The widget at `pos`: the top-most layer with a rectangle there,
561    /// then the smallest, the last drawn on a tie.
562    fn at(&self, pos: Pos2) -> Option<WidgetRect> {
563        let mut best: Option<((Order, i64), f32, usize, WidgetRect)> = None;
564        for (i, w) in &self.widgets {
565            if !Self::pickable(w.layer_id) {
566                continue;
567            }
568            let r = self.global(w);
569            if !r.is_positive() || !r.contains(pos) {
570                continue;
571            }
572            let rank = self.rank(w.layer_id);
573            let area = r.area();
574            let better = match &best {
575                None => true,
576                Some((br, ba, bi, _)) => {
577                    rank > *br || (rank == *br && (area < *ba || (area == *ba && i > bi)))
578                }
579            };
580            if better {
581                best = Some((rank, area, *i, *w));
582            }
583        }
584        best.map(|b| b.3)
585    }
586
587    /// The widgets the keyboard steps through: interactive ones, back to
588    /// front, in the order drawn.
589    fn stops(&self) -> Vec<WidgetRect> {
590        let mut v: Vec<&(usize, WidgetRect)> = self
591            .widgets
592            .iter()
593            .filter(|(_, w)| {
594                Self::pickable(w.layer_id)
595                    && w.enabled
596                    && w.sense.interactive()
597                    && self.global(w).is_positive()
598            })
599            .collect();
600        v.sort_by_key(|(i, w)| (self.rank(w.layer_id), *i));
601        v.into_iter().map(|(_, w)| *w).collect()
602    }
603
604    fn by_id(&self, id: Id) -> Option<WidgetRect> {
605        self.widgets.iter().map(|(_, w)| *w).find(|w| w.id == id)
606    }
607
608    fn named(&self, id: Id) -> Option<String> {
609        let (role, label, _, _) = self.nodes.get(&id)?;
610        label
611            .as_ref()
612            .filter(|l| !l.is_empty())
613            .map(|l| format!("{role} {l:?}"))
614    }
615
616    /// The nearest ancestor with a name.
617    fn within(&self, id: Id) -> Option<String> {
618        let mut at = id;
619        for _ in 0..64 {
620            at = *self.parents.get(&at)?;
621            if let Some(n) = self.named(at) {
622                return Some(n);
623            }
624        }
625        None
626    }
627
628    fn short(&self, w: &WidgetRect) -> String {
629        let r = self.global(w);
630        let what = self.named(w.id).or_else(|| {
631            self.nodes
632                .get(&w.id)
633                .map(|(role, ..)| role.clone())
634                .filter(|r| r != "GenericContainer")
635        });
636        let size = format!("{:.0}×{:.0}", r.width(), r.height());
637        match what {
638            Some(w) => format!("{w}  {size}"),
639            None => format!("{}  {size}", sense(w)),
640        }
641    }
642}
643
644fn sense(w: &WidgetRect) -> String {
645    let s = w.sense;
646    let mut v = Vec::new();
647    if s.senses_click() {
648        v.push("click");
649    }
650    if s.senses_drag() {
651        v.push("drag");
652    }
653    if s.is_focusable() {
654        v.push("focusable");
655    }
656    if v.is_empty() {
657        "hover".into()
658    } else {
659        v.join("+")
660    }
661}
662
663fn end_pass(ctx: &Context) {
664    if INSPECTING.load(Ordering::Relaxed) == 0 {
665        return;
666    }
667    let viewport = ctx.viewport_id();
668    let st = state(ctx);
669    let (acts, regions, parts, cursor, cursor_at) = {
670        let mut s = lock(&st);
671        if !s.on {
672            return;
673        }
674        let w = s.windows.entry(viewport).or_default();
675        (
676            std::mem::take(&mut w.acts),
677            w.regions.clone(),
678            w.parts.clone(),
679            s.cursor,
680            s.cursor_at,
681        )
682    };
683    let drawn = Drawn::read(ctx);
684    let pointer = ctx.input(|i| i.pointer.hover_pos());
685    let mut cursor = cursor
686        .filter(|(v, _)| *v == viewport)
687        .and_then(|(_, id)| drawn.by_id(id))
688        // The pointer moving gives the outline back to it.
689        .filter(|_| pointer.is_none() || pointer == cursor_at);
690    let mut picked: Option<(WidgetRect, &str)> = None;
691    for act in acts {
692        match act {
693            Act::Click(pos) => {
694                if let Some(w) = drawn.at(pos) {
695                    picked = Some((w, "pointer"));
696                }
697            }
698            Act::Node(node) => {
699                if let Some(w) = drawn
700                    .widgets
701                    .iter()
702                    .map(|(_, w)| *w)
703                    .find(|w| w.id.value() == node)
704                {
705                    picked = Some((w, "accesskit"));
706                }
707            }
708            Act::Next | Act::Previous => {
709                let stops = drawn.stops();
710                if stops.is_empty() {
711                    continue;
712                }
713                let from = cursor
714                    .or_else(|| pointer.and_then(|p| drawn.at(p)))
715                    .or_else(|| ctx.memory(|m| m.focused()).and_then(|id| drawn.by_id(id)));
716                let at = from.and_then(|f| stops.iter().position(|w| w.id == f.id));
717                let n = stops.len();
718                let next = match (at, act == Act::Next) {
719                    (Some(i), true) => (i + 1) % n,
720                    (Some(i), false) => (i + n - 1) % n,
721                    (None, true) => 0,
722                    (None, false) => n - 1,
723                };
724                cursor = Some(stops[next]);
725            }
726            Act::Pick => {
727                let target = cursor.or_else(|| pointer.and_then(|p| drawn.at(p)));
728                if let Some(w) = target {
729                    picked = Some((w, "keyboard"));
730                }
731            }
732        }
733    }
734    if let Some((w, how)) = picked {
735        let pick = describe(ctx, &drawn, &w, viewport, &regions, &parts, how);
736        let mut s = lock(&st);
737        s.last = Some(pick.clone());
738        s.picked = Some(pick);
739        leave(ctx, &mut s);
740        return;
741    }
742    {
743        let mut s = lock(&st);
744        s.cursor = cursor.map(|w| (viewport, w.id));
745        if cursor.is_some() {
746            s.cursor_at = pointer;
747        }
748    }
749    let shown = cursor.or_else(|| pointer.and_then(|p| drawn.at(p)));
750    if let Some(w) = shown {
751        outline(ctx, drawn.global(&w), &drawn.short(&w));
752    }
753}
754
755/// Draws the outline and its label over everything.
756fn outline(ctx: &Context, rect: Rect, label: &str) {
757    let t = Tokens::of(ctx);
758    let painter = ctx.layer_painter(LayerId::new(Order::Debug, Id::unique("egui_pop.inspect")));
759    painter.rect(
760        rect,
761        0.0,
762        t.accent.default.gamma_multiply(0.15),
763        Stroke::new(1.5, t.focus_ring),
764        StrokeKind::Outside,
765    );
766    let galley = painter.layout_no_wrap(
767        label.to_string(),
768        FontId::proportional(t.font.small),
769        t.text.on_accent,
770    );
771    let pad = egui::vec2(t.space.xs, t.space.xs / 2.0);
772    let size = galley.size() + 2.0 * pad;
773    let screen = ctx.content_rect();
774    let mut at = rect.left_top() - egui::vec2(0.0, size.y + 2.0);
775    if at.y < screen.top() {
776        at.y = rect.bottom() + 2.0;
777    }
778    at.x =
779        at.x.clamp(screen.left(), (screen.right() - size.x).max(screen.left()));
780    let bg = Rect::from_min_size(at, size);
781    painter.rect_filled(bg, t.radius.widget, t.accent.default);
782    painter.galley(bg.min + pad, galley, t.text.on_accent);
783}
784
785fn describe(
786    ctx: &Context,
787    drawn: &Drawn,
788    w: &WidgetRect,
789    viewport: ViewportId,
790    regions: &[Region],
791    parts: &[KitPart],
792    how: &str,
793) -> Pick {
794    let r = drawn.global(w);
795    let node = drawn.nodes.get(&w.id);
796    let role = node.map(|n| n.0.clone());
797    let container = !w.sense.interactive()
798        && role
799            .as_deref()
800            .is_none_or(|r| r == "GenericContainer" || r == "Unknown");
801    let local = w.interact_rect;
802    let centre = local.center();
803    // The application's parts around it, on its layer, outermost first.
804    let mut around: Vec<Region> = regions
805        .iter()
806        .filter(|g| g.layer == Some(w.layer_id) && g.rect.contains(centre))
807        .cloned()
808        .collect();
809    // A block fills the panel it is drawn in: the panel goes outside.
810    around.sort_by(|a, b| {
811        b.rect
812            .area()
813            .total_cmp(&a.rect.area())
814            .then_with(|| (a.kind == "block").cmp(&(b.kind == "block")))
815    });
816    // Its own box: the largest part painted within it; else the
817    // smallest painted around it.
818    let on_layer = parts.iter().filter(|p| p.layer == Some(w.layer_id));
819    let own = on_layer
820        .clone()
821        .filter(|p| w.rect.expand(4.0).contains_rect(p.rect))
822        .max_by(|a, b| a.rect.area().total_cmp(&b.rect.area()))
823        .cloned();
824    let kit = own.or_else(|| {
825        on_layer
826            .filter(|p| p.rect.contains(centre))
827            .min_by(|a, b| a.rect.area().total_cmp(&b.rect.area()))
828            .cloned()
829            .map(|mut p| {
830                p.around = true;
831                p
832            })
833    });
834    let none = |s: &Option<String>| s.clone().filter(|s| !s.is_empty());
835    Pick {
836        id: format!("{:016x}", w.id.value()),
837        kind: if container { "container" } else { "widget" }.into(),
838        role,
839        label: node.and_then(|n| none(&n.1)),
840        value: node.and_then(|n| none(&n.2)),
841        description: node.and_then(|n| none(&n.3)),
842        within: drawn.within(w.id),
843        sense: sense(w),
844        enabled: w.enabled,
845        focused: ctx.memory(|m| m.focused()) == Some(w.id),
846        rect: [r.min.x, r.min.y, r.width(), r.height()],
847        layer: format!("{:?} {:?}", w.layer_id.order, w.layer_id.id),
848        viewport,
849        regions: around,
850        kit,
851        how: how.into(),
852    }
853}
854
855/// Which windows have taken a press whose release is still owed (for
856/// tests of the hook).
857#[cfg(test)]
858fn pressed(ctx: &Context) -> std::collections::HashSet<ViewportId> {
859    lock(&state(ctx))
860        .windows
861        .iter()
862        .filter(|(_, w)| w.pressed)
863        .map(|(v, _)| *v)
864        .collect()
865}
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870
871    fn frame(ctx: &Context, events: Vec<Event>, ui: impl FnMut(&mut Ui)) {
872        let input = egui::RawInput {
873            screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0))),
874            events,
875            ..Default::default()
876        };
877        let mut out = ctx.run_ui(input, ui);
878        out.textures_delta.clear();
879    }
880
881    fn click(pos: Pos2) -> Vec<Event> {
882        vec![
883            Event::PointerMoved(pos),
884            Event::PointerButton {
885                pos,
886                button: egui::PointerButton::Primary,
887                pressed: true,
888                modifiers: Default::default(),
889            },
890            Event::PointerButton {
891                pos,
892                button: egui::PointerButton::Primary,
893                pressed: false,
894                modifiers: Default::default(),
895            },
896        ]
897    }
898
899    #[test]
900    fn a_click_picks_the_button_and_does_not_press_it() {
901        let ctx = Context::default();
902        let clicked = std::cell::Cell::new(0);
903        let at = std::cell::Cell::new(Rect::NOTHING);
904        let mut ui = |ui: &mut Ui| {
905            let r = ui.button("Save");
906            at.set(r.rect);
907            if r.clicked() {
908                clicked.set(clicked.get() + 1);
909            }
910        };
911        frame(&ctx, vec![], &mut ui);
912        start(&ctx);
913        frame(&ctx, vec![], &mut ui);
914        frame(&ctx, click(at.get().center()), &mut ui);
915        assert_eq!(clicked.get(), 0);
916        assert!(!active(&ctx));
917        assert!(pressed(&ctx).is_empty());
918        let pick = take_picked(&ctx).expect("picked");
919        assert_eq!(pick.role.as_deref(), Some("Button"));
920        assert_eq!(pick.label.as_deref(), Some("Save"));
921        assert_eq!(pick.kind, "widget");
922        assert_eq!(pick.how, "pointer");
923        // Off again, a click reaches it.
924        frame(&ctx, click(at.get().center()), &mut ui);
925        assert_eq!(clicked.get(), 1);
926    }
927
928    #[test]
929    fn keys_step_through_widgets_and_enter_picks() {
930        let ctx = Context::default();
931        let mut ui = |ui: &mut Ui| {
932            let _ = ui.button("One");
933            let _ = ui.button("Two");
934        };
935        frame(&ctx, vec![], &mut ui);
936        start(&ctx);
937        frame(&ctx, vec![], &mut ui);
938        let key = |key| Event::Key {
939            key,
940            physical_key: None,
941            pressed: true,
942            repeat: false,
943            modifiers: Default::default(),
944        };
945        frame(&ctx, vec![key(Key::Tab), key(Key::Tab)], &mut ui);
946        frame(&ctx, vec![key(Key::Enter)], &mut ui);
947        let pick = take_picked(&ctx).expect("picked");
948        assert_eq!(pick.label.as_deref(), Some("Two"));
949        assert_eq!(pick.how, "keyboard");
950    }
951
952    #[test]
953    fn escape_leaves() {
954        let ctx = Context::default();
955        frame(&ctx, vec![], |_| {});
956        start(&ctx);
957        frame(
958            &ctx,
959            vec![Event::Key {
960                key: Key::Escape,
961                physical_key: None,
962                pressed: true,
963                repeat: false,
964                modifiers: Default::default(),
965            }],
966            |_| {},
967        );
968        assert!(!active(&ctx));
969        assert!(take_left(&ctx));
970        assert!(take_picked(&ctx).is_none());
971    }
972
973    #[test]
974    fn the_shifted_copy_chord_comes_back_as_its_key() {
975        let chord = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT;
976        let mut input = egui::RawInput {
977            events: vec![Event::ModifiersChanged(chord), Event::Copy],
978            ..Default::default()
979        };
980        let mut held = egui::Modifiers::NONE;
981        give_back_the_chord(&mut input, &mut held);
982        assert!(matches!(
983            input.events[1],
984            Event::Key {
985                key: Key::C,
986                pressed: true,
987                ..
988            }
989        ));
990        let mut plain = egui::RawInput {
991            events: vec![
992                Event::ModifiersChanged(egui::Modifiers::COMMAND),
993                Event::Copy,
994            ],
995            ..Default::default()
996        };
997        give_back_the_chord(&mut plain, &mut held);
998        assert_eq!(plain.events[1], Event::Copy);
999    }
1000
1001    #[test]
1002    fn a_painted_mark_is_named_by_its_container() {
1003        let ctx = Context::default();
1004        let at = std::cell::Cell::new(Rect::NOTHING);
1005        let mut ui = |ui: &mut Ui| {
1006            ui.scope(|ui| {
1007                ui.set_min_size(egui::vec2(120.0, 60.0));
1008                at.set(ui.min_rect());
1009                ui.painter()
1010                    .circle_filled(at.get().center(), 4.0, Color32::RED);
1011            });
1012        };
1013        frame(&ctx, vec![], &mut ui);
1014        start(&ctx);
1015        frame(&ctx, vec![], &mut ui);
1016        frame(&ctx, click(at.get().center()), &mut ui);
1017        let pick = take_picked(&ctx).expect("picked");
1018        assert_eq!(pick.kind, "container");
1019    }
1020}