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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// 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: events

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::{EventCx, IsUsed, Unused, Used};
#[allow(unused)] use super::{EventState, GrabMode};
use super::{Key, KeyEvent, NamedKey, PhysicalKey, Press};
use crate::geom::{DVec2, Offset};
use crate::{dir::Direction, Id, WindowId};
#[allow(unused)] use crate::{Events, Popup};

/// Events addressed to a widget
///
/// Note that a few events are received by disabled widgets; see
/// [`Event::pass_when_disabled`].
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    /// Command input
    ///
    /// A generic "command". The source is often but not always a key press.
    /// In many cases (but not all) the target widget has navigation focus.
    ///
    /// A [`PhysicalKey`] is attached when the command is caused by a key press.
    /// The recipient may use this to call [`EventState::depress_with_key`].
    ///
    /// If a widget has keyboard input focus (see
    /// [`EventState::request_key_focus`]) it will instead receive
    /// [`Event::Key`] for key presses (but may still receive `Event::Command`
    /// from other sources).
    Command(Command, Option<PhysicalKey>),
    /// Keyboard input: `event, is_synthetic`
    ///
    /// This is only received by a widget with character focus (see
    /// [`EventState::request_key_focus`]).
    ///
    /// On some platforms, synthetic key events are generated when a window
    /// gains or loses focus with a key held (see documentation of
    /// [`winit::event::WindowEvent::KeyboardInput`]). This is indicated by the
    /// second parameter, `is_synthetic`. Unless you need to track key states
    /// it is advised only to match `Event::Key(event, false)`.
    ///
    /// Some key presses can be mapped to a [`Command`]. To do this (normally
    /// only when `event.state == ElementState::Pressed && !is_synthetic`), use
    /// `cx.config().shortcuts(|s| s.try_match(cx.modifiers(), &event.logical_key)`
    /// or (omitting shortcut matching) `Command::new(event.logical_key)`.
    /// Note that if the handler returns [`Unused`] the widget might
    /// then receive [`Event::Command`] for the same key press, but this is not
    /// guaranteed (behaviour may change in future versions).
    ///
    /// For standard text input, simply consume `event.text` when
    /// `event.state == ElementState::Pressed && !is_synthetic`.
    /// NOTE: unlike Winit, we force `text = None` for control chars and when
    /// <kbd>Ctrl</kbd>, <kbd>Alt</kbd> or <kbd>Super</kbd> modifier keys are
    /// pressed. This is subject to change.
    Key(KeyEvent, bool),
    /// A mouse or touchpad scroll event
    Scroll(ScrollDelta),
    /// A mouse or touch-screen move/zoom/rotate event
    ///
    /// This event is sent for certain types of grab ([`Press::grab`]),
    /// enabling two-finger scale/rotate gestures as well as translation.
    ///
    /// Mouse-grabs generate translation (`delta` component) only. Touch grabs
    /// optionally also generate rotation and scaling components, depending on
    /// the [`GrabMode`].
    ///
    /// In general, a point `p` on the screen should be transformed as follows:
    /// ```
    /// # use kas_core::cast::{Cast, CastFloat};
    /// # use kas_core::geom::{Coord, DVec2};
    /// # let (alpha, delta) = (DVec2::ZERO, DVec2::ZERO);
    /// let mut p = Coord::ZERO; // or whatever
    /// p = (alpha.complex_mul(p.cast()) + delta).cast_nearest();
    /// ```
    ///
    /// When it is known that there is no rotational component, one can use a
    /// simpler transformation: `alpha.0 * p + delta`. When there is also no
    /// scaling component, we just have a translation: `p + delta`.
    /// Note however that if events are generated with rotation and/or scaling
    /// components, these simplifications are invalid.
    ///
    /// Two such transforms may be combined as follows:
    /// ```
    /// # use kas_core::geom::DVec2;
    /// # let (alpha1, delta1) = (DVec2::ZERO, DVec2::ZERO);
    /// # let (alpha2, delta2) = (DVec2::ZERO, DVec2::ZERO);
    /// let alpha = alpha2.complex_mul(alpha1);
    /// let delta = alpha2.complex_mul(delta1) + delta2;
    /// ```
    /// If instead one uses a transform to map screen-space to world-space,
    /// this transform should be adjusted as follows:
    /// ```
    /// # use kas_core::geom::DVec2;
    /// # let (alpha, delta) = (DVec2::ZERO, DVec2::ZERO);
    /// # let (mut world_alpha, mut world_delta) = (DVec2::ZERO, DVec2::ZERO);
    /// world_alpha = world_alpha.complex_div(alpha.into());
    /// world_delta = world_delta - world_alpha.complex_mul(delta.into());
    /// ```
    ///
    /// Those familiar with complex numbers may recognise that
    /// `alpha = a * e^{i*t}` where `a` is the scale component and `t` is the
    /// angle of rotation. Calculate these components as follows:
    /// ```
    /// # use kas_core::geom::DVec2;
    /// # let alpha = DVec2::ZERO;
    /// let a = (alpha.0 * alpha.0 + alpha.1 * alpha.1).sqrt();
    /// let t = (alpha.1).atan2(alpha.0);
    /// ```
    Pan {
        /// Rotation and scale component
        alpha: DVec2,
        /// Translation component
        delta: DVec2,
    },
    /// Movement of mouse cursor without press
    ///
    /// This event is sent only when:
    ///
    /// 1.  No [`Press::grab`] is active
    /// 2.  A [`Popup`] is open
    ///
    /// The parent (or an ancestor) of a [`Popup`] should handle or explicitly
    /// ignore this event.
    CursorMove { press: Press },
    /// A mouse button was pressed or touch event started
    ///
    /// Call [`Press::grab`] in order to "grab" corresponding motion
    /// and release events.
    ///
    /// This event is sent in exactly two cases, in this order:
    ///
    /// 1.  When a [`Popup`] is open. A [`Popup`] will close itself if
    ///     `press.id` is not a descendant of itself, but will still return
    ///     [`Unused`]. The parent (or an ancestor) of the
    ///     [`Popup`] should handle this event.
    /// 2.  If a widget is found under the mouse when pressed or where a touch
    ///     event starts, this event is sent to the widget.
    ///
    /// If `start_id` is `None`, then no widget was found at the coordinate and
    /// the event will only be delivered to pop-up layer owners.
    PressStart { press: Press },
    /// Movement of mouse or a touch press
    ///
    /// This event is only sent when a ([`Press::grab`]) is active.
    /// Motion events for the grabbed mouse pointer or touched finger are sent.
    ///
    /// If `cur_id` is `None`, no widget was found at the coordinate (either
    /// outside the window or [`crate::Layout::find_id`] failed).
    PressMove { press: Press, delta: Offset },
    /// End of a click/touch press
    ///
    /// If `success`, this is a button-release or touch finish; otherwise this
    /// is a cancelled/interrupted grab. "Activation events" (e.g. clicking of a
    /// button or menu item) should only happen on `success`. "Movement events"
    /// such as panning, moving a slider or opening a menu should not be undone
    /// when cancelling: the panned item or slider should be released as is, or
    /// the menu should remain open.
    ///
    /// This event is only sent when a ([`Press::grab`]) is active.
    /// Release/cancel events for the same mouse button or touched finger are
    /// sent.
    ///
    /// If `cur_id` is `None`, no widget was found at the coordinate (either
    /// outside the window or [`crate::Layout::find_id`] failed).
    PressEnd { press: Press, success: bool },
    /// Update from a timer
    ///
    /// This event is received after requesting timed wake-up(s)
    /// (see [`EventState::request_timer`]).
    ///
    /// The `u64` payload is copied from [`EventState::request_timer`].
    Timer(u64),
    /// Notification that a popup has been closed
    ///
    /// This is sent to the popup when closed.
    /// Since popups may be removed directly by the [`EventCx`], the parent should
    /// clean up any associated state here.
    #[cfg_attr(not(feature = "internal_doc"), doc(hidden))]
    #[cfg_attr(doc_cfg, doc(cfg(internal_doc)))]
    PopupClosed(WindowId),
    /// Notification that a widget has gained navigation focus
    ///
    /// Navigation focus implies that the widget is highlighted and will be the
    /// primary target of [`Event::Command`], and is thus able to receive basic
    /// keyboard input (e.g. arrow keys). To receive full keyboard input
    /// ([`Event::Key`]), call [`EventState::request_key_focus`].
    ///
    /// With [`FocusSource::Pointer`] the widget should already have received
    /// [`Event::PressStart`].
    ///
    /// With [`FocusSource::Key`], [`EventCx::set_scroll`] is
    /// called automatically (to ensure that the widget is visible) and the
    /// response will be forced to [`Used`].
    NavFocus(FocusSource),
    /// Notification that a widget has lost navigation focus
    LostNavFocus,
    /// Notification that a widget has gained selection focus
    ///
    /// This focus must be requested by calling
    /// [`EventState::request_sel_focus`] or [`EventState::request_key_focus`].
    SelFocus(FocusSource),
    /// Notification that a widget has lost selection focus
    ///
    /// In the case the widget also had character focus, [`Event::LostKeyFocus`] is
    /// received first.
    LostSelFocus,
    /// Notification that a widget has gained keyboard input focus
    ///
    /// This focus must be requested by calling
    /// [`EventState::request_key_focus`].
    ///
    /// This is always preceeded by [`Event::SelFocus`] and is received prior to
    /// [`Event::Key`] events.
    KeyFocus,
    /// Notification that a widget has lost keyboard input focus
    LostKeyFocus,
    /// Notification that a widget gains or loses mouse hover
    ///
    /// The payload is `true` when focus is gained, `false` when lost.
    MouseHover(bool),
}

