Skip to main content

egui_pop_viewport/
cursor.rs

1//! Cursors over the viewport: what the active tool shows under the
2//! pointer, resolved each time the situation changes (the tool, the keys
3//! held, a drag, a handle under the pointer) and drawn crisp at the
4//! window's scale.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! A [`Cursor`] is one of:
10//!
11//! - a system cursor ([`egui::CursorIcon`]);
12//! - one of egui-pop's tool cursors ([`ToolCursor`]: a crosshair, an
13//!   eyedropper, a hand, zoom in and out...), drawn as a bitmap at the
14//!   cursor size and the window's scale, in the theme's colours, and
15//!   handed to the system as a real cursor;
16//! - a bitmap the application registered by name ([`register_image`]),
17//!   at several sizes, with a dark variant and frames if it wants;
18//! - a brush outline ([`BrushOutline`]) painted over the image, sized in
19//!   image pixels so it follows the zoom, the system cursor hidden.
20//!
21//! The viewport asks [`default_cursor`] for a [`CursorQuery`] (Alt turns
22//! zoom in into zoom out, a hand closes while dragging), then its
23//! [`on_cursor`](crate::Viewport::on_cursor) hook, which may give
24//! another cursor (`egui-pop-imaging` runs it as the `cursor.resolve`
25//! step). [`shown`] then decides what reaches the
26//! screen, under the [`CursorSettings`]: painted cursors may be turned
27//! off (system cursors only), and the cursor size follows the system's.
28//!
29//! Bitmap cursors go through `egui::Context::set_cursor_image`, which
30//! eframe's native integration hands to winit as a custom cursor; where
31//! it cannot (the web, immediate viewports), the system cursor given as
32//! the fallback shows instead.
33
34use std::collections::HashMap;
35use std::f32::consts::PI;
36use std::sync::Arc;
37
38use egui::{Color32, Context, CursorIcon, CustomCursorImage, Modifiers, Painter, Pos2, Stroke};
39use serde_json::{Value as Json, json};
40
41use egui_pop_core::state::Slot;
42
43use crate::overlay::HandleKind;
44use crate::tokens::ViewportTokens;
45
46/// The cursor size when the system says nothing, in points.
47pub const DEFAULT_SIZE: f32 = 24.0;
48
49/// Below this radius on screen (points), a brush outline gives way to a
50/// crosshair: too small to read, it would hide the point painted.
51pub const MIN_OUTLINE_RADIUS: f32 = 4.0;
52
53/// The side of the grid the built-in cursors are drawn on.
54const GRID: f32 = 32.0;
55
56/// egui-pop's tool cursors, drawn in the icon set's line style.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
58#[non_exhaustive]
59pub enum ToolCursor {
60    /// A precise point.
61    Crosshair,
62    /// An eyedropper: pick a value from the image.
63    Picker,
64    /// An open hand: the view can be dragged.
65    Hand,
66    /// A closed hand: the view (or a shape) is being dragged.
67    Grab,
68    ZoomIn,
69    ZoomOut,
70    /// Four arrows: move a shape.
71    Move,
72    /// A turning arrow: rotate a shape.
73    Rotate,
74    /// A paintbrush.
75    Brush,
76    /// An eraser.
77    Eraser,
78    /// A ring with a plus: add to a mask.
79    MaskAdd,
80    /// A ring with a minus: subtract from a mask.
81    MaskSubtract,
82    /// The tool cannot act here.
83    NotAllowed,
84}
85
86impl ToolCursor {
87    /// Every tool cursor (the gallery shows them).
88    pub const ALL: &'static [ToolCursor] = &[
89        ToolCursor::Crosshair,
90        ToolCursor::Picker,
91        ToolCursor::Hand,
92        ToolCursor::Grab,
93        ToolCursor::ZoomIn,
94        ToolCursor::ZoomOut,
95        ToolCursor::Move,
96        ToolCursor::Rotate,
97        ToolCursor::Brush,
98        ToolCursor::Eraser,
99        ToolCursor::MaskAdd,
100        ToolCursor::MaskSubtract,
101        ToolCursor::NotAllowed,
102    ];
103
104    /// Its name in kebab case (`zoom-in`).
105    pub fn name(self) -> &'static str {
106        match self {
107            ToolCursor::Crosshair => "crosshair",
108            ToolCursor::Picker => "picker",
109            ToolCursor::Hand => "hand",
110            ToolCursor::Grab => "grab",
111            ToolCursor::ZoomIn => "zoom-in",
112            ToolCursor::ZoomOut => "zoom-out",
113            ToolCursor::Move => "move",
114            ToolCursor::Rotate => "rotate",
115            ToolCursor::Brush => "brush",
116            ToolCursor::Eraser => "eraser",
117            ToolCursor::MaskAdd => "mask-add",
118            ToolCursor::MaskSubtract => "mask-subtract",
119            ToolCursor::NotAllowed => "not-allowed",
120        }
121    }
122
123    /// The tool cursor of a name, as [`ToolCursor::name`] gives it.
124    pub fn by_name(name: &str) -> Option<ToolCursor> {
125        ToolCursor::ALL.iter().copied().find(|t| t.name() == name)
126    }
127
128    /// The system cursor shown instead when painted cursors are off, or
129    /// where bitmap cursors cannot be shown.
130    pub fn system(self) -> CursorIcon {
131        match self {
132            ToolCursor::Hand => CursorIcon::Grab,
133            ToolCursor::Grab => CursorIcon::Grabbing,
134            ToolCursor::ZoomIn => CursorIcon::ZoomIn,
135            ToolCursor::ZoomOut => CursorIcon::ZoomOut,
136            ToolCursor::Move => CursorIcon::Move,
137            ToolCursor::NotAllowed => CursorIcon::NotAllowed,
138            ToolCursor::Crosshair
139            | ToolCursor::Picker
140            | ToolCursor::Rotate
141            | ToolCursor::Brush
142            | ToolCursor::Eraser
143            | ToolCursor::MaskAdd
144            | ToolCursor::MaskSubtract => CursorIcon::Crosshair,
145        }
146    }
147
148    /// Its hot spot, as a fraction of the cursor's side.
149    pub fn hotspot(self) -> [f32; 2] {
150        let h = shape(self).1;
151        [h[0] / GRID, h[1] / GRID]
152    }
153}
154
155/// What a brush outline carries beside the pointer.
156#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
157pub enum BrushMark {
158    #[default]
159    None,
160    /// A plus: the brush adds (to a mask).
161    Add,
162    /// A minus: the brush subtracts.
163    Subtract,
164    /// A cross: the brush erases.
165    Erase,
166}
167
168impl BrushMark {
169    pub fn name(self) -> &'static str {
170        match self {
171            BrushMark::None => "none",
172            BrushMark::Add => "add",
173            BrushMark::Subtract => "subtract",
174            BrushMark::Erase => "erase",
175        }
176    }
177
178    fn by_name(name: &str) -> BrushMark {
179        match name {
180            "add" => BrushMark::Add,
181            "subtract" => BrushMark::Subtract,
182            "erase" => BrushMark::Erase,
183            _ => BrushMark::None,
184        }
185    }
186}
187
188/// A brush outline: a ring of the brush's radius, in image pixels, so it
189/// follows the zoom, and an inner ring where its hardness ends (the
190/// feather between them).
191#[derive(Clone, Copy, Debug, PartialEq)]
192pub struct BrushOutline {
193    /// The brush's radius, in image pixels.
194    pub radius: f64,
195    /// The share of the radius painted at full strength, 0 to 1; the
196    /// inner ring is drawn below 1.
197    pub hardness: f32,
198    pub mark: BrushMark,
199}
200
201impl BrushOutline {
202    /// Its radius on screen, in points, at a zoom (physical pixels per
203    /// image pixel) on a window of `ppp` physical pixels per point.
204    pub fn screen_radius(&self, zoom: f64, ppp: f32) -> f32 {
205        (self.radius * zoom / f64::from(ppp.max(1e-3))) as f32
206    }
207}
208
209/// A cursor.
210#[derive(Clone, Debug, PartialEq)]
211pub enum Cursor {
212    /// One of the system's cursors.
213    System(CursorIcon),
214    /// One of egui-pop's tool cursors.
215    Tool(ToolCursor),
216    /// A bitmap the application registered by name ([`register_image`]).
217    Image(String),
218    /// A brush outline painted over the image, the system cursor hidden.
219    Brush(BrushOutline),
220}
221
222impl Default for Cursor {
223    fn default() -> Self {
224        Cursor::System(CursorIcon::Default)
225    }
226}
227
228impl Cursor {
229    /// A short name for traces and the debug bridge (`tool:zoom-in`).
230    pub fn name(&self) -> String {
231        match self {
232            Cursor::System(i) => format!("system:{i:?}"),
233            Cursor::Tool(t) => format!("tool:{}", t.name()),
234            Cursor::Image(n) => format!("image:{n}"),
235            Cursor::Brush(b) => format!("brush:{:.1}", b.radius),
236        }
237    }
238
239    /// As JSON: `{"system": "Crosshair"}`, `{"tool": "zoom-in"}`,
240    /// `{"image": "lasso"}` or `{"brush": {"radius", "hardness", "mark"}}`.
241    pub fn to_json(&self) -> Json {
242        match self {
243            Cursor::System(i) => json!({ "system": format!("{i:?}") }),
244            Cursor::Tool(t) => json!({ "tool": t.name() }),
245            Cursor::Image(n) => json!({ "image": n }),
246            Cursor::Brush(b) => json!({ "brush": {
247                "radius": b.radius,
248                "hardness": b.hardness,
249                "mark": b.mark.name(),
250            }}),
251        }
252    }
253
254    /// From [`Cursor::to_json`]'s form; `None` when it is not one.
255    pub fn from_json(v: &Json) -> Option<Cursor> {
256        if let Some(s) = v["system"].as_str() {
257            return CursorIcon::ALL
258                .iter()
259                .find(|i| format!("{i:?}") == s)
260                .map(|i| Cursor::System(*i));
261        }
262        if let Some(s) = v["tool"].as_str() {
263            return ToolCursor::by_name(s).map(Cursor::Tool);
264        }
265        if let Some(s) = v["image"].as_str() {
266            return Some(Cursor::Image(s.to_string()));
267        }
268        let b = &v["brush"];
269        let radius = b["radius"].as_f64()?;
270        Some(Cursor::Brush(BrushOutline {
271            radius,
272            hardness: b["hardness"].as_f64().unwrap_or(1.0) as f32,
273            mark: BrushMark::by_name(b["mark"].as_str().unwrap_or("none")),
274        }))
275    }
276}
277
278/// A brush tool's size and hardness.
279#[derive(Clone, Copy, Debug, PartialEq)]
280pub struct Brush {
281    /// The radius, in image pixels.
282    pub radius: f64,
283    /// The share of the radius at full strength, 0 to 1.
284    pub hardness: f32,
285}
286
287impl Brush {
288    pub fn new(radius: f64, hardness: f32) -> Brush {
289        Brush {
290            radius: radius.max(0.0),
291            hardness: hardness.clamp(0.0, 1.0),
292        }
293    }
294
295    fn outline(self, mark: BrushMark) -> BrushOutline {
296        BrushOutline {
297            radius: self.radius,
298            hardness: self.hardness,
299            mark,
300        }
301    }
302}
303
304/// The tool active over a viewport, which decides its cursor.
305#[derive(Clone, Debug, Default, PartialEq)]
306pub enum Tool {
307    /// No tool: the system's arrow (a hand while panning, a move cursor
308    /// over a handle).
309    #[default]
310    None,
311    /// Drag the view: an open hand, closed while dragging.
312    Pan,
313    /// Zoom in where clicked: Alt zooms out.
314    Zoom,
315    /// Pick a value: an eyedropper.
316    Picker,
317    /// Place a point: a crosshair.
318    Crosshair,
319    /// Move a shape.
320    Move,
321    /// Rotate a shape.
322    Rotate,
323    /// Paint: the brush's outline.
324    Brush(Brush),
325    /// Erase: the brush's outline, marked with a cross.
326    Eraser(Brush),
327    /// Paint a mask: the brush's outline marked with a plus, a minus
328    /// with Alt.
329    Mask(Brush),
330    /// The tool cannot act here (a locked layer).
331    Disabled,
332    /// A tool of the application's own, by name: its cursor comes from
333    /// the `on_cursor` hook (the system's arrow by default).
334    Named(String),
335}
336
337impl Tool {
338    /// Its name (`zoom`, `brush`, or a named tool's name).
339    pub fn name(&self) -> &str {
340        match self {
341            Tool::None => "none",
342            Tool::Pan => "pan",
343            Tool::Zoom => "zoom",
344            Tool::Picker => "picker",
345            Tool::Crosshair => "crosshair",
346            Tool::Move => "move",
347            Tool::Rotate => "rotate",
348            Tool::Brush(_) => "brush",
349            Tool::Eraser(_) => "eraser",
350            Tool::Mask(_) => "mask",
351            Tool::Disabled => "disabled",
352            Tool::Named(n) => n,
353        }
354    }
355
356    /// Its brush, for the tools that have one.
357    pub fn brush(&self) -> Option<Brush> {
358        match self {
359            Tool::Brush(b) | Tool::Eraser(b) | Tool::Mask(b) => Some(*b),
360            _ => None,
361        }
362    }
363}
364
365/// What a viewport knows when it asks which cursor to show. It asks
366/// again only when this changes.
367#[derive(Clone, Debug, PartialEq)]
368pub struct CursorQuery {
369    pub tool: Tool,
370    /// The keys held.
371    pub modifiers: Modifiers,
372    /// A button is held down on the viewport (a drag of the tool, of the
373    /// view or of a handle).
374    pub dragging: bool,
375    /// The view is being panned, or the pan key is held.
376    pub panning: bool,
377    /// The handle under the pointer, or the one dragged.
378    pub handle: Option<HandleKind>,
379    /// The pointer is over the image (not the background around it).
380    pub over_image: bool,
381}
382
383impl CursorQuery {
384    /// A query for a tool, nothing held.
385    pub fn new(tool: Tool) -> CursorQuery {
386        CursorQuery {
387            tool,
388            modifiers: Modifiers::NONE,
389            dragging: false,
390            panning: false,
391            handle: None,
392            over_image: true,
393        }
394    }
395
396    /// As JSON, for the `cursor.resolve` step.
397    pub fn to_json(&self) -> Json {
398        let m = self.modifiers;
399        let mut v = json!({
400            "tool": self.tool.name(),
401            "modifiers": {
402                "alt": m.alt,
403                "ctrl": m.ctrl,
404                "shift": m.shift,
405                "command": m.command,
406            },
407            "dragging": self.dragging,
408            "panning": self.panning,
409            "handle": self.handle.map(HandleKind::name),
410            "over_image": self.over_image,
411        });
412        if let Some(b) = self.tool.brush() {
413            v["brush"] = json!({ "radius": b.radius, "hardness": b.hardness });
414        }
415        v
416    }
417}
418
419/// The cursor egui-pop shows for a query, before the application's hook:
420///
421/// - panning (the pan key held, or a pan drag): an open hand, closed
422///   while dragging;
423/// - over a handle: a move cursor (a rotate cursor on a rotation
424///   handle), a closed hand while dragging it;
425/// - else the tool's: zoom in (zoom out with Alt), an eyedropper, a
426///   crosshair, a brush outline (mask brushes marked with a plus, a
427///   minus with Alt; erasers with a cross)...
428pub fn default_cursor(q: &CursorQuery) -> Cursor {
429    if q.panning {
430        return Cursor::Tool(if q.dragging {
431            ToolCursor::Grab
432        } else {
433            ToolCursor::Hand
434        });
435    }
436    if let Some(kind) = q.handle {
437        return Cursor::Tool(match (kind, q.dragging) {
438            (HandleKind::Rotate, _) => ToolCursor::Rotate,
439            (_, true) => ToolCursor::Grab,
440            (_, false) => ToolCursor::Move,
441        });
442    }
443    match &q.tool {
444        Tool::None | Tool::Named(_) => Cursor::System(CursorIcon::Default),
445        Tool::Pan => Cursor::Tool(if q.dragging {
446            ToolCursor::Grab
447        } else {
448            ToolCursor::Hand
449        }),
450        Tool::Zoom => Cursor::Tool(if q.modifiers.alt {
451            ToolCursor::ZoomOut
452        } else {
453            ToolCursor::ZoomIn
454        }),
455        Tool::Picker => Cursor::Tool(ToolCursor::Picker),
456        Tool::Crosshair => Cursor::Tool(ToolCursor::Crosshair),
457        Tool::Move => Cursor::Tool(if q.dragging {
458            ToolCursor::Grab
459        } else {
460            ToolCursor::Move
461        }),
462        Tool::Rotate => Cursor::Tool(ToolCursor::Rotate),
463        Tool::Brush(b) => Cursor::Brush(b.outline(BrushMark::None)),
464        Tool::Eraser(b) => Cursor::Brush(b.outline(BrushMark::Erase)),
465        Tool::Mask(b) => Cursor::Brush(b.outline(if q.modifiers.alt {
466            BrushMark::Subtract
467        } else {
468            BrushMark::Add
469        })),
470        Tool::Disabled => Cursor::Tool(ToolCursor::NotAllowed),
471    }
472}
473
474/// How cursors are shown in a context ([`set_settings`]).
475#[derive(Clone, Copy, Debug, PartialEq)]
476pub struct CursorSettings {
477    /// egui-pop's own cursors (tool bitmaps, registered images, brush
478    /// outlines); off, system cursors only.
479    pub painted: bool,
480    /// The cursor size, in points; `None` follows the system's
481    /// ([`system_size`]).
482    pub size: Option<f32>,
483}
484
485impl Default for CursorSettings {
486    fn default() -> Self {
487        CursorSettings {
488            painted: true,
489            size: None,
490        }
491    }
492}
493
494const SETTINGS: Slot<CursorSettings> = Slot::new("viewport.cursor.settings");
495
496/// The cursor settings of a context.
497pub fn settings(ctx: &Context) -> CursorSettings {
498    SETTINGS.get_or_default(ctx)
499}
500
501/// Sets the cursor settings of a context (an application maps its own
502/// settings here).
503pub fn set_settings(ctx: &Context, settings: CursorSettings) {
504    SETTINGS.set(ctx, settings);
505}
506
507/// The system's cursor size, in points: `XCURSOR_SIZE` where it is set
508/// (X11 and Wayland desktops), else [`DEFAULT_SIZE`].
509pub fn system_size() -> f32 {
510    // upstream: winit does not report the cursor size (docs/upstream.md).
511    parse_size(std::env::var("XCURSOR_SIZE").ok().as_deref())
512}
513
514/// A cursor size from the text of `XCURSOR_SIZE`: 8 to 256, else the
515/// default.
516pub fn parse_size(text: Option<&str>) -> f32 {
517    text.and_then(|s| s.trim().parse::<f32>().ok())
518        .filter(|s| (8.0..=256.0).contains(s))
519        .unwrap_or(DEFAULT_SIZE)
520}
521
522/// The cursor size in use in a context, in points.
523pub fn size(ctx: &Context) -> f32 {
524    settings(ctx)
525        .size
526        .unwrap_or_else(system_size)
527        .clamp(8.0, 256.0)
528}
529
530/// A bitmap of a cursor: straight (not premultiplied) RGBA.
531#[derive(Clone, Debug, PartialEq, Eq)]
532pub struct Bitmap {
533    pub rgba: Arc<[u8]>,
534    /// Width and height, in physical pixels.
535    pub size: [u16; 2],
536    /// The hot spot, in physical pixels from the top left.
537    pub hotspot: [u16; 2],
538}
539
540impl Bitmap {
541    /// A bitmap, or `None` when the pixels do not fill `size` or the hot
542    /// spot falls outside (or the side is over winit's 2048).
543    pub fn new(rgba: impl Into<Arc<[u8]>>, size: [u16; 2], hotspot: [u16; 2]) -> Option<Bitmap> {
544        let rgba = rgba.into();
545        let ok = rgba.len() == usize::from(size[0]) * usize::from(size[1]) * 4
546            && size[0] > 0
547            && size[1] > 0
548            && size[0] <= 2048
549            && size[1] <= 2048
550            && hotspot[0] < size[0]
551            && hotspot[1] < size[1];
552        ok.then_some(Bitmap {
553            rgba,
554            size,
555            hotspot,
556        })
557    }
558
559    fn image(&self) -> CustomCursorImage {
560        CustomCursorImage {
561            rgba: self.rgba.clone(),
562            size: self.size,
563            hotspot: self.hotspot,
564        }
565    }
566}
567
568/// A cursor of the application's: bitmaps at several sizes (give one per
569/// scale used: 1x, 1.5x, 2x...), a dark theme's variant, more frames
570/// for an animation, and the system cursor shown where bitmaps cannot be.
571#[derive(Clone, Debug, PartialEq)]
572pub struct CursorImage {
573    pub sizes: Vec<Bitmap>,
574    /// The bitmaps for a dark theme (empty: `sizes` in every theme).
575    pub dark: Vec<Bitmap>,
576    /// The frames after the first (`sizes`) of an animated cursor, each
577    /// at its sizes; shown only when motion is not reduced.
578    pub frames: Vec<Vec<Bitmap>>,
579    /// Seconds per frame.
580    pub frame_time: f32,
581    pub fallback: CursorIcon,
582}
583
584impl CursorImage {
585    /// An image with no bitmap yet, falling back to `fallback`.
586    pub fn new(fallback: CursorIcon) -> CursorImage {
587        CursorImage {
588            sizes: Vec::new(),
589            dark: Vec::new(),
590            frames: Vec::new(),
591            frame_time: 0.1,
592            fallback,
593        }
594    }
595
596    /// Adds a size.
597    pub fn size(mut self, bitmap: Bitmap) -> CursorImage {
598        self.sizes.push(bitmap);
599        self
600    }
601
602    /// Adds a size of the dark theme's variant.
603    pub fn dark(mut self, bitmap: Bitmap) -> CursorImage {
604        self.dark.push(bitmap);
605        self
606    }
607
608    /// Adds a frame (its sizes) to an animation.
609    pub fn frame(mut self, sizes: Vec<Bitmap>) -> CursorImage {
610        self.frames.push(sizes);
611        self
612    }
613
614    /// The number of frames (1 for a still cursor).
615    pub fn frame_count(&self) -> usize {
616        1 + self.frames.len()
617    }
618
619    /// The bitmap for a side in physical pixels: the smallest at least
620    /// that wide, else the largest; in a dark theme the dark variant
621    /// when there is one; frame `frame` of an animation.
622    pub fn pick(&self, side: u32, dark: bool, frame: usize) -> Option<&Bitmap> {
623        let set = match frame % self.frame_count() {
624            0 if dark && !self.dark.is_empty() => &self.dark,
625            0 => &self.sizes,
626            i => &self.frames[i - 1],
627        };
628        set.iter()
629            .filter(|b| u32::from(b.size[0]) >= side)
630            .min_by_key(|b| b.size[0])
631            .or_else(|| set.iter().max_by_key(|b| b.size[0]))
632    }
633}
634
635/// The cursor images registered, by name.
636const IMAGES: Slot<HashMap<String, CursorImage>> = Slot::new("viewport.cursor.images");
637
638/// Registers a cursor image under a name, for [`Cursor::Image`].
639pub fn register_image(ctx: &Context, name: impl Into<String>, image: CursorImage) {
640    let name = name.into();
641    IMAGES.update(ctx, |m| m.insert(name, image));
642}
643
644/// The cursor image registered under a name.
645pub fn image(ctx: &Context, name: &str) -> Option<CursorImage> {
646    IMAGES.get(ctx).and_then(|m| m.get(name).cloned())
647}
648
649/// What reaches the screen for a cursor.
650#[derive(Clone, Debug, PartialEq)]
651pub enum Shown {
652    /// A system cursor.
653    System(CursorIcon),
654    /// A tool cursor's bitmap.
655    Tool(ToolCursor),
656    /// A registered image's bitmap.
657    Image(String),
658    /// A brush outline of `radius` points (its hardness ring at `inner`
659    /// points, 0 for none), the system cursor hidden.
660    Outline {
661        radius: f32,
662        inner: f32,
663        mark: BrushMark,
664    },
665}
666
667/// What a cursor shows in a context at a zoom (physical pixels per image
668/// pixel) and scale: with painted cursors off, the system cursor
669/// standing for it; a brush outline under [`MIN_OUTLINE_RADIUS`], a
670/// crosshair; an image nobody registered, its name's system arrow.
671pub fn shown(ctx: &Context, cursor: &Cursor, zoom: f64, ppp: f32) -> Shown {
672    let painted = settings(ctx).painted;
673    match cursor {
674        Cursor::System(i) => Shown::System(*i),
675        Cursor::Tool(t) if painted => Shown::Tool(*t),
676        Cursor::Tool(t) => Shown::System(t.system()),
677        Cursor::Image(name) => match image(ctx, name) {
678            Some(_) if painted => Shown::Image(name.clone()),
679            Some(img) => Shown::System(img.fallback),
680            None => Shown::System(CursorIcon::Default),
681        },
682        Cursor::Brush(b) => {
683            let radius = b.screen_radius(zoom, ppp);
684            if !painted {
685                Shown::System(CursorIcon::Crosshair)
686            } else if radius < MIN_OUTLINE_RADIUS {
687                Shown::Tool(ToolCursor::Crosshair)
688            } else {
689                let inner = radius * b.hardness.clamp(0.0, 1.0);
690                let inner = if b.hardness < 0.98 && inner >= 2.0 {
691                    inner
692                } else {
693                    0.0
694                };
695                Shown::Outline {
696                    radius,
697                    inner,
698                    mark: b.mark,
699                }
700            }
701        }
702    }
703}
704
705/// Shows a cursor for this frame at `pos`: sets the system cursor, hands
706/// a bitmap to the integration, or paints an outline with `painter`.
707/// Returns whether a bitmap was set: the caller clears it
708/// ([`clear_image`]) once the pointer leaves, as egui keeps it from frame
709/// to frame.
710pub fn apply(ctx: &Context, painter: &Painter, pos: Pos2, shown: &Shown) -> bool {
711    match shown {
712        Shown::System(i) => {
713            if *i != CursorIcon::Default {
714                ctx.set_cursor_icon(*i);
715            }
716            false
717        }
718        Shown::Tool(t) => {
719            // upstream: the bitmap is dropped on the web and in immediate
720            // viewports; the system cursor below stands in there
721            // (docs/upstream.md).
722            ctx.set_cursor_image(Some(tool_image(ctx, *t)));
723            ctx.set_cursor_icon(t.system());
724            true
725        }
726        Shown::Image(name) => {
727            let Some(img) = image(ctx, name) else {
728                return false;
729            };
730            let side = (size(ctx) * ctx.pixels_per_point()).round() as u32;
731            let tokens = egui_pop_core::theme::Tokens::of(ctx);
732            let dark = tokens.dark_mode();
733            let reduced = tokens.motion_duration == 0.0;
734            let frame = if reduced || img.frame_count() == 1 {
735                0
736            } else {
737                let t = img.frame_time.max(0.01);
738                ctx.request_repaint_after(std::time::Duration::from_secs_f32(t));
739                (ctx.input(|i| i.time) / f64::from(t)) as usize
740            };
741            ctx.set_cursor_icon(img.fallback);
742            match img.pick(side, dark, frame) {
743                Some(b) => {
744                    ctx.set_cursor_image(Some(b.image()));
745                    true
746                }
747                None => false,
748            }
749        }
750        Shown::Outline {
751            radius,
752            inner,
753            mark,
754        } => {
755            ctx.set_cursor_icon(CursorIcon::None);
756            paint_outline(painter, pos, *radius, *inner, *mark);
757            false
758        }
759    }
760}
761
762/// Clears a bitmap cursor set by [`apply`].
763pub fn clear_image(ctx: &Context) {
764    ctx.set_cursor_image(None);
765}
766
767/// Paints a brush outline: a ring of `radius` points, a lighter one at
768/// `inner` (none at 0), a point at the centre and the mark beside it,
769/// each a line over a wider one in the outline colour so it reads on any
770/// image.
771pub fn paint_outline(painter: &Painter, pos: Pos2, radius: f32, inner: f32, mark: BrushMark) {
772    let t = ViewportTokens::of(painter.ctx());
773    let w = |x: f32| egui_pop_core::scale::stroke(painter.ctx(), x);
774    let under = Stroke::new(w(3.0), t.cursor_outline);
775    let line = Stroke::new(w(1.0), t.cursor_fill);
776    painter.circle_stroke(pos, radius, under);
777    painter.circle_stroke(pos, radius, line);
778    if inner > 0.0 {
779        let faint = Stroke::new(w(1.0), t.cursor_fill.gamma_multiply(0.6));
780        painter.circle_stroke(
781            pos,
782            inner,
783            Stroke::new(w(2.0), t.cursor_outline.gamma_multiply(0.6)),
784        );
785        painter.circle_stroke(pos, inner, faint);
786    }
787    painter.circle_filled(pos, w(2.5), t.cursor_outline);
788    painter.circle_filled(pos, w(1.0), t.cursor_fill);
789    let s = 4.0;
790    let c = pos + egui::vec2(radius.min(24.0) * 0.5 + 8.0, radius.min(24.0) * 0.5 + 8.0);
791    let mut segments: Vec<[Pos2; 2]> = Vec::new();
792    match mark {
793        BrushMark::None => {}
794        BrushMark::Add => {
795            segments.push([c - egui::vec2(s, 0.0), c + egui::vec2(s, 0.0)]);
796            segments.push([c - egui::vec2(0.0, s), c + egui::vec2(0.0, s)]);
797        }
798        BrushMark::Subtract => {
799            segments.push([c - egui::vec2(s, 0.0), c + egui::vec2(s, 0.0)]);
800        }
801        BrushMark::Erase => {
802            segments.push([c - egui::vec2(s, s) * 0.8, c + egui::vec2(s, s) * 0.8]);
803            segments.push([c + egui::vec2(-s, s) * 0.8, c + egui::vec2(s, -s) * 0.8]);
804        }
805    }
806    for seg in &segments {
807        painter.line_segment(*seg, Stroke::new(w(4.0), t.cursor_outline));
808    }
809    for seg in &segments {
810        painter.line_segment(*seg, Stroke::new(w(2.0), t.cursor_fill));
811    }
812}
813
814/// The tool cursors' bitmaps made, by tool, side and colours.
815const BITMAPS: Slot<HashMap<CacheKey, CustomCursorImage>> = Slot::new("viewport.cursor.bitmaps");
816/// A tool cursor sample's texture and the colours it was made with, per
817/// tool and side.
818const SAMPLES: Slot<([[u8; 4]; 2], egui::TextureHandle)> = Slot::opaque("viewport.cursor.samples");
819
820type CacheKey = (ToolCursor, u32, [u8; 4], [u8; 4]);
821
822/// A tool cursor's bitmap at the context's cursor size and scale, in the
823/// theme's colours; drawn once, then kept.
824pub fn tool_image(ctx: &Context, tool: ToolCursor) -> CustomCursorImage {
825    let side = ((size(ctx) * ctx.pixels_per_point()).round() as u32).clamp(8, 512);
826    let t = ViewportTokens::of(ctx);
827    let key: CacheKey = (
828        tool,
829        side,
830        t.cursor_fill.to_array(),
831        t.cursor_outline.to_array(),
832    );
833    if let Some(img) = BITMAPS.get(ctx).and_then(|m| m.get(&key).cloned()) {
834        return img;
835    }
836    let rgba = rasterize(tool, side, t.cursor_fill, t.cursor_outline);
837    let h = shape(tool).1;
838    let at = |v: f32| ((v / GRID * side as f32).floor() as u32).min(side - 1) as u16;
839    let img = CustomCursorImage {
840        rgba: rgba.into(),
841        size: [side as u16, side as u16],
842        hotspot: [at(h[0]), at(h[1])],
843    };
844    BITMAPS.update(ctx, |m| m.insert(key, img.clone()));
845    img
846}
847
848/// One stroke or fill of a built-in cursor, on a 32-unit grid.
849#[derive(Clone, Copy, Debug)]
850enum Prim {
851    /// A line with round ends: from, to, width.
852    Seg([f32; 2], [f32; 2], f32),
853    /// A circle's outline: centre, radius, width.
854    Ring([f32; 2], f32, f32),
855    /// An arc: centre, radius, from and to (radians, clockwise on
856    /// screen, `to` after `from`), width.
857    Arc([f32; 2], f32, f32, f32, f32),
858    /// A filled disc: centre, radius.
859    Disc([f32; 2], f32),
860    /// A filled polygon.
861    Poly(&'static [[f32; 2]]),
862}
863
864const UP: &[[f32; 2]] = &[[16.0, 2.0], [11.0, 8.0], [21.0, 8.0]];
865const DOWN: &[[f32; 2]] = &[[16.0, 30.0], [11.0, 24.0], [21.0, 24.0]];
866const LEFT: &[[f32; 2]] = &[[2.0, 16.0], [8.0, 11.0], [8.0, 21.0]];
867const RIGHT: &[[f32; 2]] = &[[30.0, 16.0], [24.0, 11.0], [24.0, 21.0]];
868const PALM: &[[f32; 2]] = &[
869    [8.0, 17.0],
870    [24.0, 17.0],
871    [23.0, 25.0],
872    [19.0, 29.0],
873    [12.0, 29.0],
874    [8.0, 24.0],
875];
876const ROTATE_HEAD: &[[f32; 2]] = &[[20.0, 3.0], [27.0, 7.5], [20.0, 12.0]];
877const BRUSH_TIP: &[[f32; 2]] = &[
878    [10.0, 17.0],
879    [15.0, 22.0],
880    [6.0, 30.0],
881    [2.0, 30.0],
882    [2.0, 26.0],
883];
884
885/// A built-in cursor's strokes and its hot spot, on the 32-unit grid.
886fn shape(tool: ToolCursor) -> (Vec<Prim>, [f32; 2]) {
887    use Prim::{Arc, Disc, Poly, Ring, Seg};
888    match tool {
889        ToolCursor::Crosshair => (
890            vec![
891                Seg([16.0, 3.0], [16.0, 12.0], 2.0),
892                Seg([16.0, 20.0], [16.0, 29.0], 2.0),
893                Seg([3.0, 16.0], [12.0, 16.0], 2.0),
894                Seg([20.0, 16.0], [29.0, 16.0], 2.0),
895                Disc([16.0, 16.0], 1.2),
896            ],
897            [16.0, 16.0],
898        ),
899        ToolCursor::Picker => (
900            vec![
901                Seg([3.5, 28.5], [18.0, 14.0], 3.0),
902                Seg([13.0, 9.0], [23.0, 19.0], 2.5),
903                Seg([19.0, 13.0], [25.0, 7.0], 6.0),
904                Disc([26.0, 6.0], 4.0),
905            ],
906            [3.0, 29.0],
907        ),
908        ToolCursor::Hand => (
909            vec![
910                Seg([10.0, 9.0], [10.0, 19.0], 3.5),
911                Seg([14.0, 5.0], [14.0, 18.0], 3.5),
912                Seg([18.0, 5.0], [18.0, 18.0], 3.5),
913                Seg([22.0, 8.0], [22.0, 19.0], 3.5),
914                Seg([5.5, 15.0], [9.5, 21.0], 3.5),
915                Poly(PALM),
916            ],
917            [16.0, 16.0],
918        ),
919        ToolCursor::Grab => (
920            vec![
921                Seg([10.0, 14.0], [10.0, 19.0], 3.5),
922                Seg([14.0, 12.0], [14.0, 18.0], 3.5),
923                Seg([18.0, 12.0], [18.0, 18.0], 3.5),
924                Seg([22.0, 14.0], [22.0, 19.0], 3.5),
925                Seg([7.5, 18.0], [9.5, 21.0], 3.5),
926                Poly(PALM),
927            ],
928            [16.0, 16.0],
929        ),
930        ToolCursor::ZoomIn | ToolCursor::ZoomOut => {
931            let mut v = vec![
932                Ring([13.0, 13.0], 8.5, 2.5),
933                Seg([19.5, 19.5], [28.0, 28.0], 4.0),
934                Seg([9.0, 13.0], [17.0, 13.0], 2.0),
935            ];
936            if tool == ToolCursor::ZoomIn {
937                v.push(Seg([13.0, 9.0], [13.0, 17.0], 2.0));
938            }
939            (v, [13.0, 13.0])
940        }
941        ToolCursor::Move => (
942            vec![
943                Seg([16.0, 6.0], [16.0, 26.0], 2.0),
944                Seg([6.0, 16.0], [26.0, 16.0], 2.0),
945                Poly(UP),
946                Poly(DOWN),
947                Poly(LEFT),
948                Poly(RIGHT),
949            ],
950            [16.0, 16.0],
951        ),
952        ToolCursor::Rotate => (
953            vec![
954                Arc([16.0, 16.0], 10.0, -PI * 0.45, PI * 1.25, 2.5),
955                Poly(ROTATE_HEAD),
956                Disc([16.0, 16.0], 1.5),
957            ],
958            [16.0, 16.0],
959        ),
960        ToolCursor::Brush => (
961            vec![
962                Seg([28.0, 4.0], [15.0, 17.0], 3.0),
963                Seg([16.5, 15.5], [12.5, 19.5], 5.0),
964                Poly(BRUSH_TIP),
965            ],
966            [3.0, 29.0],
967        ),
968        ToolCursor::Eraser => (
969            vec![
970                Seg([6.0, 22.0], [18.0, 10.0], 2.0),
971                Seg([18.0, 10.0], [26.0, 18.0], 2.0),
972                Seg([26.0, 18.0], [14.0, 30.0], 2.0),
973                Seg([14.0, 30.0], [6.0, 22.0], 2.0),
974                Seg([10.0, 18.0], [18.0, 26.0], 2.0),
975            ],
976            [9.0, 25.0],
977        ),
978        ToolCursor::MaskAdd | ToolCursor::MaskSubtract => {
979            let mut v = vec![
980                Ring([12.0, 12.0], 8.0, 2.0),
981                Disc([12.0, 12.0], 1.2),
982                Seg([21.0, 26.0], [29.0, 26.0], 2.5),
983            ];
984            if tool == ToolCursor::MaskAdd {
985                v.push(Seg([25.0, 22.0], [25.0, 30.0], 2.5));
986            }
987            (v, [12.0, 12.0])
988        }
989        ToolCursor::NotAllowed => (
990            vec![
991                Ring([16.0, 16.0], 11.0, 3.0),
992                Seg([8.5, 23.5], [23.5, 8.5], 3.0),
993            ],
994            [16.0, 16.0],
995        ),
996    }
997}
998
999fn sub(a: [f32; 2], b: [f32; 2]) -> [f32; 2] {
1000    [a[0] - b[0], a[1] - b[1]]
1001}
1002
1003fn len(v: [f32; 2]) -> f32 {
1004    v[0].hypot(v[1])
1005}
1006
1007fn segment_distance(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
1008    let ab = sub(b, a);
1009    let ap = sub(p, a);
1010    let l2 = ab[0] * ab[0] + ab[1] * ab[1];
1011    let t = if l2 > 0.0 {
1012        ((ap[0] * ab[0] + ap[1] * ab[1]) / l2).clamp(0.0, 1.0)
1013    } else {
1014        0.0
1015    };
1016    len([ap[0] - ab[0] * t, ap[1] - ab[1] * t])
1017}
1018
1019/// The signed distance from `p` to a primitive (negative inside), in
1020/// grid units.
1021fn distance(prim: &Prim, p: [f32; 2]) -> f32 {
1022    match *prim {
1023        Prim::Seg(a, b, w) => segment_distance(p, a, b) - w / 2.0,
1024        Prim::Ring(c, r, w) => (len(sub(p, c)) - r).abs() - w / 2.0,
1025        Prim::Arc(c, r, from, to, w) => {
1026            let d = sub(p, c);
1027            let a = d[1].atan2(d[0]);
1028            let along = from + (a - from).rem_euclid(2.0 * PI);
1029            if along <= to {
1030                (len(d) - r).abs() - w / 2.0
1031            } else {
1032                let end = |t: f32| [c[0] + r * t.cos(), c[1] + r * t.sin()];
1033                len(sub(p, end(from))).min(len(sub(p, end(to)))) - w / 2.0
1034            }
1035        }
1036        Prim::Disc(c, r) => len(sub(p, c)) - r,
1037        Prim::Poly(pts) => {
1038            let mut d = f32::MAX;
1039            let mut inside = false;
1040            for (i, &a) in pts.iter().enumerate() {
1041                let b = pts[(i + 1) % pts.len()];
1042                d = d.min(segment_distance(p, a, b));
1043                if (a[1] > p[1]) != (b[1] > p[1])
1044                    && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0]
1045                {
1046                    inside = !inside;
1047                }
1048            }
1049            if inside { -d } else { d }
1050        }
1051    }
1052}
1053
1054/// Draws a tool cursor at `side` physical pixels: its strokes in `fill`,
1055/// ringed by `outline` (about a pixel at 24, more when larger), with
1056/// anti-aliased edges. Straight RGBA, row by row.
1057pub fn rasterize(tool: ToolCursor, side: u32, fill: Color32, outline: Color32) -> Vec<u8> {
1058    let prims = shape(tool).0;
1059    let side_f = side as f32;
1060    let units = GRID / side_f;
1061    let halo = (side_f / 24.0).max(1.0);
1062    let mut out = Vec::with_capacity((side * side * 4) as usize);
1063    for y in 0..side {
1064        for x in 0..side {
1065            let p = [(x as f32 + 0.5) * units, (y as f32 + 0.5) * units];
1066            let d = prims
1067                .iter()
1068                .map(|prim| distance(prim, p))
1069                .fold(f32::MAX, f32::min)
1070                / units;
1071            let f = (0.5 - d).clamp(0.0, 1.0);
1072            let o = (0.5 - (d - halo)).clamp(0.0, 1.0);
1073            let a = f + (1.0 - f) * o;
1074            if a <= 0.0 {
1075                out.extend_from_slice(&[0, 0, 0, 0]);
1076                continue;
1077            }
1078            let mix = |c1: u8, c2: u8| {
1079                ((f32::from(c1) * f + f32::from(c2) * (1.0 - f) * o) / a)
1080                    .round()
1081                    .clamp(0.0, 255.0) as u8
1082            };
1083            out.extend_from_slice(&[
1084                mix(fill.r(), outline.r()),
1085                mix(fill.g(), outline.g()),
1086                mix(fill.b(), outline.b()),
1087                (a * 255.0).round() as u8,
1088            ]);
1089        }
1090    }
1091    out
1092}
1093
1094/// Paints a tool cursor with `painter` in a square (the gallery's
1095/// samples, a legend): the bitmap the system would show, as a texture.
1096pub fn paint_sample(ui: &egui::Ui, rect: egui::Rect, tool: ToolCursor) {
1097    let ppp = ui.ctx().pixels_per_point();
1098    let side = ((rect.width() * ppp).round() as u32).clamp(8, 512);
1099    let t = ViewportTokens::of(ui.ctx());
1100    let id = SAMPLES.keyed((tool, side));
1101    let key = (t.cursor_fill.to_array(), t.cursor_outline.to_array());
1102    let texture = id.get(ui.ctx());
1103    let handle = match texture {
1104        Some((k, h)) if k == [key.0, key.1] => h,
1105        _ => {
1106            let rgba = rasterize(tool, side, t.cursor_fill, t.cursor_outline);
1107            let image =
1108                egui::ColorImage::from_rgba_unmultiplied([side as usize, side as usize], &rgba);
1109            let h = ui.ctx().load_texture(
1110                format!("egui-pop-cursor-{}-{side}", tool.name()),
1111                image,
1112                egui::TextureOptions::NEAREST,
1113            );
1114            id.set(ui.ctx(), ([key.0, key.1], h.clone()));
1115            h
1116        }
1117    };
1118    ui.painter().image(
1119        handle.id(),
1120        rect,
1121        egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
1122        Color32::WHITE,
1123    );
1124}