kas-core 0.17.0

KAS GUI / core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Event handling: mouse and touch events

mod mouse;
mod touch;
pub(crate) mod velocity;

#[allow(unused)] use super::{Event, EventState}; // for doc-links
use super::{EventCx, IsUsed};
#[allow(unused)] use crate::Events; // for doc-links
use crate::Id;
use crate::event::{CursorIcon, MouseButton, Unused, Used};
use crate::geom::{Coord, DVec2, Offset, Vec2};
use cast::{Cast, CastApprox, Conv};
pub(crate) use mouse::Mouse;
pub(crate) use touch::Touch;
use winit::event::FingerId;

/// Controls the types of events delivered by [`PressStart::grab`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GrabMode {
    /// Deliver [`Event::PressEnd`] only for each grabbed press
    Click,
    /// Deliver [`Event::PressMove`] and [`Event::PressEnd`] for each grabbed press
    Grab,
    /// Deliver [`Event::Pan`] events
    ///
    /// Scaling and rotation are optional.
    Pan { scale: bool, rotate: bool },
}

impl GrabMode {
    /// [`GrabMode::Pan`] without scaling or rotation
    pub const PAN_NONE: GrabMode = GrabMode::Pan {
        scale: false,
        rotate: false,
    };
    /// [`GrabMode::Pan`] with scaling only
    pub const PAN_SCALE: GrabMode = GrabMode::Pan {
        scale: true,
        rotate: false,
    };
    /// [`GrabMode::Pan`] with rotation only
    pub const PAN_ROTATE: GrabMode = GrabMode::Pan {
        scale: false,
        rotate: true,
    };
    /// [`GrabMode::Pan`] with scaling and rotation
    pub const PAN_FULL: GrabMode = GrabMode::Pan {
        scale: true,
        rotate: true,
    };

    /// True for "pan" variants
    #[inline]
    pub fn is_pan(self) -> bool {
        matches!(self, GrabMode::Pan { .. })
    }
}

/// Source of a [`Press`] event
///
/// This identifies the source of a click, touch or pointer motion. It
/// identifies which mouse button is pressed (if any) and whether this is a
/// double-click (see [`Self::repetitions`]).
///
/// This may be used to track a click/touch, but note that identifiers may be
/// re-used after the event completes, thus an [`Event::PressStart`] with
/// `PressSource` equal to a prior instance does not indicate that the same
/// finger / mouse was used.
/// Further note: identifying multiple mice is not currently supported.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PressSource(u64);

impl PressSource {
    const FLAG_TOUCH: u64 = 1 << 63;

    /// Construct a mouse source
    pub(crate) fn mouse(button: Option<MouseButton>, repetitions: u32) -> Self {
        let r = (repetitions as u64) << 32;
        debug_assert!(r & Self::FLAG_TOUCH == 0);
        // Note: MouseButton::try_from_u8 returns None on u8::MAX
        let b = button.map(|b| b as u8).unwrap_or(u8::MAX);
        Self(r | b as u64)
    }

    /// Construct a touch source
    pub(crate) fn touch(finger_id: FingerId) -> Self {
        let id = u64::conv(finger_id.into_raw());
        // Investigation shows that almost all sources use a 32-bit identifier.
        // The only exceptional winit backend is iOS, which uses a pointer.
        assert!(id & Self::FLAG_TOUCH == 0);
        Self(Self::FLAG_TOUCH | id)
    }

    /// Returns true if this represents a mouse event
    #[inline]
    pub fn is_mouse(self) -> bool {
        self.0 & Self::FLAG_TOUCH == 0
    }

    /// Returns true if this represents a touch event
    #[inline]
    pub fn is_touch(self) -> bool {
        self.0 & Self::FLAG_TOUCH != 0
    }

    /// Returns the finger identifier if this represents a touch event
    fn finger_id(self) -> Option<FingerId> {
        if self.is_touch() {
            let id = self.0 & !Self::FLAG_TOUCH;
            Some(FingerId::from_raw(id.cast()))
        } else {
            None
        }
    }

    /// Identify the mouse button used
    ///
    /// This returns `Some(button)` for mouse events with a button. It returns
    /// `None` for touch events and mouse events without a button (e.g. motion).
    pub fn mouse_button(self) -> Option<MouseButton> {
        if self.is_mouse() {
            let b = self.0 as u8;
            MouseButton::try_from_u8(b)
        } else {
            None
        }
    }

    /// Returns true if this represents the left mouse button or a touch event
    #[inline]
    pub fn is_primary(self) -> bool {
        self.is_touch() || self.mouse_button() == Some(MouseButton::Left)
    }

    /// Returns true if this represents the right mouse button
    #[inline]
    pub fn is_secondary(self) -> bool {
        self.mouse_button() == Some(MouseButton::Right)
    }

    /// Returns true if this represents the middle mouse button
    #[inline]
    pub fn is_tertiary(self) -> bool {
        self.mouse_button() == Some(MouseButton::Middle)
    }

