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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
// 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 context state

// Without winit, several things go unused
#![cfg_attr(not(winit), allow(unused))]

use linear_map::LinearMap;
use smallvec::SmallVec;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::time::Instant;
use std::u16;

use super::config::WindowConfig;
use super::*;
use crate::app::{AppShared, Platform, WindowDataErased};
use crate::cast::Cast;
use crate::geom::Coord;
use crate::messages::{Erased, MessageStack};
use crate::util::WidgetHierarchy;
use crate::LayoutExt;
use crate::{Action, Id, NavAdvance, Node, Widget, WindowId};

mod config;
mod cx_pub;
mod platform;
mod press;

pub use config::ConfigCx;
pub use press::{GrabBuilder, Press, PressSource};

/// Controls the types of events delivered by [`Press::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, without scaling or rotation
    PanOnly,
    /// Deliver [`Event::Pan`] events, with rotation
    PanRotate,
    /// Deliver [`Event::Pan`] events, with scaling
    PanScale,
    /// Deliver [`Event::Pan`] events, with scaling and rotation
    PanFull,
}

impl GrabMode {
    /// True for "pan" variants
    pub fn is_pan(self) -> bool {
        use GrabMode::*;
        matches!(self, PanFull | PanScale | PanRotate | PanOnly)
    }
}

#[derive(Clone, Debug)]
enum GrabDetails {
    Click { cur_id: Option<Id> },
    Grab,
    Pan((u16, u16)),
}

impl GrabDetails {
    fn is_pan(&self) -> bool {
        matches!(self, GrabDetails::Pan(_))
    }
}

#[derive(Clone, Debug)]
struct MouseGrab {
    button: MouseButton,
    repetitions: u32,
    start_id: Id,
    depress: Option<Id>,
    details: GrabDetails,
}

impl<'a> EventCx<'a> {
    fn flush_mouse_grab_motion(&mut self) {
        if let Some(grab) = self.mouse_grab.as_mut() {
            match grab.details {
                GrabDetails::Click { ref cur_id } => {
                    if grab.start_id == cur_id {
                        if grab.depress != *cur_id {
                            grab.depress = cur_id.clone();
                            self.action |= Action::REDRAW;
                        }
                    } else if grab.depress.is_some() {
                        grab.depress = None;
                        self.action |= Action::REDRAW;
                    }
                }
                _ => (),
            }
        }
    }
}

#[derive(Clone, Debug)]
struct TouchGrab {
    id: u64,
    start_id: Id,
    depress: Option<Id>,
    cur_id: Option<Id>,
    last_move: Coord,
    coord: Coord,
    mode: GrabMode,
    pan_grab: (u16, u16),
}

impl TouchGrab {
    fn flush_click_move(&mut self) -> Action {
        if self.mode == GrabMode::Click && self.last_move != self.coord {
            self.last_move = self.coord;
            if self.start_id == self.cur_id {
                if self.depress != self.cur_id {
                    self.depress = self.cur_id.clone();
                    return Action::REDRAW;
                }
            } else if self.depress.is_some() {
                self.depress = None;
                return Action::REDRAW;
            }
        }
        Action::empty()
    }
}

const MAX_PAN_GRABS: usize = 2;

#[derive(Clone, Debug)]
struct PanGrab {
    id: Id,
    mode: GrabMode,
    source_is_touch: bool,
    n: u16,
    coords: [(Coord, Coord); MAX_PAN_GRABS],
}

#[derive(Debug)]
struct PendingSelFocus {
    target: Option<Id>,
    key_focus: bool,
    source: FocusSource,
}

#[crate::impl_default(PendingNavFocus::None)]
enum PendingNavFocus {
    None,
    Set {
        target: Option<Id>,
        source: FocusSource,
    },
    Next {
        target: Option<Id>,
        reverse: bool,
        source: FocusSource,
    },
}

type AccessLayer = (bool, HashMap<Key, Id>);