impl std::ops::Add<Offset> for Event {
    type Output = Self;

    #[inline]
    fn add(mut self, offset: Offset) -> Event {
        self += offset;
        self
    }
}

impl std::ops::AddAssign<Offset> for Event {
    fn add_assign(&mut self, offset: Offset) {
        match self {
            Event::CursorMove { ref mut press } => {
                press.coord += offset;
            }
            Event::PressStart { ref mut press, .. } => {
                press.coord += offset;
            }
            Event::PressMove { ref mut press, .. } => {
                press.coord += offset;
            }
            Event::PressEnd { ref mut press, .. } => {
                press.coord += offset;
            }
            _ => (),
        }
    }
}

impl Event {
    /// Call `f` on any "activation" event
    ///
    /// Activation is considered:
    ///
    /// -   Mouse click and release on the same widget
    /// -   Touchscreen press and release on the same widget
    /// -   `Event::Command(cmd, _)` where [`cmd.is_activate()`](Command::is_activate)
    ///
    /// The method calls [`EventState::depress_with_key`] on activation.
    pub fn on_activate<F: FnOnce(&mut EventCx) -> IsUsed>(
        self,
        cx: &mut EventCx,
        id: Id,
        f: F,
    ) -> IsUsed {
        match self {
            Event::Command(cmd, code) if cmd.is_activate() => {
                if let Some(code) = code {
                    cx.depress_with_key(id, code);
                }
                f(cx)
            }
            Event::PressStart { press, .. } if press.is_primary() => press.grab(id).with_cx(cx),
            Event::PressEnd { press, success } => {
                if success && id == press.id {
                    f(cx)
                } else {
                    Used
                }
            }
            _ => Unused,
        }
    }