    /// The `repetitions` value
    ///
    /// This is 1 for a single-click and all touch events, 2 for a double-click,
    /// 3 for a triple-click, etc. For [`Event::PointerMove`] without a grab this is 0.
    #[inline]
    pub fn repetitions(self) -> u32 {
        if self.is_mouse() {
            // Top 32 bits is repetitions
            (self.0 >> 32) as u32
        } else {
            // Touch events do not support repetitions.
            1
        }
    }
}

/// Details of press start events
///
/// This type dereferences to [`PressSource`].
#[crate::autoimpl(Deref using self.source)]
#[derive(Clone, Debug, PartialEq)]
pub struct PressStart {
    /// Source of the press
    pub source: PressSource,
    /// Identifier of the widget currently under the press
    pub id: Option<Id>,
    /// Current coordinate
    position: DVec2,
}

impl std::ops::AddAssign<Offset> for PressStart {
    #[inline]
    fn add_assign(&mut self, offset: Offset) {
        self.position += DVec2::conv(offset);
    }
}

impl PressStart {
    /// Get the current press coordinate
    #[inline]
    pub fn coord(&self) -> Coord {
        self.position.cast_approx()
    }

    /// Grab pan/move/press-end events for widget `id`
    ///
    /// There are three types of grab ([`GrabMode`]):
    ///
    /// -   `Click`: send the corresponding [`Event::PressEnd`] only
    /// -   `Grab` (the default): send [`Event::PressMove`] and [`Event::PressEnd`]
    /// -   Pan modes: send [`Event::Pan`] on motion.
    ///     Note: this is most useful when grabbing multiple touch events.
    ///
    /// Only a single mouse grab is allowed at any one time; requesting a
    /// second will cancel the first (sending [`Event::PressEnd`] with
    /// `success: false`).
    ///
    /// [`EventState::is_depressed`] will return true for the grabbing widget.
    /// Call [`EventCx::set_grab_depress`] on `PressMove` to update the
    /// grab's depress target. (This is done automatically for
    /// [`GrabMode::Click`], and ends automatically when the grab ends.)
    ///
    /// This method uses the builder pattern. On completion, [`Used`]
    /// is returned. It is expected that the requested press/pan events are all
    /// "used" ([`Used`]).
    #[inline]
    pub fn grab(&self, id: Id, mode: GrabMode) -> GrabBuilder {
        GrabBuilder {
            id,
            source: self.source,
            position: self.position,
            mode,
            icon: None,
        }
    }

    /// Convenience wrapper for [`Self::grab`] using [`GrabMode::Click`]
    #[inline]
    pub fn grab_click(&self, id: Id) -> GrabBuilder {
        self.grab(id, GrabMode::Click)
    }

    /// Convenience wrapper for [`Self::grab`] using [`GrabMode::Grab`]
    #[inline]
    pub fn grab_move(&self, id: Id) -> GrabBuilder {
        self.grab(id, GrabMode::Grab)
    }
}

/// Details of press events
///
/// This type dereferences to [`PressSource`].
#[crate::autoimpl(Deref using self.source)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Press {
    /// Source of the press
    pub source: PressSource,
    /// Identifier of the widget currently under the press
    pub id: Option<Id>,
    /// Current coordinate
    pub coord: Coord,
}

/// Bulider pattern (see [`PressStart::grab`])
///
/// Conclude by calling [`Self::complete`].
#[must_use]
pub struct GrabBuilder {
    id: Id,
    source: PressSource,
    position: DVec2,
    mode: GrabMode,
    icon: Option<CursorIcon>,
}

impl GrabBuilder {
    /// Set pointer icon (default: do not set)
    #[inline]
    pub fn with_icon(self, icon: CursorIcon) -> Self {
        self.with_opt_icon(Some(icon))
    }

    /// Optionally set pointer icon (default: do not set)
    #[inline]
    pub fn with_opt_icon(mut self, icon: Option<CursorIcon>) -> Self {
        self.icon = icon;
        self
    }

    /// Complete the grab, providing the [`EventCx`]
    ///
    /// In case of an existing grab for the same [`source`](Press::source),
    /// - If the [`Id`] differs this fails (returns [`Unused`])
    /// - If the [`MouseButton`] differs this fails (technically this is a
    ///   different `source`, but simultaneous grabs of multiple mouse buttons
    ///   are not supported).
    /// - If one grab is a [pan](GrabMode::is_pan) and the other is not, this fails
    /// - [`GrabMode::Click`] may be upgraded to [`GrabMode::Grab`]
    /// - Changing from one pan mode to another is an error
    /// - Mouse button repetitions may be increased; decreasing is an error
    /// - A [`CursorIcon`] may be set
    /// - The depress target is re-set to the grabbing widget
    ///
    /// Note: error conditions are only checked in debug builds. These cases
    /// may need revision.
    pub fn complete(self, cx: &mut EventCx) -> IsUsed {
        let GrabBuilder {
            id,
            source,
            position,
            mode,
            icon,
        } = self;
        log::trace!(target: "kas_core::event", "grab_press: start_id={id}, source={source:?}");
        let success = if let Some(button) = source.mouse_button() {
            cx.mouse.start_grab(
                button,
                source.repetitions(),
                id.clone(),
                position,
                mode,
                icon.unwrap_or_default(),
            )
        } else if let Some(finger_id) = source.finger_id() {
            cx.touch.start_grab(finger_id, id.clone(), position, mode)
        } else {
            false
        };

        if success {
            cx.redraw();
            Used
        } else {
            Unused
        }
    }
}