/// Event context state
///
/// This struct encapsulates window-specific event-handling state and handling.
/// Most operations are only available via a [`EventCx`] handle, though some
/// are available on this struct.
///
/// Besides event handling, this struct also configures widgets.
///
/// Some methods are intended only for usage by graphics and platform backends
/// and are hidden from generated documentation unless the `internal_doc`
/// feature is enabled. Only [winit]
/// events are currently supported; changes will be required to generalise this.
///
/// [winit]: https://github.com/rust-windowing/winit
//
// Note that the most frequent usage of fields is to check highlighting states
// for each widget during drawing. Most fields contain only a few values, hence
// `SmallVec` is used to keep contents in local memory.
pub struct EventState {
    config: WindowConfig,
    platform: Platform,
    disabled: Vec<Id>,
    window_has_focus: bool,
    modifiers: ModifiersState,
    /// key focus is on same widget as sel_focus; otherwise its value is ignored
    key_focus: bool,
    sel_focus: Option<Id>,
    nav_focus: Option<Id>,
    nav_fallback: Option<Id>,
    hover: Option<Id>,
    hover_icon: CursorIcon,
    old_hover_icon: CursorIcon,
    key_depress: LinearMap<PhysicalKey, Id>,
    last_mouse_coord: Coord,
    last_click_button: MouseButton,
    last_click_repetitions: u32,
    last_click_timeout: Instant,
    mouse_grab: Option<MouseGrab>,
    touch_grab: SmallVec<[TouchGrab; 8]>,
    pan_grab: SmallVec<[PanGrab; 4]>,
    access_layers: BTreeMap<Id, AccessLayer>,
    // For each: (WindowId of popup, popup descriptor, old nav focus)
    popups: SmallVec<[(WindowId, crate::PopupDescriptor, Option<Id>); 16]>,
    popup_removed: SmallVec<[(Id, WindowId); 16]>,
    time_updates: Vec<(Instant, Id, u64)>,
    // Set of futures of messages together with id of sending widget
    fut_messages: Vec<(Id, Pin<Box<dyn Future<Output = Erased>>>)>,
    // Widget requiring update (and optionally configure)
    pending_update: Option<(Id, bool)>,
    // Optional new target for selection focus. bool is true if this also gains key focus.
    pending_sel_focus: Option<PendingSelFocus>,
    pending_nav_focus: PendingNavFocus,
    pending_cmds: VecDeque<(Id, Command)>,
    #[cfg_attr(not(feature = "internal_doc"), doc(hidden))]
    #[cfg_attr(doc_cfg, doc(cfg(internal_doc)))]
    pub action: Action,
}

/// internals
impl EventState {
    #[inline]
    fn key_focus(&self) -> Option<Id> {
        if self.key_focus {
            self.sel_focus.clone()
        } else {
            None
        }
    }

    fn clear_key_focus(&mut self) {
        if self.key_focus {
            if let Some(ref mut pending) = self.pending_sel_focus {
                if pending.target == self.sel_focus {
                    pending.key_focus = false;
                }
            } else {
                self.pending_sel_focus = Some(PendingSelFocus {
                    target: None,
                    key_focus: false,
                    source: FocusSource::Synthetic,
                });
            }
        }
    }

    fn set_pan_on(
        &mut self,
        id: Id,
        mode: GrabMode,
        source_is_touch: bool,
        coord: Coord,
    ) -> (u16, u16) {
        for (gi, grab) in self.pan_grab.iter_mut().enumerate() {
            if grab.id == id {
                if grab.source_is_touch != source_is_touch {
                    self.remove_pan(gi);
                    break;
                }

                debug_assert_eq!(grab.mode, mode);

                let index = grab.n;
                if usize::from(index) < MAX_PAN_GRABS {
                    grab.coords[usize::from(index)] = (coord, coord);
                }
                grab.n = index + 1;
                return (gi.cast(), index);
            }
        }

        let gj = self.pan_grab.len().cast();
        let n = 1;
        let mut coords: [(Coord, Coord); MAX_PAN_GRABS] = Default::default();
        coords[0] = (coord, coord);
        log::trace!("set_pan_on: index={}, id={id}", self.pan_grab.len());
        self.pan_grab.push(PanGrab {
            id,
            mode,
            source_is_touch,
            n,
            coords,
        });
        (gj, 0)
    }

    fn remove_pan(&mut self, index: usize) {
        log::trace!("remove_pan: index={index}");
        self.pan_grab.remove(index);
        if let Some(grab) = &mut self.mouse_grab {
            if let GrabDetails::Pan(ref mut g) = grab.details {
                if usize::from(g.0) >= index {
                    g.0 -= 1;
                }
            }
        }
        for grab in self.touch_grab.iter_mut() {
            let p0 = grab.pan_grab.0;
            if usize::from(p0) >= index && p0 != u16::MAX {
                grab.pan_grab.0 = p0 - 1;
            }
        }
    }