    /// Pass to disabled widgets?
    ///
    /// Disabled status should disable input handling but not prevent other
    /// notifications.
    pub fn pass_when_disabled(&self) -> bool {
        use Event::*;
        match self {
            Command(_, _) => false,
            Key(_, _) | Scroll(_) | Pan { .. } => false,
            CursorMove { .. } | PressStart { .. } | PressMove { .. } | PressEnd { .. } => false,
            Timer(_) | PopupClosed(_) => true,
            NavFocus { .. } | SelFocus(_) | KeyFocus | MouseHover(_) => false,
            LostNavFocus | LostKeyFocus | LostSelFocus => true,
        }
    }

    /// Can the event be received by [`Events::handle_event`] during unwinding?
    ///
    /// Events which may be sent to the widget under the mouse or to the
    /// keyboard navigation target may be acted on by an ancestor if unused.
    /// Other events may not be; e.g. [`Event::PressMove`] and
    /// [`Event::PressEnd`] are only received by the widget requesting them
    /// while [`Event::LostKeyFocus`] (and similar events) are only sent to a
    /// specific widget.
    pub fn is_reusable(&self) -> bool {
        use Event::*;
        match self {
            Key(_, _) => false,
            Command(_, _) | Scroll(_) | Pan { .. } => true,
            CursorMove { .. } | PressStart { .. } => true,
            PressMove { .. } | PressEnd { .. } => false,
            Timer(_) | PopupClosed(_) => false,
            NavFocus { .. } | LostNavFocus => false,
            SelFocus(_) | LostSelFocus => false,
            KeyFocus | LostKeyFocus => false,
            MouseHover(_) => false,
        }
    }
}