/// Mouse and touch methods
impl EventState {
    /// Check whether the given widget is visually depressed
    pub fn is_depressed(&self, w_id: &Id) -> bool {
        for (_, id) in &self.key_depress {
            if *id == w_id {
                return true;
            }
        }
        if self
            .mouse
            .grab
            .as_ref()
            .map(|grab| *w_id == grab.depress)
            .unwrap_or(false)
        {
            return true;
        }
        for grab in self.touch.touch_grab.iter() {
            if *w_id == grab.depress {
                return true;
            }
        }
        for popup in &self.popups {
            if *w_id == popup.desc.parent {
                return true;
            }
        }
        false
    }

    /// Get whether the widget is under the mouse pointer
    #[inline]
    pub fn is_under_mouse(&self, w_id: &Id) -> bool {
        *w_id == self.mouse.over
            && self
                .mouse
                .grab
                .as_ref()
                .is_none_or(|grab| grab.start_id == w_id)
    }

    /// Returns true if there is a mouse or touch grab on `id` or any descendant of `id`
    pub fn any_grab_on(&self, id: &Id) -> bool {
        if self
            .mouse
            .grab
            .as_ref()
            .map(|grab| grab.start_id == id)
            .unwrap_or(false)
        {
            return true;
        }
        self.touch.touch_grab.iter().any(|grab| grab.start_id == id)
    }

    /// Get velocity of the mouse pointer or a touch
    ///
    /// The velocity is calculated at the time this method is called using
    /// existing samples of motion.
    ///
    /// Where the `source` is a mouse this always succeeds.
    /// For touch events this requires an active grab and is not
    /// guaranteed to succeed; currently only a limited number of presses with
    /// mode [`GrabMode::Grab`] are tracked for velocity.
    pub fn press_velocity(&self, source: PressSource) -> Option<Vec2> {
        let evc = self.config().event();
        if source.is_mouse() {
            Some(self.mouse.samples.velocity(evc.kinetic_timeout()))
        } else if let Some(finger_id) = source.finger_id() {
            self.touch.velocity(finger_id, evc)
        } else {
            unreachable!()
        }
    }
}

impl<'a> EventCx<'a> {
    /// Set the pointer icon
    ///
    /// This is normally called from [`Events::handle_mouse_over`]. In other
    /// cases, calling this method may be ineffective. The icon is
    /// automatically "unset" when the widget is no longer under the mouse.
    ///
    /// See also [`EventCx::set_grab_icon`]: if a mouse grab
    /// ([`PressStart::grab`]) is active, its icon takes precedence.
    pub fn set_mouse_over_icon(&mut self, icon: CursorIcon) {
        // Note: this is acted on by EventState::update
        self.mouse.icon = icon;
    }

    /// Set a grab's depress target
    ///
    /// When a grab on mouse or touch input is in effect
    /// ([`PressStart::grab`]), the widget owning the grab may set itself
    /// or any other widget as *depressed* ("pushed down"). Each grab depresses
    /// at most one widget, thus setting a new depress target clears any
    /// existing target. Initially a grab depresses its owner.
    ///
    /// This effect is purely visual. A widget is depressed when one or more
    /// grabs targets the widget to depress, or when a keyboard binding is used
    /// to activate a widget (for the duration of the key-press).
    ///
    /// Assumption: this method will only be called by handlers of a grab (i.e.
    /// recipients of [`Event::PressStart`] after initiating a successful grab,
    /// [`Event::PressMove`] or [`Event::PressEnd`]).
    ///
    /// Queues a redraw and returns `true` if the depress target changes,
    /// otherwise returns `false`.
    pub fn set_grab_depress(&mut self, source: PressSource, target: Option<Id>) -> bool {
        let mut old = None;
        let mut redraw = false;
        if source.is_mouse() {
            if let Some(grab) = self.mouse.grab.as_mut() {
                redraw = grab.depress != target;
                old = grab.depress.take();
                grab.depress = target.clone();
            }
        } else if let Some(finger_id) = source.finger_id() {
            if let Some(grab) = self.touch.get_touch(finger_id) {
                redraw = grab.depress != target;
                old = grab.depress.take();
                grab.depress = target.clone();
            }
        } else {
            unreachable!()
        }

        if redraw {
            log::trace!(target: "kas_core::event", "set_grab_depress: target={target:?}");
            self.opt_redraw(old);
            self.opt_redraw(target);
        }
        redraw
    }

    /// Update the mouse pointer icon used during a grab
    ///
    /// This only succeeds if widget `id` has an active mouse-grab (see
    /// [`PressStart::grab`]). The icon will be reset when the mouse-grab
    /// ends.
    pub fn set_grab_icon(&mut self, id: &Id, icon: CursorIcon) {
        if let Some(grab) = self.mouse.grab.as_mut()
            && grab.start_id == *id
        {
            grab.icon = icon;
        }
    }
}