Skip to main content

waft_services/
mouse_cursor.rs

1//! Flutter counterpart: `services/mouse_cursor.dart`.
2
3use std::any::Any;
4use std::collections::HashMap;
5use std::fmt;
6use std::rc::Rc;
7
8use waft_embedder::{Platform, SystemMouseCursorKind, ViewId};
9use waft_foundation::describe_enum;
10use waft_gestures::PointerEvent;
11
12/// A shared reference to an immutable [`MouseCursor`] (a Dart object reference).
13pub type MouseCursorRef = Rc<dyn MouseCursor>;
14
15/// Maintains the state of mouse cursors and manages how cursors are searched
16/// for.
17///
18/// This is typically created as a global singleton and owned by `MouseTracker`.
19pub struct MouseCursorManager {
20    /// The mouse cursor to use if all cursor candidates choose to defer.
21    ///
22    /// See also:
23    ///
24    ///  * `MouseCursor.defer`, the mouse cursor object to use to defer.
25    pub fallback_mouse_cursor: MouseCursorRef,
26    last_session: HashMap<i64, Box<dyn MouseCursorSession>>,
27}
28
29impl MouseCursorManager {
30    /// Create a [`MouseCursorManager`] by specifying the fallback cursor.
31    ///
32    /// The `fallback_mouse_cursor` must not be `MouseCursor.defer`.
33    pub fn new(fallback_mouse_cursor: MouseCursorRef) -> MouseCursorManager {
34        debug_assert!(!fallback_mouse_cursor.is_defer());
35        MouseCursorManager {
36            fallback_mouse_cursor,
37            last_session: HashMap::new(),
38        }
39    }
40
41    /// Returns the active mouse cursor of a device.
42    ///
43    /// The return value is the last [`MouseCursor`] activated onto this device,
44    /// even if the activation failed.
45    ///
46    /// This function is only active in debug mode: in release it returns `None`.
47    pub fn debug_device_active_cursor(&self, device: i64) -> Option<MouseCursorRef> {
48        if !cfg!(debug_assertions) {
49            return None;
50        }
51        self.last_session
52            .get(&device)
53            .map(|session| session.cursor())
54    }
55
56    /// Handles the changes that cause a pointer device to have a new list of
57    /// mouse cursor candidates.
58    ///
59    /// This change can be caused by a pointer event, in which case
60    /// `triggering_event` should not be `None`, or by other changes, such as when a
61    /// widget has moved under a still mouse, which is detected after the current
62    /// frame is complete. In either case, `cursor_candidates` should be the list
63    /// of cursors at the location of the mouse in hit-test order.
64    ///
65    /// `view` is the one the device is on, from its latest event: the cursor is that view's
66    /// host's to show, and the session asks it.
67    pub fn handle_device_cursor_update(
68        &mut self,
69        platform: &dyn Platform,
70        view: ViewId,
71        device: i64,
72        triggering_event: Option<&PointerEvent>,
73        cursor_candidates: impl IntoIterator<Item = MouseCursorRef>,
74    ) {
75        if let Some(PointerEvent::Removed(_)) = triggering_event {
76            self.last_session.remove(&device);
77            return;
78        }
79        let next_cursor = first_non_deferred(cursor_candidates)
80            .unwrap_or_else(|| Rc::clone(&self.fallback_mouse_cursor));
81        debug_assert!(!next_cursor.is_defer());
82        if let Some(last_session) = self.last_session.get(&device)
83            && *last_session.cursor() == *next_cursor
84        {
85            return;
86        }
87        let mut next_session = next_cursor.create_session(device);
88        if let Some(mut last_session) = self.last_session.remove(&device) {
89            last_session.dispose();
90        }
91        next_session.activate(platform, view);
92        self.last_session.insert(device, next_session);
93    }
94}
95
96/// Manages the duration that a pointing device should display a specific mouse
97/// cursor.
98///
99/// While [`MouseCursor`] classes describe the kind of cursors, [`MouseCursorSession`]
100/// classes represent a continuous use of the cursor on a pointing device. The
101/// [`MouseCursorSession`] classes can be stateful. For example, a cursor that
102/// needs to load resources might want to try a fallback cursor first, and switch
103/// to the target cursor when the resources are loaded.
104///
105/// A [`MouseCursorSession`] has the following lifecycle:
106///
107///  * When a pointing device should start displaying a cursor, `MouseTracker`
108///    creates a session by calling [`MouseCursor::create_session`] on the target
109///    cursor, and stores it in a table associated with the device.
110///  * `MouseTracker` then immediately calls the session's [`activate`], where
111///    the session should fetch resources and make system calls.
112///  * When the pointing device should start displaying another cursor,
113///    `MouseTracker` calls [`dispose`] on this session. After [`dispose`], this
114///    session will no longer be used in the future.
115///
116/// [`activate`]: MouseCursorSession::activate
117/// [`dispose`]: MouseCursorSession::dispose
118pub trait MouseCursorSession {
119    /// The cursor that created this session.
120    fn cursor(&self) -> MouseCursorRef;
121
122    /// The device ID of the pointing device.
123    fn device(&self) -> i64;
124
125    /// Override this method to do the work of changing the cursor of the device.
126    ///
127    /// Called right after this session is created.
128    ///
129    /// This method has full control over the cursor until the [`dispose`] call,
130    /// and can make system calls to change the pointer cursor as many times as
131    /// necessary (usually through the system cursor request of the host of `view`,
132    /// the one the device is on, which `platform` finds; a session that changes the
133    /// cursor later keeps it).
134    ///
135    /// [`dispose`]: MouseCursorSession::dispose
136    fn activate(&mut self, platform: &dyn Platform, view: ViewId);
137
138    /// Called when device stops displaying the cursor.
139    ///
140    /// After this call, this session instance will no longer be used in the
141    /// future.
142    ///
143    /// When implementing this method in subclasses, you should release resources
144    /// and prevent [`activate`] from causing side effects after disposal.
145    ///
146    /// [`activate`]: MouseCursorSession::activate
147    fn dispose(&mut self);
148}
149
150/// An interface for mouse cursor definitions.
151///
152/// A mouse cursor is a graphical image on the screen that echoes the movement
153/// of a pointing device, such as a mouse or a stylus. A [`MouseCursor`] object
154/// defines a kind of mouse cursor, such as an arrow, a pointing hand, or an
155/// I-beam.
156///
157/// During the painting phase, [`MouseCursor`] objects are assigned to regions on
158/// the screen via annotations. Later during a device update (e.g. when a mouse
159/// moves), `MouseTracker` finds the _active cursor_, the top-most region
160/// associated with the position of each mouse device, and activates the cursor
161/// as necessary.
162///
163/// ## Cursor classes
164///
165/// A [`SystemMouseCursor`] is a cursor that is natively supported by the
166/// platform that the program is running on. All supported system mouse cursors
167/// are enumerated in [`SystemMouseCursors`].
168///
169/// ## Using cursors
170///
171/// A [`MouseCursor`] object is used by being assigned to a `MouseRegion` or
172/// another widget that exposes the `MouseRegion` API, such as
173/// `InkResponse.mouseCursor`.
174///
175/// ## Related classes
176///
177/// [`MouseCursorSession`] represents the duration when a pointing device
178/// displays a cursor, and defines the states and behaviors of the cursor.
179///
180/// [`MouseCursorManager`] is a mixin that manages the states of mouse cursors,
181/// such as `MouseTracker`.
182///
183/// Values are shared as [`MouseCursorRef`]. Dart's `MouseCursor.defer` and
184/// `MouseCursor.uncontrolled` are `<dyn MouseCursor>::defer()` and
185/// `<dyn MouseCursor>::uncontrolled()`.
186pub trait MouseCursor: fmt::Debug {
187    /// Associate a pointing device to this cursor.
188    ///
189    /// A mouse cursor class usually has a corresponding [`MouseCursorSession`]
190    /// class, and instantiates such class in this method.
191    ///
192    /// This method is called each time a pointing device starts displaying this
193    /// cursor. A given cursor can be displayed by multiple devices at the same
194    /// time, in which case this method will be called separately for each device.
195    fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession>;
196
197    /// A very short description of the mouse cursor.
198    ///
199    /// The `debug_description` should be a few words that can describe this cursor
200    /// to make debug information more readable. It is returned as the `Debug`
201    /// output when the diagnostic level is at or above info.
202    fn debug_description(&self) -> String;
203
204    /// Downcast support for Dart's `==` between cursor classes.
205    fn as_any(&self) -> &dyn Any;
206
207    /// Dart's `==`. Identity unless a class overrides it, as [`SystemMouseCursor`] does.
208    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
209        std::ptr::addr_eq(self as *const Self, other as *const dyn MouseCursor)
210    }
211
212    /// Whether this is `MouseCursor.defer`.
213    fn is_defer(&self) -> bool {
214        self.as_any().is::<DeferringMouseCursor>()
215    }
216}
217
218impl dyn MouseCursor {
219    /// A special class that indicates that the region with this cursor defers the
220    /// choice of cursor to the next region behind it.
221    ///
222    /// When an event occurs, `MouseTracker` will update each pointer's cursor by
223    /// finding the list of regions that contain the pointer's location, from front
224    /// to back in hit-test order. The pointer's cursor will be the first cursor
225    /// that is not deferred.
226    pub fn defer() -> MouseCursorRef {
227        Rc::new(DeferringMouseCursor)
228    }
229
230    /// A special value that doesn't change cursor by itself, but make a region
231    /// that blocks other regions behind it from changing the cursor.
232    ///
233    /// When a pointer enters a region with a cursor of `uncontrolled`, the pointer
234    /// retains its previous cursor and keeps so until it moves out of the region.
235    /// Technically, this region absorb the mouse cursor hit test without changing
236    /// the pointer's cursor.
237    ///
238    /// This is useful in a region that displays a platform view, which let the
239    /// operating system handle pointer events and change cursors accordingly. To
240    /// achieve this, the region's cursor must not be any Flutter cursor, since
241    /// that might overwrite the system request upon pointer entering; the cursor
242    /// must not be `None` either, since that allows the widgets behind the region to
243    /// change cursors.
244    pub fn uncontrolled() -> MouseCursorRef {
245        Rc::new(NoopMouseCursor)
246    }
247}
248
249impl PartialEq for dyn MouseCursor {
250    fn eq(&self, other: &dyn MouseCursor) -> bool {
251        self.eq_cursor(other)
252    }
253}
254
255/// The cursor behind `MouseCursor.defer`. Every instance is equal.
256#[derive(Debug)]
257pub struct DeferringMouseCursor;
258
259impl MouseCursor for DeferringMouseCursor {
260    fn create_session(&self, _device: i64) -> Box<dyn MouseCursorSession> {
261        panic!("DeferringMouseCursor can not create a session");
262    }
263
264    fn debug_description(&self) -> String {
265        "defer".to_owned()
266    }
267
268    fn as_any(&self) -> &dyn Any {
269        self
270    }
271
272    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
273        other.is_defer()
274    }
275}
276
277/// Returns the first cursor from the given cursors that is not a
278/// [`DeferringMouseCursor`], or `None` if none is found.
279fn first_non_deferred(cursors: impl IntoIterator<Item = MouseCursorRef>) -> Option<MouseCursorRef> {
280    cursors.into_iter().find(|cursor| !cursor.is_defer())
281}
282
283struct NoopMouseCursorSession {
284    device: i64,
285}
286
287impl MouseCursorSession for NoopMouseCursorSession {
288    fn cursor(&self) -> MouseCursorRef {
289        <dyn MouseCursor>::uncontrolled()
290    }
291
292    fn device(&self) -> i64 {
293        self.device
294    }
295
296    fn activate(&mut self, _platform: &dyn Platform, _view: ViewId) {
297        // Nothing.
298    }
299
300    fn dispose(&mut self) {
301        // Nothing.
302    }
303}
304
305/// The cursor behind `MouseCursor.uncontrolled`. Every instance is equal.
306#[derive(Debug)]
307pub struct NoopMouseCursor;
308
309impl MouseCursor for NoopMouseCursor {
310    fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession> {
311        Box::new(NoopMouseCursorSession { device })
312    }
313
314    fn debug_description(&self) -> String {
315        "uncontrolled".to_owned()
316    }
317
318    fn as_any(&self) -> &dyn Any {
319        self
320    }
321
322    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
323        other.as_any().is::<NoopMouseCursor>()
324    }
325}
326
327struct SystemMouseCursorSession {
328    cursor: SystemMouseCursor,
329    device: i64,
330}
331
332impl MouseCursorSession for SystemMouseCursorSession {
333    fn cursor(&self) -> MouseCursorRef {
334        Rc::new(self.cursor)
335    }
336
337    fn device(&self) -> i64 {
338        self.device
339    }
340
341    fn activate(&mut self, platform: &dyn Platform, view: ViewId) {
342        if let Some(view) = platform.view(view) {
343            view.host()
344                .activate_system_cursor(self.device, self.cursor.kind());
345        }
346    }
347
348    fn dispose(&mut self) {
349        // Nothing.
350    }
351}
352
353/// A mouse cursor that is natively supported on the platform that the
354/// application is running on.
355///
356/// System cursors can be used without external resources, and their appearances
357/// match the experience of native apps. Examples of system cursors are a
358/// pointing arrow, a pointing hand, a double arrow for resizing, or a text
359/// I-beam, etc.
360///
361/// An instance of [`SystemMouseCursor`] refers to one cursor from each platform
362/// that represents the same concept, such as being text, being clickable, or
363/// being a forbidden operation. Since the set of system cursors supported by each
364/// platform varies, multiple instances can correspond to the same system cursor.
365///
366/// Each cursor is noted with its corresponding native cursors on each platform:
367///
368///  * Android: API name in Java
369///  * Web: CSS cursor
370///  * Windows: Win32 API
371///  * Linux: GDK, `gdk_cursor_new_from_name`
372///  * macOS: API name in ObjectiveC
373///
374/// If the platform that the application is running on is not listed for a
375/// cursor, using this cursor falls back to [`SystemMouseCursors::BASIC`].
376///
377/// [`SystemMouseCursors`] enumerates the complete set of system cursors supported
378/// by Flutter, which are hard-coded in the engine. Therefore, manually
379/// instantiating this class is not supported.
380#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
381pub struct SystemMouseCursor {
382    kind: SystemMouseCursorKind,
383}
384
385impl SystemMouseCursor {
386    const fn new(kind: SystemMouseCursorKind) -> SystemMouseCursor {
387        SystemMouseCursor { kind }
388    }
389
390    /// The kind of the cursor.
391    ///
392    /// The interpretation of `kind` is platform-dependent.
393    pub fn kind(&self) -> SystemMouseCursorKind {
394        self.kind
395    }
396}
397
398impl MouseCursor for SystemMouseCursor {
399    fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession> {
400        Box::new(SystemMouseCursorSession {
401            cursor: *self,
402            device,
403        })
404    }
405
406    fn debug_description(&self) -> String {
407        format!("SystemMouseCursor({})", describe_enum(&self.kind))
408    }
409
410    fn as_any(&self) -> &dyn Any {
411        self
412    }
413
414    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
415        other
416            .as_any()
417            .downcast_ref::<SystemMouseCursor>()
418            .is_some_and(|other| other.kind == self.kind)
419    }
420}
421
422impl From<SystemMouseCursor> for MouseCursorRef {
423    fn from(cursor: SystemMouseCursor) -> MouseCursorRef {
424        Rc::new(cursor)
425    }
426}
427
428/// A collection of system [`MouseCursor`]s.
429///
430/// System cursors are standard mouse cursors that are provided by the current
431/// platform. They don't require external resources.
432///
433/// [`SystemMouseCursors`] is a superset of the system cursors of every platform
434/// that Flutter supports, therefore some of these objects might map to the same
435/// result, or fallback to the [`BASIC`](Self::BASIC) arrow. This mapping is defined
436/// by the Flutter engine.
437///
438/// The cursors should be named based on the cursors' use cases instead of their
439/// appearance, because different platforms might (although not commonly) use
440/// different shapes for the same use case.
441pub struct SystemMouseCursors;
442
443impl SystemMouseCursors {
444    /// Hide the cursor.
445    ///
446    /// Any cursor other than [`NONE`](Self::NONE) or `MouseCursor.uncontrolled`
447    /// unhides the cursor.
448    pub const NONE: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::None);
449
450    /// The platform-dependent basic cursor.
451    ///
452    /// Typically the shape of an arrow.
453    pub const BASIC: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Basic);
454
455    /// A cursor that emphasizes an element being clickable, such as a hyperlink.
456    ///
457    /// Typically the shape of a pointing hand.
458    pub const CLICK: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Click);
459
460    /// A cursor indicating an operation that will not be carried out.
461    ///
462    /// Typically the shape of a circle with a diagonal line. May fall back to
463    /// [`NO_DROP`](Self::NO_DROP).
464    pub const FORBIDDEN: SystemMouseCursor =
465        SystemMouseCursor::new(SystemMouseCursorKind::Forbidden);
466
467    /// A cursor indicating the status that the program is busy and therefore
468    /// can not be interacted with.
469    ///
470    /// Typically the shape of an hourglass or a watch.
471    ///
472    /// This cursor is not available as a system cursor on macOS. Although macOS
473    /// displays a "spinning ball" cursor when busy, it's handled by the OS and not
474    /// exposed for applications to choose.
475    pub const WAIT: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Wait);
476
477    /// A cursor indicating the status that the program is busy but can still be
478    /// interacted with.
479    ///
480    /// Typically the shape of an arrow with an hourglass or a watch at the
481    /// corner. Does *not* fall back to [`WAIT`](Self::WAIT) if unavailable.
482    pub const PROGRESS: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Progress);
483
484    /// A cursor indicating somewhere the user can trigger a context menu.
485    ///
486    /// Typically the shape of an arrow with a small menu at the corner.
487    pub const CONTEXT_MENU: SystemMouseCursor =
488        SystemMouseCursor::new(SystemMouseCursorKind::ContextMenu);
489
490    /// A cursor indicating help information.
491    ///
492    /// Typically the shape of a question mark, or an arrow therewith.
493    pub const HELP: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Help);
494
495    /// A cursor indicating selectable text.
496    ///
497    /// Typically the shape of a capital I.
498    pub const TEXT: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Text);
499
500    /// A cursor indicating selectable vertical text.
501    ///
502    /// Typically the shape of a capital I rotated to be horizontal. May fall
503    /// back to [`TEXT`](Self::TEXT).
504    pub const VERTICAL_TEXT: SystemMouseCursor =
505        SystemMouseCursor::new(SystemMouseCursorKind::VerticalText);
506
507    /// A cursor indicating selectable table cells.
508    ///
509    /// Typically the shape of a hollow plus sign.
510    pub const CELL: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Cell);
511
512    /// A cursor indicating precise selection, such as selecting a pixel in a
513    /// bitmap.
514    ///
515    /// Typically the shape of a crosshair.
516    pub const PRECISE: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Precise);
517
518    /// A cursor indicating moving something.
519    ///
520    /// Typically the shape of four-way arrow. May fall back to
521    /// [`ALL_SCROLL`](Self::ALL_SCROLL).
522    pub const MOVE: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Move);
523
524    /// A cursor indicating something that can be dragged.
525    ///
526    /// Typically the shape of an open hand.
527    pub const GRAB: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Grab);
528
529    /// A cursor indicating something that is being dragged.
530    ///
531    /// Typically the shape of a closed hand.
532    pub const GRABBING: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Grabbing);
533
534    /// A cursor indicating somewhere that the current item may not be dropped.
535    ///
536    /// Typically the shape of a hand with a [`FORBIDDEN`](Self::FORBIDDEN) sign at
537    /// the corner. May fall back to [`FORBIDDEN`](Self::FORBIDDEN).
538    pub const NO_DROP: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::NoDrop);
539
540    /// A cursor indicating that the current operation will create an alias of, or
541    /// a shortcut of the item.
542    ///
543    /// Typically the shape of an arrow with a shortcut icon at the corner.
544    pub const ALIAS: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Alias);
545
546    /// A cursor indicating that the current operation will copy the item.
547    ///
548    /// Typically the shape of an arrow with a boxed plus sign at the corner.
549    pub const COPY: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::Copy);
550
551    /// A cursor indicating that the current operation will result in the
552    /// disappearance of the item.
553    ///
554    /// Typically the shape of an arrow with a cloud of smoke at the corner.
555    pub const DISAPPEARING: SystemMouseCursor =
556        SystemMouseCursor::new(SystemMouseCursorKind::Disappearing);
557
558    /// A cursor indicating scrolling in any direction.
559    ///
560    /// Typically the shape of a dot surrounded by 4 arrows.
561    pub const ALL_SCROLL: SystemMouseCursor =
562        SystemMouseCursor::new(SystemMouseCursorKind::AllScroll);
563
564    /// A cursor indicating resizing an object bidirectionally from its left or
565    /// right edge.
566    ///
567    /// Typically the shape of a bidirectional arrow pointing left and right.
568    pub const RESIZE_LEFT_RIGHT: SystemMouseCursor =
569        SystemMouseCursor::new(SystemMouseCursorKind::ResizeLeftRight);
570
571    /// A cursor indicating resizing an object bidirectionally from its top or
572    /// bottom edge.
573    ///
574    /// Typically the shape of a bidirectional arrow pointing up and down.
575    pub const RESIZE_UP_DOWN: SystemMouseCursor =
576        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUpDown);
577
578    /// A cursor indicating resizing an object bidirectionally from its top left or
579    /// bottom right corner.
580    ///
581    /// Typically the shape of a bidirectional arrow pointing upper left and lower
582    /// right.
583    pub const RESIZE_UP_LEFT_DOWN_RIGHT: SystemMouseCursor =
584        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUpLeftDownRight);
585
586    /// A cursor indicating resizing an object bidirectionally from its top right or
587    /// bottom left corner.
588    ///
589    /// Typically the shape of a bidirectional arrow pointing upper right and lower
590    /// left.
591    pub const RESIZE_UP_RIGHT_DOWN_LEFT: SystemMouseCursor =
592        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUpRightDownLeft);
593
594    /// A cursor indicating resizing an object from its top edge.
595    ///
596    /// Typically the shape of an arrow pointing up. May fallback to
597    /// [`RESIZE_UP_DOWN`](Self::RESIZE_UP_DOWN).
598    pub const RESIZE_UP: SystemMouseCursor =
599        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUp);
600
601    /// A cursor indicating resizing an object from its bottom edge.
602    ///
603    /// Typically the shape of an arrow pointing down. May fallback to
604    /// [`RESIZE_UP_DOWN`](Self::RESIZE_UP_DOWN).
605    pub const RESIZE_DOWN: SystemMouseCursor =
606        SystemMouseCursor::new(SystemMouseCursorKind::ResizeDown);
607
608    /// A cursor indicating resizing an object from its left edge.
609    ///
610    /// Typically the shape of an arrow pointing left. May fallback to
611    /// [`RESIZE_LEFT_RIGHT`](Self::RESIZE_LEFT_RIGHT).
612    pub const RESIZE_LEFT: SystemMouseCursor =
613        SystemMouseCursor::new(SystemMouseCursorKind::ResizeLeft);
614
615    /// A cursor indicating resizing an object from its right edge.
616    ///
617    /// Typically the shape of an arrow pointing right. May fallback to
618    /// [`RESIZE_LEFT_RIGHT`](Self::RESIZE_LEFT_RIGHT).
619    pub const RESIZE_RIGHT: SystemMouseCursor =
620        SystemMouseCursor::new(SystemMouseCursorKind::ResizeRight);
621
622    /// A cursor indicating resizing an object from its top-left corner.
623    ///
624    /// Typically the shape of an arrow pointing upper left. May fallback to
625    /// [`RESIZE_UP_LEFT_DOWN_RIGHT`](Self::RESIZE_UP_LEFT_DOWN_RIGHT).
626    pub const RESIZE_UP_LEFT: SystemMouseCursor =
627        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUpLeft);
628
629    /// A cursor indicating resizing an object from its top-right corner.
630    ///
631    /// Typically the shape of an arrow pointing upper right. May fallback to
632    /// [`RESIZE_UP_RIGHT_DOWN_LEFT`](Self::RESIZE_UP_RIGHT_DOWN_LEFT).
633    pub const RESIZE_UP_RIGHT: SystemMouseCursor =
634        SystemMouseCursor::new(SystemMouseCursorKind::ResizeUpRight);
635
636    /// A cursor indicating resizing an object from its bottom-left corner.
637    ///
638    /// Typically the shape of an arrow pointing lower left. May fallback to
639    /// [`RESIZE_UP_RIGHT_DOWN_LEFT`](Self::RESIZE_UP_RIGHT_DOWN_LEFT).
640    pub const RESIZE_DOWN_LEFT: SystemMouseCursor =
641        SystemMouseCursor::new(SystemMouseCursorKind::ResizeDownLeft);
642
643    /// A cursor indicating resizing an object from its bottom-right corner.
644    ///
645    /// Typically the shape of an arrow pointing lower right. May fallback to
646    /// [`RESIZE_UP_LEFT_DOWN_RIGHT`](Self::RESIZE_UP_LEFT_DOWN_RIGHT).
647    pub const RESIZE_DOWN_RIGHT: SystemMouseCursor =
648        SystemMouseCursor::new(SystemMouseCursorKind::ResizeDownRight);
649
650    /// A cursor indicating resizing a column, or an item horizontally.
651    ///
652    /// Typically the shape of arrows pointing left and right with a vertical bar
653    /// separating them. May fallback to [`RESIZE_LEFT_RIGHT`](Self::RESIZE_LEFT_RIGHT).
654    pub const RESIZE_COLUMN: SystemMouseCursor =
655        SystemMouseCursor::new(SystemMouseCursorKind::ResizeColumn);
656
657    /// A cursor indicating resizing a row, or an item vertically.
658    ///
659    /// Typically the shape of arrows pointing up and down with a horizontal bar
660    /// separating them. May fallback to [`RESIZE_UP_DOWN`](Self::RESIZE_UP_DOWN).
661    pub const RESIZE_ROW: SystemMouseCursor =
662        SystemMouseCursor::new(SystemMouseCursorKind::ResizeRow);
663
664    /// A cursor indicating zooming in.
665    ///
666    /// Typically a magnifying glass with a plus sign.
667    pub const ZOOM_IN: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::ZoomIn);
668
669    /// A cursor indicating zooming out.
670    ///
671    /// Typically a magnifying glass with a minus sign.
672    pub const ZOOM_OUT: SystemMouseCursor = SystemMouseCursor::new(SystemMouseCursorKind::ZoomOut);
673}
674
675#[cfg(test)]
676mod tests {
677    use waft_embedder::ViewRef;
678    use waft_gestures::{PointerHoverEvent, PointerRemovedEvent};
679    use waft_test::{TestPlatform, TestView};
680
681    use super::*;
682
683    const VIEW: ViewId = ViewId(3);
684
685    /// A platform with view [`VIEW`], whose host records the cursors it is asked for, and the view.
686    fn recording_platform() -> (TestPlatform, Rc<TestView>) {
687        let view = Rc::new(TestView::new(800.0, 600.0).with_id(VIEW));
688        let platform = TestPlatform::new().with_view(Rc::clone(&view) as ViewRef);
689        (platform, view)
690    }
691
692    fn hover() -> PointerEvent {
693        PointerEvent::Hover(PointerHoverEvent::default())
694    }
695
696    #[test]
697    fn system_cursors_compare_by_kind_and_special_cursors_by_class() {
698        let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
699        let click_again: MouseCursorRef = SystemMouseCursors::CLICK.into();
700        let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
701        assert!(*click == *click_again);
702        assert!(*click != *basic);
703        assert!(*<dyn MouseCursor>::defer() == *<dyn MouseCursor>::defer());
704        assert!(*<dyn MouseCursor>::uncontrolled() == *<dyn MouseCursor>::uncontrolled());
705        assert!(*<dyn MouseCursor>::defer() != *<dyn MouseCursor>::uncontrolled());
706        assert!(*<dyn MouseCursor>::defer() != *click);
707        assert_eq!(click.debug_description(), "SystemMouseCursor(click)");
708        assert_eq!(<dyn MouseCursor>::defer().debug_description(), "defer");
709    }
710
711    #[test]
712    fn manager_activates_the_first_non_deferred_candidate() {
713        let (platform, view) = recording_platform();
714        let mut manager = MouseCursorManager::new(SystemMouseCursors::BASIC.into());
715        manager.handle_device_cursor_update(
716            &platform,
717            VIEW,
718            1,
719            Some(&hover()),
720            [<dyn MouseCursor>::defer(), SystemMouseCursors::TEXT.into()],
721        );
722        assert_eq!(
723            view.test_host().cursors(),
724            [(1, SystemMouseCursorKind::Text)],
725            "the deferring region lets the text region behind it decide"
726        );
727        let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
728        assert!(*manager.debug_device_active_cursor(1).unwrap() == *text);
729    }
730
731    #[test]
732    fn manager_falls_back_when_every_candidate_defers() {
733        let (platform, view) = recording_platform();
734        let mut manager = MouseCursorManager::new(SystemMouseCursors::BASIC.into());
735        manager.handle_device_cursor_update(
736            &platform,
737            VIEW,
738            1,
739            Some(&hover()),
740            [<dyn MouseCursor>::defer()],
741        );
742        assert_eq!(
743            view.test_host().cursors(),
744            [(1, SystemMouseCursorKind::Basic)]
745        );
746    }
747
748    #[test]
749    fn manager_does_not_reactivate_the_same_cursor() {
750        let (platform, view) = recording_platform();
751        let mut manager = MouseCursorManager::new(SystemMouseCursors::BASIC.into());
752        manager.handle_device_cursor_update(
753            &platform,
754            VIEW,
755            1,
756            Some(&hover()),
757            [SystemMouseCursors::CLICK.into()],
758        );
759        manager.handle_device_cursor_update(
760            &platform,
761            VIEW,
762            1,
763            None,
764            [SystemMouseCursors::CLICK.into()],
765        );
766        assert_eq!(view.test_host().cursors().len(), 1);
767
768        manager.handle_device_cursor_update(
769            &platform,
770            VIEW,
771            1,
772            None,
773            [SystemMouseCursors::GRAB.into()],
774        );
775        assert_eq!(view.test_host().cursors().len(), 2);
776    }
777
778    #[test]
779    fn an_uncontrolled_region_keeps_the_previous_system_request() {
780        let (platform, view) = recording_platform();
781        let mut manager = MouseCursorManager::new(SystemMouseCursors::BASIC.into());
782        manager.handle_device_cursor_update(
783            &platform,
784            VIEW,
785            1,
786            Some(&hover()),
787            [SystemMouseCursors::CLICK.into()],
788        );
789        manager.handle_device_cursor_update(
790            &platform,
791            VIEW,
792            1,
793            None,
794            [<dyn MouseCursor>::uncontrolled()],
795        );
796        assert_eq!(
797            view.test_host().cursors(),
798            [(1, SystemMouseCursorKind::Click)],
799            "the no-op session makes no request; the host keeps whatever it shows"
800        );
801        assert!(
802            *manager.debug_device_active_cursor(1).unwrap() == *<dyn MouseCursor>::uncontrolled()
803        );
804    }
805
806    #[test]
807    fn a_removed_device_forgets_its_session() {
808        let (platform, _view) = recording_platform();
809        let mut manager = MouseCursorManager::new(SystemMouseCursors::BASIC.into());
810        manager.handle_device_cursor_update(
811            &platform,
812            VIEW,
813            1,
814            Some(&hover()),
815            [SystemMouseCursors::CLICK.into()],
816        );
817        let removed = PointerEvent::Removed(PointerRemovedEvent::default());
818        manager.handle_device_cursor_update(&platform, VIEW, 1, Some(&removed), []);
819        assert!(manager.debug_device_active_cursor(1).is_none());
820    }
821}