/// Command input ([`Event::Command`])
///
/// `Command` events are mostly produced as a result of OS-specific keyboard
/// bindings; for example,  [`Command::Copy`] is produced by pressing
/// <kbd>Command+C</kbd> on MacOS or <kbd>Ctrl+C</kbd> on other platforms.
/// See [`crate::event::config::Shortcuts`] for more on these bindings.
///
/// A `Command` event does not necessarily come from keyboard input; for example
/// some menu widgets send [`Command::Activate`] to trigger an entry as a result
/// of mouse input.
///
/// *Most* `Command` entries represent an action (such as `Copy` or `FindNext`)
/// but some represent an important key whose action may be context-dependent
/// (e.g. `Escape`, `Space`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum Command {
    /// Escape key
    ///
    /// Each press of this key should somehow relax control. It is expected that
    /// widgets receiving this key repeatedly eventually (soon) have no more
    /// use for this themselves and return it via [`Unused`].
    ///
    /// This is in some cases remapped to [`Command::Deselect`].
    Escape,
    /// Programmatic activation
    ///
    /// A synthetic event to activate widgets. Consider matching
    /// [`Command::is_activate`] or using using [`Event::on_activate`]
    /// instead for generally applicable activation.
    Activate,
    /// Return / enter key
    ///
    /// This may insert a line-break or may activate something.
    Enter,
    /// Space bar key
    Space,
    /// Tab key
    ///
    /// This key is used to insert (horizontal) tabulators as well as to
    /// navigate focus (in reverse when combined with Shift).
    ///
    /// This is usually not sent to widgets but instead used for navigation.
    Tab,

    /// Move view up without affecting selection
    ViewUp,
    /// Move view down without affecting selection
    ViewDown,

    /// Move left
    Left,
    /// Move right
    Right,
    /// Move up
    Up,
    /// Move down
    Down,
    /// Move left one word
    WordLeft,
    /// Move right one word
    WordRight,
    /// Move to start (of the line)
    Home,
    /// Move to end (of the line)
    End,
    /// Move to start of the document
    DocHome,
    /// Move to end of the document
    DocEnd,
    /// Move up a page
    PageUp,
    /// Move down a page
    PageDown,

    /// Capture a screenshot
    Snapshot,
    /// Lock output of screen
    ScrollLock,
    /// Pause key
    Pause,
    /// Insert key
    Insert,

    /// Delete forwards
    Delete,
    /// Delete backwards (Backspace key)
    DelBack,
    /// Delete forwards one word
    DelWord,
    /// Delete backwards one word
    DelWordBack,

    /// Clear any selections
    Deselect,
    /// Select all contents
    SelectAll,

    /// Find (start)
    Find,
    /// Find and replace (start)
    FindReplace,
    /// Find next
    FindNext,
    /// Find previous
    FindPrevious,

    /// Make text bold
    Bold,
    /// Make text italic
    Italic,
    /// Underline text
    Underline,
    /// Insert a link
    Link,

    /// Copy to clipboard and clear
    Cut,
    /// Copy to clipboard
    Copy,
    /// Copy from clipboard
    Paste,
    /// Undo the last action
    Undo,
    /// Redo the last undone action
    Redo,

    /// New document
    New,
    /// Open document
    Open,
    /// Save document
    Save,
    /// Print document
    Print,

    /// Navigate forwards one page/item
    NavNext,
    /// Navigate backwards one page/item
    NavPrevious,
    /// Navigate to the parent item
    ///
    /// May be used to browse "up" to a parent directory.
    NavParent,
    /// Navigate "down"
    ///
    /// This is an opposite to `NavParent`, and will mostly not be used.
    NavDown,

    /// Open a new tab
    TabNew,
    /// Navigate to next tab
    TabNext,
    /// Navigate to previous tab
    TabPrevious,

    /// Show help
    Help,
    /// Rename
    Rename,
    /// Refresh
    Refresh,
    /// Debug
    Debug,
    /// Spell-check tool
    SpellCheck,
    /// Open the context menu
    ContextMenu,
    /// Open or activate the application menu / menubar
    Menu,
    /// Make view fullscreen
    Fullscreen,

    /// Close window/tab/popup
    Close,
    /// Exit program (e.g. Ctrl+Q)
    Exit,
}

