Skip to main content

egui_pop_core/
areas.rs

1//! The area registry: what each interactive area writes, declared to the
2//! framework, which draws the affordance so a person tells at a glance
3//! what only shows from what edits.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! An interactive area registers each pass it is drawn ([`register`],
9//! after its widget) with its kind ([`AreaKind`]):
10//!
11//! - **display**: shows something, writes nothing (a scope's picture);
12//! - **navigate**: moves what is shown without touching what is edited
13//!   (pan and zoom, the selection, a scope's mode);
14//! - **edit**: writes what the application edits (a parameter, the
15//!   histogram's drag), with the control it writes ("Exposure"), its value
16//!   now ("+0.30 EV") and, if the application has one, its path.
17//!
18//! For an edit area the framework draws, never the widget:
19//!
20//! - its **grips at rest** ([`Grip`]), small handles where a drag takes it
21//!   (as the handles of a Levels tool): a graph with grips edits, a graph
22//!   without is a picture;
23//! - the **edit cursor** of its drag ([`AreaSpec::cursor`]);
24//! - a **hover card** naming the control and its value, which is also the
25//!   area's accessible description.
26//!
27//! An edit area is **inert** while what it shows is not current: the
28//! application side draws a panel whose state is stale, updating or
29//! failed inside [`scope`] with `inert`, and a widget asks [`inert`] before
30//! it senses its drag (dragging the histogram of the previous photo would
31//! edit with a wrong picture). An inert area shows no grip, no card and no
32//! edit cursor, and is listed as inert.
33//!
34//! [`list`] gives the areas of each window's last pass, for agents and
35//! tests (the application API carries them on its bus as `pop.ui.areas`).
36//!
37//! ```
38//! use egui_pop_core::areas::{self, AreaSpec, Grip};
39//!
40//! fn exposure(ui: &mut egui::Ui, ev: &mut f32) {
41//!     let inert = areas::inert(ui);
42//!     let sense = if inert { egui::Sense::hover() } else { egui::Sense::drag() };
43//!     let (rect, r) = ui.allocate_exact_size(egui::vec2(160.0, 40.0), sense);
44//!     *ev += r.drag_delta().x / rect.width() * 4.0;
45//!     areas::register(
46//!         ui,
47//!         &r,
48//!         AreaSpec::edit("demo.exposure", "Exposure")
49//!             .value(format!("{ev:+.2} EV"))
50//!             .grip(Grip::horizontal(rect.right_center())),
51//!     );
52//! }
53//! ```
54
55use std::collections::HashMap;
56use std::sync::{Arc, Mutex};
57
58use egui::{Context, Id, Pos2, Rect, Response, Stroke, StrokeKind, Ui, ViewportId, vec2};
59use serde::{Deserialize, Serialize};
60
61use crate::hover_card::{Card, HoverCard};
62use crate::pointer::DragKind;
63use crate::state::{lock, shared};
64use crate::theme::Tokens;
65
66/// What an interactive area writes.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
68#[serde(rename_all = "kebab-case")]
69#[non_exhaustive]
70pub enum AreaKind {
71    /// Shows, writes nothing.
72    Display,
73    /// Moves what is shown (pan, zoom, selection, a mode), never what is
74    /// edited.
75    Navigate,
76    /// Writes what the application edits.
77    Edit,
78}
79
80impl AreaKind {
81    /// The kind as the registry lists it (`edit`).
82    pub fn as_str(self) -> &'static str {
83        match self {
84            AreaKind::Display => "display",
85            AreaKind::Navigate => "navigate",
86            AreaKind::Edit => "edit",
87        }
88    }
89}
90
91/// Which way a grip's drag goes.
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
93#[serde(rename_all = "kebab-case")]
94#[non_exhaustive]
95pub enum GripAxis {
96    /// Left and right: a tall handle.
97    Horizontal,
98    /// Up and down: a wide handle.
99    Vertical,
100    /// Any way: a round handle.
101    Free,
102}
103
104/// A grip drawn at rest on an edit area: a small handle centred where a
105/// drag takes it.
106#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct Grip {
109    /// Its centre, in points.
110    pub at: Pos2,
111    pub axis: GripAxis,
112}
113
114impl Grip {
115    pub fn new(at: Pos2, axis: GripAxis) -> Grip {
116        Grip { at, axis }
117    }
118
119    /// A grip dragged left and right.
120    pub fn horizontal(at: Pos2) -> Grip {
121        Grip::new(at, GripAxis::Horizontal)
122    }
123
124    /// A grip dragged up and down.
125    pub fn vertical(at: Pos2) -> Grip {
126        Grip::new(at, GripAxis::Vertical)
127    }
128
129    /// A grip dragged any way.
130    pub fn free(at: Pos2) -> Grip {
131        Grip::new(at, GripAxis::Free)
132    }
133
134    /// The handle's rectangle.
135    pub fn rect(&self) -> Rect {
136        let size = match self.axis {
137            GripAxis::Horizontal => vec2(GRIP_THIN, GRIP_LONG),
138            GripAxis::Vertical => vec2(GRIP_LONG, GRIP_THIN),
139            GripAxis::Free => vec2(GRIP_THIN + 2.0, GRIP_THIN + 2.0),
140        };
141        Rect::from_center_size(self.at, size)
142    }
143}
144
145/// A grip's short side, in points.
146const GRIP_THIN: f32 = 7.0;
147/// A grip's long side, in points.
148const GRIP_LONG: f32 = 18.0;
149
150/// An area declared to the registry ([`register`]).
151#[derive(Clone, Debug, PartialEq)]
152#[non_exhaustive]
153pub struct AreaSpec {
154    pub id: String,
155    pub kind: AreaKind,
156    /// For an edit area: the control it writes, in the person's words.
157    pub control: Option<String>,
158    /// For an edit area: the control's value now, formatted.
159    pub value: Option<String>,
160    /// For an edit area: what it writes, as the application names it (a
161    /// parameter's path).
162    pub path: Option<String>,
163    pub grips: Vec<Grip>,
164    /// The cursor of its drag, shown by the framework.
165    pub cursor: Option<DragKind>,
166}
167
168impl AreaSpec {
169    pub fn new(id: impl Into<String>, kind: AreaKind) -> AreaSpec {
170        AreaSpec {
171            id: id.into(),
172            kind,
173            control: None,
174            value: None,
175            path: None,
176            grips: Vec::new(),
177            cursor: None,
178        }
179    }
180
181    /// An area that only shows.
182    pub fn display(id: impl Into<String>) -> AreaSpec {
183        AreaSpec::new(id, AreaKind::Display)
184    }
185
186    /// An area that moves what is shown.
187    pub fn navigate(id: impl Into<String>) -> AreaSpec {
188        AreaSpec::new(id, AreaKind::Navigate)
189    }
190
191    /// An area that edits `control` ("Exposure").
192    pub fn edit(id: impl Into<String>, control: impl Into<String>) -> AreaSpec {
193        let mut a = AreaSpec::new(id, AreaKind::Edit);
194        a.control = Some(control.into());
195        a
196    }
197
198    /// The control's value now ("+0.30 EV").
199    pub fn value(mut self, value: impl Into<String>) -> AreaSpec {
200        self.value = Some(value.into());
201        self
202    }
203
204    /// What it writes, as the application names it (`exposure`).
205    pub fn path(mut self, path: impl Into<String>) -> AreaSpec {
206        self.path = Some(path.into());
207        self
208    }
209
210    /// A grip drawn at rest.
211    pub fn grip(mut self, grip: Grip) -> AreaSpec {
212        self.grips.push(grip);
213        self
214    }
215
216    /// The cursor of its drag (the framework shows it while the area is
217    /// hovered or dragged).
218    pub fn cursor(mut self, kind: DragKind) -> AreaSpec {
219        self.cursor = Some(kind);
220        self
221    }
222
223    /// What its hover card says: the control and its value; empty for an
224    /// area that does not edit.
225    pub fn card(&self) -> Card {
226        match (self.kind, &self.control) {
227            (AreaKind::Edit, Some(control)) => {
228                let text = match &self.value {
229                    Some(v) => format!("**{control}** {v}"),
230                    None => format!("**{control}**"),
231                };
232                Card::new().text(text)
233            }
234            _ => Card::new(),
235        }
236    }
237}
238
239/// An area as the registry lists it, from a window's last pass.
240#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
241#[non_exhaustive]
242pub struct AreaRecord {
243    pub id: String,
244    pub kind: AreaKind,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub control: Option<String>,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub value: Option<String>,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub path: Option<String>,
251    /// Where it is, in points.
252    pub rect: Rect,
253    /// The panel it is drawn in ([`scope`]), if any.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub panel: Option<String>,
256    /// Its window, as egui's debug text names its viewport (`ROOT`).
257    pub window: String,
258    /// It edits but is inert now (its panel is not current).
259    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
260    pub inert: bool,
261    /// The grips it shows now (none while inert).
262    #[serde(default, skip_serializing_if = "Vec::is_empty")]
263    pub grips: Vec<Grip>,
264}
265
266/// A panel being drawn: its id, and whether its edit areas are inert.
267#[derive(Clone, Debug)]
268struct Scope {
269    panel: String,
270    inert: bool,
271}
272
273/// One window's areas.
274#[derive(Debug, Default)]
275struct Window {
276    /// A pass draws now.
277    drawing: bool,
278    /// The areas of the pass drawing, or of the last one once it ended.
279    current: Vec<AreaRecord>,
280    /// The areas of the pass before the one drawing.
281    last: Vec<AreaRecord>,
282    /// The panels being drawn, innermost last.
283    scopes: Vec<Scope>,
284}
285
286#[derive(Debug, Default)]
287struct State {
288    windows: HashMap<ViewportId, Window>,
289}
290
291fn state(ctx: &Context) -> Arc<Mutex<State>> {
292    shared::<State>(ctx, "core.areas")
293}
294
295/// Turns each window's list over at the start of its pass.
296struct Hook;
297
298impl egui::Plugin for Hook {
299    fn debug_name(&self) -> &'static str {
300        "egui_pop_areas"
301    }
302
303    fn on_begin_pass(&mut self, ui: &mut Ui) {
304        let viewport = ui.ctx().viewport_id();
305        let st = state(ui.ctx());
306        let mut s = lock(&st);
307        let w = s.windows.entry(viewport).or_default();
308        w.last = std::mem::take(&mut w.current);
309        w.drawing = true;
310        w.scopes.clear();
311    }
312
313    fn on_end_pass(&mut self, ui: &mut Ui) {
314        let viewport = ui.ctx().viewport_id();
315        let st = state(ui.ctx());
316        if let Some(w) = lock(&st).windows.get_mut(&viewport) {
317            w.drawing = false;
318        }
319    }
320}
321
322/// Draws `add` as the content of `panel`: the areas it registers name the
323/// panel, and its edit areas are inert when `inert` (the panel's state is
324/// not current).
325pub fn scope<R>(ui: &mut Ui, panel: &str, inert: bool, add: impl FnOnce(&mut Ui) -> R) -> R {
326    let ctx = ui.ctx().clone();
327    let viewport = ctx.viewport_id();
328    let st = state(&ctx);
329    lock(&st)
330        .windows
331        .entry(viewport)
332        .or_default()
333        .scopes
334        .push(Scope {
335            panel: panel.to_owned(),
336            inert,
337        });
338    // Popped even when `add` panics (a fault boundary inside catches it).
339    struct Pop(Arc<Mutex<State>>, ViewportId);
340    impl Drop for Pop {
341        fn drop(&mut self) {
342            if let Some(w) = lock(&self.0).windows.get_mut(&self.1) {
343                w.scopes.pop();
344            }
345        }
346    }
347    let _pop = Pop(st, viewport);
348    add(ui)
349}
350
351/// Whether an edit area drawn in `ui` now is inert: it senses no edit,
352/// shows no grip. Ask it before sensing the drag.
353pub fn inert(ui: &Ui) -> bool {
354    let ctx = ui.ctx();
355    let viewport = ctx.viewport_id();
356    lock(&state(ctx))
357        .windows
358        .get(&viewport)
359        .and_then(|w| w.scopes.last())
360        .is_some_and(|s| s.inert)
361}
362
363/// Registers an area drawn this pass, after its widget (`response`), and
364/// draws what the framework draws for it: an edit area's grips, its
365/// cursor and its hover card, unless it is inert. Returns whether it is
366/// inert.
367pub fn register(ui: &Ui, response: &Response, area: AreaSpec) -> bool {
368    let ctx = ui.ctx().clone();
369    ctx.add_plugin(Hook);
370    let viewport = ctx.viewport_id();
371    let st = state(&ctx);
372    let (panel, inert) = {
373        let s = lock(&st);
374        let scope = s.windows.get(&viewport).and_then(|w| w.scopes.last());
375        (
376            scope.map(|s| s.panel.clone()),
377            area.kind == AreaKind::Edit && scope.is_some_and(|s| s.inert),
378        )
379    };
380    let edits = area.kind == AreaKind::Edit && !inert;
381    if edits {
382        let active = response.hovered() || response.dragged() || response.has_focus();
383        for g in &area.grips {
384            paint_grip(ui, g, active);
385        }
386        if let Some(kind) = area.cursor {
387            crate::pointer::drag_cursor(response, kind);
388        }
389        // Not while dragging: the drag's own Escape gives the gesture up.
390        let card = if response.dragged() {
391            Card::new()
392        } else {
393            area.card()
394        };
395        HoverCard::new(("egui_pop.area", response.id)).show(ui, response, &card);
396    }
397    let record = AreaRecord {
398        id: area.id,
399        kind: area.kind,
400        control: area.control,
401        value: area.value,
402        path: area.path,
403        rect: response.rect,
404        panel,
405        window: format!("{viewport:?}"),
406        inert,
407        grips: if edits { area.grips } else { Vec::new() },
408    };
409    lock(&st)
410        .windows
411        .entry(viewport)
412        .or_default()
413        .current
414        .push(record);
415    inert
416}
417
418/// Paints a grip, in the theme's colours: the raised surface, the strong
419/// border (the accent while its area is hovered, dragged or focused) and
420/// ridges in the muted text colour.
421pub fn paint_grip(ui: &Ui, grip: &Grip, active: bool) {
422    let t = Tokens::of(ui.ctx());
423    let fill = t.surface.raised;
424    let border = if active {
425        t.accent.default
426    } else {
427        t.border.strong
428    };
429    let line = t.text.muted;
430    let rect = grip.rect();
431    let painter = ui.painter();
432    let radius = rect.width().min(rect.height()) / 2.0;
433    painter.rect_filled(rect, radius, fill);
434    painter.rect_stroke(rect, radius, Stroke::new(1.0, border), StrokeKind::Inside);
435    // Two short lines across its long side, as a handle's ridges.
436    let ridge = Stroke::new(1.0, line);
437    match grip.axis {
438        GripAxis::Horizontal => {
439            for dy in [-2.0, 2.0] {
440                let y = rect.center().y + dy;
441                painter.line_segment(
442                    [
443                        Pos2::new(rect.left() + 2.0, y),
444                        Pos2::new(rect.right() - 2.0, y),
445                    ],
446                    ridge,
447                );
448            }
449        }
450        GripAxis::Vertical => {
451            for dx in [-2.0, 2.0] {
452                let x = rect.center().x + dx;
453                painter.line_segment(
454                    [
455                        Pos2::new(x, rect.top() + 2.0),
456                        Pos2::new(x, rect.bottom() - 2.0),
457                    ],
458                    ridge,
459                );
460            }
461        }
462        GripAxis::Free => {
463            painter.circle_filled(rect.center(), 1.5, line);
464        }
465    }
466}
467
468/// The areas of each window's last pass (the pass drawing, once it ended;
469/// the one before while it draws), the main window's first.
470pub fn list(ctx: &Context) -> Vec<AreaRecord> {
471    let st = state(ctx);
472    let s = lock(&st);
473    let mut windows: Vec<_> = s.windows.iter().collect();
474    windows.sort_by_key(|(id, _)| (**id != ViewportId::ROOT, format!("{id:?}")));
475    windows
476        .into_iter()
477        .flat_map(|(_, w)| if w.drawing { &w.last } else { &w.current })
478        .cloned()
479        .collect()
480}
481
482/// The area under `id` in the last pass, if registered.
483pub fn find(ctx: &Context, id: &str) -> Option<AreaRecord> {
484    list(ctx).into_iter().find(|a| a.id == id)
485}
486
487/// The hover card's id of the area drawn by `response`'s widget id, for
488/// [`crate::hover_card::open`].
489pub fn card_id(widget: Id) -> Id {
490    HoverCard::new(("egui_pop.area", widget)).id()
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    #[test]
498    fn an_edit_card_names_the_control_and_its_value() {
499        let a = AreaSpec::edit("h", "Exposure").value("+0.30 EV");
500        assert_eq!(a.card().plain_text(), "Exposure +0.30 EV");
501        assert!(AreaSpec::display("w").card().is_empty());
502        assert_eq!(AreaKind::Navigate.as_str(), "navigate");
503    }
504
505    #[test]
506    fn a_grip_is_tall_when_dragged_sideways() {
507        let g = Grip::horizontal(Pos2::new(10.0, 10.0));
508        assert!(g.rect().height() > g.rect().width());
509        assert_eq!(g.rect().center(), Pos2::new(10.0, 10.0));
510    }
511}