    fn remove_pan_grab(&mut self, g: (u16, u16)) {
        if let Some(grab) = self.pan_grab.get_mut(usize::from(g.0)) {
            grab.n -= 1;
            if grab.n == 0 {
                return self.remove_pan(g.0.into());
            }
            assert!(grab.source_is_touch);
            for i in (usize::from(g.1))..(usize::from(grab.n) - 1) {
                grab.coords[i] = grab.coords[i + 1];
            }
        } else {
            return;
        }

        // Note: the fact that grab.n > 0 implies source is a touch event!
        for grab in self.touch_grab.iter_mut() {
            if grab.pan_grab.0 == g.0 && grab.pan_grab.1 > g.1 {
                grab.pan_grab.1 -= 1;
                if usize::from(grab.pan_grab.1) == MAX_PAN_GRABS - 1 {
                    let v = grab.coord;
                    self.pan_grab[usize::from(g.0)].coords[usize::from(grab.pan_grab.1)] = (v, v);
                }
            }
        }
    }

    #[inline]
    fn get_touch(&mut self, touch_id: u64) -> Option<&mut TouchGrab> {
        self.touch_grab.iter_mut().find(|grab| grab.id == touch_id)
    }

    // Clears touch grab and pan grab and redraws
    fn remove_touch(&mut self, touch_id: u64) -> Option<TouchGrab> {
        for i in 0..self.touch_grab.len() {
            if self.touch_grab[i].id == touch_id {
                let grab = self.touch_grab.remove(i);
                log::trace!(
                    "remove_touch: touch_id={touch_id}, start_id={}",
                    grab.start_id
                );
                self.opt_action(grab.depress.clone(), Action::REDRAW);
                self.remove_pan_grab(grab.pan_grab);
                return Some(grab);
            }
        }
        None
    }
}

/// Event handling context
///
/// `EventCx` and [`EventState`] (available via [`Deref`]) support various
/// event management and event-handling state querying operations.
#[must_use]
pub struct EventCx<'a> {
    state: &'a mut EventState,
    shared: &'a mut dyn AppShared,
    window: &'a dyn WindowDataErased,
    messages: &'a mut MessageStack,
    last_child: Option<usize>,
    scroll: Scroll,
}

impl<'a> Deref for EventCx<'a> {
    type Target = EventState;
    fn deref(&self) -> &Self::Target {
        self.state
    }
}
impl<'a> DerefMut for EventCx<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.state
    }
}

/// Internal methods
impl<'a> EventCx<'a> {
    fn start_key_event(&mut self, mut widget: Node<'_>, vkey: Key, code: PhysicalKey) {
        log::trace!(
            "start_key_event: widget={}, vkey={vkey:?}, physical_key={code:?}",
            widget.id()
        );

        let opt_command = self
            .config
            .shortcuts(|s| s.try_match(self.modifiers, &vkey));

        if let Some(cmd) = opt_command {
            let mut targets = vec![];
            let mut send = |_self: &mut Self, id: Id, cmd| -> bool {
                if !targets.contains(&id) {
                    let event = Event::Command(cmd, Some(code));
                    let used = _self.send_event(widget.re(), id.clone(), event);
                    targets.push(id);
                    used
                } else {
                    false
                }
            };

            if self.key_focus || cmd.suitable_for_sel_focus() {
                if let Some(id) = self.sel_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if !self.modifiers.alt_key() {
                if let Some(id) = self.nav_focus.clone() {
                    if send(self, id, cmd) {
                        return;
                    }
                }
            }

            if let Some(id) = self.popups.last().map(|popup| popup.1.id.clone()) {
                if send(self, id, cmd) {
                    return;
                }
            }

            if let Some(id) = self.nav_fallback.clone() {
                if send(self, id, cmd) {
                    return;
                }
            }

            if matches!(cmd, Command::Debug) {
                if let Some(ref id) = self.hover {
                    if let Some(w) = widget.as_layout().find_widget(id) {
                        let hier = WidgetHierarchy::new(w);
                        log::debug!("Widget heirarchy (from mouse): {hier}");
                    }
                } else {
                    let hier = WidgetHierarchy::new(widget.as_layout());
                    log::debug!("Widget heirarchy (whole window): {hier}");
                }
                return;
            }
        }

        // Next priority goes to access keys when Alt is held or alt_bypass is true
        let mut target = None;
        for id in (self.popups.iter().rev())
            .map(|(_, popup, _)| popup.id.clone())
            .chain(std::iter::once(widget.id()))
        {
            if let Some(layer) = self.access_layers.get(&id) {
                // but only when Alt is held or alt-bypass is enabled:
                if self.modifiers == ModifiersState::ALT
                    || layer.0 && self.modifiers == ModifiersState::empty()
                {
                    if let Some(id) = layer.1.get(&vkey).cloned() {
                        target = Some(id);
                        break;
                    }
                }
            }
        }

        if let Some(id) = target {
            if let Some(id) = self.nav_next(widget.re(), Some(&id), NavAdvance::None) {
                self.set_nav_focus(id, FocusSource::Key);
            }
            let event = Event::Command(Command::Activate, Some(code));
            self.send_event(widget, id, event);
        } else if self.config.nav_focus && vkey == Key::Named(NamedKey::Tab) {
            let shift = self.modifiers.shift_key();
            self.next_nav_focus_impl(widget.re(), None, shift, FocusSource::Key);
        } else if vkey == Key::Named(NamedKey::Escape) {
            if let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
                self.close_window(id);
            }
        }
    }

