Skip to main content

egui_pop_core/pointer/
claim.rs

1//! A widget's own use of the secondary button.
2//!
3//! The secondary button opens a context menu everywhere by default, and
4//! a canvas may bind a secondary drag in its pointer profile (Blender /
5//! node editors pan the graph with it). A widget that needs the right
6//! click for something else (a curve editor deleting a point, a swatch
7//! resetting its colour, a canvas of its own binding a right drag)
8//! **claims** it on its rect, every pass it is drawn:
9//!
10//! ```
11//! use egui_pop_core::pointer::claim::{self, SecondaryClaim};
12//!
13//! fn swatch(ui: &mut egui::Ui) {
14//!     let r = ui.allocate_response(egui::vec2(24.0, 24.0), egui::Sense::click());
15//!     claim::claim_secondary(&r, SecondaryClaim::new("Swatch").click("Resets the colour"));
16//!     if r.secondary_clicked() {
17//!         // reset
18//!     }
19//! }
20//! ```
21//!
22//! While the pointer was pressed over a claim, neither a context menu
23//! opened through [`context_menu`] (and `egui_pop_api::menus`' context
24//! menus) nor a canvas's profile binding for that gesture fires: the
25//! widget alone acts. A claim names the click, the drag or both; a
26//! claimed click leaves a secondary drag to the canvas, and the other
27//! way round.
28//!
29//! A claim lasts the pass it was made in and the next one, so a parent
30//! that reads its response before its children are drawn sees them.
31//! Claims under a layer drawn above them (a window, a popup) do not
32//! count there.
33//!
34//! What a claim does, when it says so (a label), is kept as the
35//! widget's **use** ([`uses`]): the shortcuts editor lists the uses seen
36//! so far, and the `pointer` collector of the debug bridge shows them
37//! with the claims in force ([`claims`]). [`declare_use`] lists a use
38//! before its widget is first drawn.
39
40use std::collections::BTreeMap;
41
42use egui::{Context, Id, InnerResponse, LayerId, Pos2, Rect, Response, SetOpenCommand, Ui};
43use egui_pop_model::keymap::{Button, Pointer};
44use serde::Serialize;
45use serde_json::{Value as Json, json};
46
47use crate::state::Slot;
48
49/// What a widget takes of the secondary button: the click, the drag, or
50/// both, each with what it does there.
51#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
52pub struct SecondaryClaim {
53    /// The widget, as people know it (`Curve editor`): how the shortcuts
54    /// editor and agents name it.
55    pub widget: String,
56    /// The secondary click is the widget's, doing this (empty: not said).
57    pub click: Option<String>,
58    /// The secondary drag is the widget's, doing this (empty: not said).
59    pub drag: Option<String>,
60}
61
62impl SecondaryClaim {
63    /// A claim of nothing yet, by a widget of this name.
64    pub fn new(widget: impl Into<String>) -> Self {
65        Self {
66            widget: widget.into(),
67            click: None,
68            drag: None,
69        }
70    }
71
72    /// Claims the secondary click, saying what it does (`""`: the
73    /// shortcuts editor does not list it).
74    pub fn click(mut self, does: impl Into<String>) -> Self {
75        self.click = Some(does.into());
76        self
77    }
78
79    /// Claims the secondary drag, saying what it does.
80    pub fn drag(mut self, does: impl Into<String>) -> Self {
81        self.drag = Some(does.into());
82        self
83    }
84
85    /// Whether it claims this gesture.
86    pub fn takes(&self, gesture: Secondary) -> bool {
87        match gesture {
88            Secondary::Click => self.click.is_some(),
89            Secondary::Drag => self.drag.is_some(),
90        }
91    }
92
93    /// Each gesture claimed with what it does (empty when not said).
94    pub fn gestures(&self) -> Vec<(Secondary, &str)> {
95        [
96            (Secondary::Click, &self.click),
97            (Secondary::Drag, &self.drag),
98        ]
99        .into_iter()
100        .filter_map(|(g, does)| does.as_deref().map(|d| (g, d)))
101        .collect()
102    }
103}
104
105/// A gesture of the secondary button a widget can claim.
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
107pub enum Secondary {
108    /// A press and release without moving (it opens context menus).
109    Click,
110    /// A press held while the pointer moves.
111    Drag,
112}
113
114impl Secondary {
115    /// Its pointer gesture: `SecondaryClick`, `SecondaryDrag`.
116    pub fn pointer(self) -> Pointer {
117        match self {
118            Secondary::Click => Pointer::Click(Button::Secondary),
119            Secondary::Drag => Pointer::Drag(Button::Secondary),
120        }
121    }
122}
123
124/// One claim in force.
125#[derive(Clone, Debug, PartialEq)]
126pub struct Claimed {
127    /// The claiming widget's egui id.
128    pub id: Id,
129    pub layer: LayerId,
130    /// Its rect, in the window's points (a scene's transform applied).
131    pub rect: Rect,
132    pub claim: SecondaryClaim,
133}
134
135/// One labelled use seen (or declared): what a widget does with a
136/// gesture of the secondary button.
137#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
138pub struct WidgetUse {
139    pub widget: String,
140    /// `SecondaryClick` or `SecondaryDrag`.
141    pub gesture: String,
142    pub does: String,
143}
144
145#[derive(Clone, Debug, Default)]
146struct Claims {
147    /// The pass `now` was made in.
148    pass: u64,
149    now: Vec<Claimed>,
150    last: Vec<Claimed>,
151    /// `(widget, gesture)` → what it does.
152    uses: BTreeMap<(String, Secondary), String>,
153}
154
155impl Claims {
156    /// Moves to `pass`: what was made before it becomes the last pass's
157    /// (or goes, when older).
158    fn at(&mut self, pass: u64) {
159        if self.pass == pass {
160            return;
161        }
162        self.last = if self.pass + 1 == pass {
163            std::mem::take(&mut self.now)
164        } else {
165            Vec::new()
166        };
167        self.now.clear();
168        self.pass = pass;
169    }
170
171    /// The claims of this pass, then those of the last one not made
172    /// again.
173    fn in_force(&self, pass: u64) -> Vec<Claimed> {
174        if self.pass == pass {
175            let mut out = self.now.clone();
176            out.extend(
177                self.last
178                    .iter()
179                    .filter(|c| !self.now.iter().any(|n| n.id == c.id))
180                    .cloned(),
181            );
182            out
183        } else if self.pass + 1 == pass {
184            self.now.clone()
185        } else {
186            Vec::new()
187        }
188    }
189}
190
191const CLAIMS: Slot<Claims> = Slot::new("core.pointer.claims");
192
193/// The widget of `response` claims the secondary button on its rect for
194/// this pass (and the next): see the [module](self).
195pub fn claim_secondary(response: &Response, claim: SecondaryClaim) {
196    claim_secondary_rect(
197        &response.ctx,
198        response.id,
199        response.layer_id,
200        response.interact_rect,
201        claim,
202    );
203}
204
205/// As [`claim_secondary`], for a rect of a widget's (a handle, a point)
206/// rather than its whole response.
207pub fn claim_secondary_rect(
208    ctx: &Context,
209    id: Id,
210    layer: LayerId,
211    rect: Rect,
212    claim: SecondaryClaim,
213) {
214    if claim.click.is_none() && claim.drag.is_none() {
215        return;
216    }
217    let rect = ctx
218        .layer_transform_to_global(layer)
219        .map_or(rect, |t| t * rect);
220    let pass = ctx.cumulative_pass_nr();
221    CLAIMS.update(ctx, |c| {
222        c.at(pass);
223        for (g, does) in claim.gestures() {
224            if !does.is_empty() {
225                c.uses.insert((claim.widget.clone(), g), does.to_string());
226            }
227        }
228        c.now.retain(|x| x.id != id);
229        c.now.push(Claimed {
230            id,
231            layer,
232            rect,
233            claim,
234        });
235    });
236}
237
238/// Lists a widget's use of a gesture of the secondary button before the
239/// widget is drawn (an application declaring its own canvas's), for the
240/// shortcuts editor.
241pub fn declare_use(ctx: &Context, widget: &str, gesture: Secondary, does: &str) {
242    CLAIMS.update(ctx, |c| {
243        c.uses
244            .insert((widget.to_string(), gesture), does.to_string());
245    });
246}
247
248/// The claims in force: made in this pass, or in the last one.
249pub fn claims(ctx: &Context) -> Vec<Claimed> {
250    let pass = ctx.cumulative_pass_nr();
251    CLAIMS
252        .get(ctx)
253        .map(|c| c.in_force(pass))
254        .unwrap_or_default()
255}
256
257/// The uses seen or declared, by widget then gesture.
258pub fn uses(ctx: &Context) -> Vec<WidgetUse> {
259    CLAIMS
260        .get(ctx)
261        .map(|c| {
262            c.uses
263                .iter()
264                .map(|((widget, g), does)| WidgetUse {
265                    widget: widget.clone(),
266                    gesture: g.pointer().name(),
267                    does: does.clone(),
268                })
269                .collect()
270        })
271        .unwrap_or_default()
272}
273
274/// The claim of a gesture at a point, if a widget made one there (the
275/// last made wins).
276pub fn claimed_at(ctx: &Context, at: Pos2, gesture: Secondary) -> Option<Claimed> {
277    let list = claims(ctx);
278    if list.is_empty() {
279        return None;
280    }
281    let top = ctx.layer_id_at(at);
282    list.into_iter().rev().find(|c| {
283        c.claim.takes(gesture)
284            && c.rect.contains(at)
285            && !top.is_some_and(|t| t != c.layer && t.order > c.layer.order)
286    })
287}
288
289/// The claim of a gesture where the pointer was pressed (where it is,
290/// once released): what a canvas or a context menu asks before acting
291/// on a secondary click or drag.
292pub fn claimed(ctx: &Context, gesture: Secondary) -> Option<Claimed> {
293    let at = ctx.input(|i| i.pointer.press_origin().or(i.pointer.interact_pos()))?;
294    claimed_at(ctx, at, gesture)
295}
296
297/// Whether `response` opens its context menu in this pass: a secondary
298/// click no widget claimed there, or the context menu key (Shift+F10, or
299/// the `Menu` key) while it has the focus.
300pub fn opens_context_menu(response: &Response) -> bool {
301    (response.secondary_clicked() && claimed(&response.ctx, Secondary::Click).is_none())
302        || (response.has_focus() && menu_key(&response.ctx, false))
303}
304
305/// Whether the context menu key was pressed in this pass: Shift+F10, as on
306/// Windows, in GTK and Qt, or the `Menu` key alone. With `take`, the press
307/// is taken out of the input. A widget holding the focus for its rows (a
308/// tree, a list) asks this to open its cursor's menu.
309pub fn menu_key(ctx: &Context, take: bool) -> bool {
310    let pressed = |i: &egui::InputState| {
311        i.events.iter().any(|e| {
312            matches!(
313                e,
314                egui::Event::Key { key: egui::Key::F10, pressed: true, modifiers, .. }
315                    if modifiers.shift_only()
316            ) || matches!(
317                e,
318                egui::Event::Key { key: egui::Key::Menu, pressed: true, modifiers, .. }
319                    if !modifiers.any()
320            )
321        })
322    };
323    if !take {
324        return ctx.input(pressed);
325    }
326    ctx.input_mut(|i| {
327        let was = pressed(i);
328        if was {
329            i.consume_key(egui::Modifiers::SHIFT, egui::Key::F10);
330            i.consume_key(egui::Modifiers::NONE, egui::Key::Menu);
331        }
332        was
333    })
334}
335
336/// Where a context menu opened by the keyboard shows: under its widget,
337/// rather than at the pointer.
338const BY_KEY: Slot<bool> = Slot::new("egui_pop.context_menu_by_key");
339
340/// egui's [`Response::context_menu`], unless a widget claimed the
341/// secondary click where it happened: then the menu does not open. The
342/// context menu key opens it too while `response` has the focus, under the
343/// widget rather than at the pointer.
344pub fn context_menu<R>(
345    response: &Response,
346    add: impl FnOnce(&mut Ui) -> R,
347) -> Option<InnerResponse<R>> {
348    let by_key = response.has_focus() && menu_key(&response.ctx, true);
349    context_menu_opened(response, by_key, add)
350}
351
352/// As [`context_menu`], `by_key` saying that the keyboard opens it now: for a
353/// widget whose rows open menus while the focus stays on the widget (a
354/// tree's cursor row), which asks [`menu_key`] itself.
355pub fn context_menu_opened<R>(
356    response: &Response,
357    by_key: bool,
358    add: impl FnOnce(&mut Ui) -> R,
359) -> Option<InnerResponse<R>> {
360    let keyed = BY_KEY.keyed(response.id);
361    let open = if response.secondary_clicked() {
362        keyed.set(&response.ctx, false);
363        opens_context_menu(response).then_some(SetOpenCommand::Bool(true))
364    } else if by_key {
365        keyed.set(&response.ctx, true);
366        Some(SetOpenCommand::Bool(true))
367    } else if response.clicked() {
368        Some(SetOpenCommand::Bool(false))
369    } else {
370        None
371    };
372    let popup = egui::Popup::menu(response).open_memory(open);
373    let id = popup.get_id();
374    let popup = if keyed.get(&response.ctx).unwrap_or(false) {
375        popup
376    } else {
377        popup.at_pointer_fixed()
378    };
379    let shown = popup.show(add);
380    // On the overlays' watch (an application's bus): opened, closed and how.
381    let still = egui::Popup::is_id_open(&response.ctx, id);
382    crate::overlay::follow_popup(&response.ctx, id, "context menu", still, None);
383    shown
384}
385
386/// The claims in force and the uses seen, as the `pointer` collector
387/// shows them.
388pub fn report(ctx: &Context) -> Json {
389    let claims: Vec<Json> = claims(ctx)
390        .into_iter()
391        .map(|c| {
392            json!({
393                "id": format!("{:?}", c.id),
394                "widget": c.claim.widget,
395                "rect": [c.rect.min.x, c.rect.min.y, c.rect.width(), c.rect.height()],
396                "click": c.claim.click,
397                "drag": c.claim.drag,
398            })
399        })
400        .collect();
401    json!({ "claims": claims, "uses": uses(ctx) })
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn at(ctx: &Context, rect: Rect, claim: SecondaryClaim) {
409        claim_secondary_rect(
410            ctx,
411            Id::unique(&claim.widget),
412            LayerId::background(),
413            rect,
414            claim,
415        );
416    }
417
418    #[test]
419    fn a_claim_covers_its_rect_and_its_gestures_only() {
420        let ctx = Context::default();
421        let rect = Rect::from_min_size(Pos2::new(10.0, 10.0), egui::vec2(20.0, 20.0));
422        at(
423            &ctx,
424            rect,
425            SecondaryClaim::new("curve").click("Deletes a point"),
426        );
427        let inside = Pos2::new(15.0, 15.0);
428        assert!(claimed_at(&ctx, inside, Secondary::Click).is_some());
429        assert!(claimed_at(&ctx, inside, Secondary::Drag).is_none());
430        assert!(claimed_at(&ctx, Pos2::new(50.0, 50.0), Secondary::Click).is_none());
431        assert_eq!(
432            uses(&ctx),
433            vec![WidgetUse {
434                widget: "curve".into(),
435                gesture: "SecondaryClick".into(),
436                does: "Deletes a point".into(),
437            }]
438        );
439    }
440
441    #[test]
442    fn an_unlabelled_claim_is_not_a_use() {
443        let ctx = Context::default();
444        let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0));
445        at(&ctx, rect, SecondaryClaim::new("pad").drag(""));
446        assert!(claimed_at(&ctx, Pos2::new(5.0, 5.0), Secondary::Drag).is_some());
447        assert!(uses(&ctx).is_empty());
448    }
449}