impl Command {
    /// Try constructing from a [`winit::keyboard::Key`]
    pub fn new(key: &Key) -> Option<Self> {
        match key {
            Key::Named(named) => Some(match named {
                NamedKey::ScrollLock => Command::ScrollLock,
                NamedKey::Enter => Command::Enter,
                NamedKey::Tab => Command::Tab,
                NamedKey::Space => Command::Space,
                NamedKey::ArrowDown => Command::Down,
                NamedKey::ArrowLeft => Command::Left,
                NamedKey::ArrowRight => Command::Right,
                NamedKey::ArrowUp => Command::Up,
                NamedKey::End => Command::End,
                NamedKey::Home => Command::Home,
                NamedKey::PageDown => Command::PageDown,
                NamedKey::PageUp => Command::PageUp,
                NamedKey::Backspace => Command::DelBack,
                NamedKey::Clear => Command::Deselect,
                NamedKey::Copy => Command::Copy,
                NamedKey::Cut => Command::Cut,
                NamedKey::Delete => Command::Delete,
                NamedKey::Insert => Command::Insert,
                NamedKey::Paste => Command::Paste,
                NamedKey::Redo | NamedKey::Again => Command::Redo,
                NamedKey::Undo => Command::Undo,
                NamedKey::ContextMenu => Command::ContextMenu,
                NamedKey::Escape => Command::Escape,
                NamedKey::Execute => Command::Activate,
                NamedKey::Find => Command::Find,
                NamedKey::Help => Command::Help,
                NamedKey::Pause => Command::Pause,
                NamedKey::Select => Command::SelectAll,
                NamedKey::PrintScreen => Command::Snapshot,
                // NamedKey::Close => CloseDocument ?
                NamedKey::New => Command::New,
                NamedKey::Open => Command::Open,
                NamedKey::Print => Command::Print,
                NamedKey::Save => Command::Save,
                NamedKey::SpellCheck => Command::SpellCheck,
                NamedKey::BrowserBack | NamedKey::GoBack => Command::NavPrevious,
                NamedKey::BrowserForward => Command::NavNext,
                NamedKey::BrowserRefresh => Command::Refresh,
                NamedKey::Exit => Command::Exit,
                _ => return None,
            }),
            _ => None,
        }
    }

    /// True for "activation" commands
    ///
    /// This matches:
    ///
    /// -   [`Self::Activate`] — programmatic activation
    /// -   [`Self::Enter`] —  <kbd>Enter</kbd> and <kbd>Return</kbd> keys
    /// -   [`Self::Space`] — <kbd>Space</kbd> key
    pub fn is_activate(self) -> bool {
        use Command::*;
        matches!(self, Activate | Enter | Space)
    }

    /// Convert to selection-focus command
    ///
    /// Certain limited commands may be sent to widgets with selection focus but
    /// not character or navigation focus.
    pub fn suitable_for_sel_focus(self) -> bool {
        use Command::*;
        matches!(self, Escape | Cut | Copy | Deselect)
    }

    /// Convert arrow keys to a direction
    pub fn as_direction(self) -> Option<Direction> {
        match self {
            Command::Left => Some(Direction::Left),
            Command::Right => Some(Direction::Right),
            Command::Up => Some(Direction::Up),
            Command::Down => Some(Direction::Down),
            _ => None,
        }
    }
}

/// Reason that navigation focus is received
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FocusSource {
    /// Focus is received as a result of a mouse or touch event
    Pointer,
    /// Focus is received as a result of keyboard navigation (usually
    /// <kbd>Tab</kbd>) or a command ([`Event::Command`])
    Key,
    /// Focus is received from a programmatic event
    Synthetic,
}

impl FocusSource {
    pub fn key_or_synthetic(self) -> bool {
        match self {
            FocusSource::Pointer => false,
            FocusSource::Key | FocusSource::Synthetic => true,
        }
    }
}

/// Type used by [`Event::Scroll`]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScrollDelta {
    /// Scroll a given number of lines
    LineDelta(f32, f32),
    /// Scroll a given number of pixels
    PixelDelta(Offset),
}