    // Clears mouse grab and pan grab, resets cursor and redraws
    fn remove_mouse_grab(&mut self, success: bool) -> Option<(Id, Event)> {
        if let Some(grab) = self.mouse_grab.take() {
            log::trace!("remove_mouse_grab: start_id={}", grab.start_id);
            self.window.set_cursor_icon(self.hover_icon);
            self.opt_action(grab.depress.clone(), Action::REDRAW);
            if let GrabDetails::Pan(g) = grab.details {
                self.remove_pan_grab(g);
                // Pan grabs do not receive Event::PressEnd
                None
            } else {
                let press = Press {
                    source: PressSource::Mouse(grab.button, grab.repetitions),
                    id: self.hover.clone(),
                    coord: self.last_mouse_coord,
                };
                let event = Event::PressEnd { press, success };
                Some((grab.start_id, event))
            }
        } else {
            None
        }
    }

    pub(crate) fn assert_post_steal_unused(&self) {
        if self.scroll != Scroll::None || self.messages.has_any() {
            panic!("steal_event affected EventCx and returned Unused");
        }
    }

    pub(crate) fn post_send(&mut self, index: usize) -> Option<Scroll> {
        self.last_child = Some(index);
        (self.scroll != Scroll::None).then_some(self.scroll)
    }

    /// Replay a message as if it was pushed by `id`
    fn replay(&mut self, mut widget: Node<'_>, id: Id, msg: Erased) {
        debug_assert!(self.scroll == Scroll::None);
        debug_assert!(self.last_child.is_none());
        self.messages.set_base();
        log::trace!(target: "kas_core::event", "replay: id={id}: {msg:?}");

        widget._replay(self, id, msg);
        self.last_child = None;
        self.scroll = Scroll::None;
    }

    // Call Widget::_send; returns true when event is used
    fn send_event(&mut self, mut widget: Node<'_>, mut id: Id, event: Event) -> bool {
        debug_assert!(self.scroll == Scroll::None);
        debug_assert!(self.last_child.is_none());
        self.messages.set_base();
        log::trace!(target: "kas_core::event", "send_event: id={id}: {event:?}");

        // TODO(opt): we should be able to use binary search here
        let mut disabled = false;
        if !event.pass_when_disabled() {
            for d in &self.disabled {
                if d.is_ancestor_of(&id) {
                    id = d.clone();
                    disabled = true;
                }
            }
            if disabled {
                log::trace!(target: "kas_core::event", "target is disabled; sending to ancestor {id}");
            }
        }

        let used = widget._send(self, id, disabled, event) == Used;

        self.last_child = None;
        self.scroll = Scroll::None;
        used
    }

    fn send_popup_first(&mut self, mut widget: Node<'_>, id: Option<Id>, event: Event) {
        while let Some(pid) = self.popups.last().map(|(_, p, _)| p.id.clone()) {
            let mut target = pid;
            if let Some(id) = id.clone() {
                if target.is_ancestor_of(&id) {
                    target = id;
                }
            }
            log::trace!("send_popup_first: id={target}: {event:?}");
            if self.send_event(widget.re(), target, event.clone()) {
                return;
            }
        }
        if let Some(id) = id {
            self.send_event(widget, id, event);
        }
    }

    // Call Widget::_nav_next
    #[inline]
    fn nav_next(
        &mut self,
        mut widget: Node<'_>,
        focus: Option<&Id>,
        advance: NavAdvance,
    ) -> Option<Id> {
        log::trace!(target: "kas_core::event", "nav_next: focus={focus:?}, advance={advance:?}");

        widget._nav_next(&mut self.config_cx(), focus, advance)
    }

    // Clear old hover, set new hover, send events.
    // If there is a popup, only permit descendands of that.
    fn set_hover(&mut self, mut widget: Node<'_>, mut w_id: Option<Id>) {
        if let Some(ref id) = w_id {
            if let Some(popup) = self.popups.last() {
                if !popup.1.id.is_ancestor_of(id) {
                    w_id = None;
                }
            }
        }

        if self.hover != w_id {
            log::trace!("set_hover: w_id={w_id:?}");
            self.hover_icon = Default::default();
            if let Some(id) = self.hover.take() {
                self.send_event(widget.re(), id, Event::MouseHover(false));
            }
            self.hover = w_id.clone();

            if let Some(id) = w_id {
                self.send_event(widget, id, Event::MouseHover(true));
            }
        }
    }

    // Set selection focus to `wid` immediately; if `key_focus` also set that
    fn set_sel_focus(&mut self, mut widget: Node<'_>, pending: PendingSelFocus) {
        let PendingSelFocus {
            target,
            key_focus,
            source,
        } = pending;

        log::trace!("set_sel_focus: target={target:?}, key_focus={key_focus}");

        if target == self.sel_focus {
            self.key_focus = target.is_some() && (self.key_focus || key_focus);
            return;
        }

        if let Some(id) = self.sel_focus.clone() {
            if self.key_focus {
                // If widget has key focus, this is lost
                self.send_event(widget.re(), id.clone(), Event::LostKeyFocus);
            }

            // Selection focus is lost if another widget receives key focus
            self.send_event(widget.re(), id, Event::LostSelFocus);
        }

        self.key_focus = key_focus;
        self.sel_focus = target.clone();

        if let Some(id) = target {
            // The widget probably already has nav focus, but anyway:
            self.set_nav_focus(id.clone(), FocusSource::Synthetic);

            self.send_event(widget.re(), id.clone(), Event::SelFocus(source));
            if key_focus {
                self.send_event(widget, id, Event::KeyFocus);
            }
        }
    }

    /// Set navigation focus immediately
    fn set_nav_focus_impl(&mut self, mut widget: Node, target: Option<Id>, source: FocusSource) {
        if target == self.nav_focus || !self.config.nav_focus {
            return;
        }

        self.clear_key_focus();

        if let Some(old) = self.nav_focus.take() {
            self.action(&old, Action::REDRAW);
            self.send_event(widget.re(), old, Event::LostNavFocus);
        }

        self.nav_focus = target.clone();
        log::debug!(target: "kas_core::event", "nav_focus = {target:?}");
        if let Some(id) = target {
            self.action(&id, Action::REDRAW);
            self.send_event(widget, id, Event::NavFocus(source));
        }
    }

    /// Advance the keyboard navigation focus immediately
    fn next_nav_focus_impl(
        &mut self,
        mut widget: Node,
        target: Option<Id>,
        reverse: bool,
        source: FocusSource,
    ) {
        if !self.config.nav_focus || (target.is_some() && target == self.nav_focus) {
            return;
        }

        if let Some(id) = self.popups.last().map(|(_, p, _)| p.id.clone()) {
            if id.is_ancestor_of(widget.id_ref()) {
                // do nothing
            } else if let Some(r) = widget.find_node(&id, |node| {
                self.next_nav_focus_impl(node, target, reverse, source)
            }) {
                return r;
            } else {
                log::warn!(
                    target: "kas_core::event",
                    "next_nav_focus: have open pop-up which is not a child of widget",
                );
                return;
            }
        }

        let advance = if !reverse {
            NavAdvance::Forward(target.is_some())
        } else {
            NavAdvance::Reverse(target.is_some())
        };
        let focus = target.or_else(|| self.nav_focus.clone());

        // Whether to restart from the beginning on failure
        let restart = focus.is_some();

        let mut opt_id = self.nav_next(widget.re(), focus.as_ref(), advance);
        if restart && opt_id.is_none() {
            opt_id = self.nav_next(widget.re(), None, advance);
        }

        self.set_nav_focus_impl(widget, opt_id, source);
    }
}