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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use crate::focus::core::FocusCore;
use crate::{FocusFlag, HasFocus, HasFocusFlag};
use log::debug;
use rat_event::{ct_event, FocusKeys, HandleEvent, MouseOnly, Outcome};
use ratatui::layout::Rect;

#[derive(Debug, Default)]
pub struct Focus<'a> {
    /// Name for the cycle.
    name: String,
    pub core: FocusCore<'a>,
}

impl<'a> Focus<'a> {
    /// Construct a new focus list.
    pub fn new(list: &[&'a dyn HasFocusFlag]) -> Self {
        let mut ff = Focus::default();
        for f in list {
            ff.core.add(f.focus(), f.area(), f.z_areas(), f.navigable());
        }
        ff
    }

    /// Construct a new focus list for a container widget.
    ///
    /// The focus-flag for the container accumulates all the flags.
    /// If any has focus, the container has the focus too.
    /// Focus-gained and focus-lost are only set if the focus
    /// leaves the container.
    ///
    /// The container widget itself interacts with the mouse too.
    /// If no single widget is hit with the mouse, but the area of
    /// the container is, the first widget gets the focus.
    ///
    /// See `examples/focus_recursive` and `examples/focus_recursive2`
    pub fn new_container(c: &'a dyn HasFocusFlag, list: &[&'a dyn HasFocusFlag]) -> Self {
        let mut ff = Focus::default();
        ff.core.set_container(c.focus(), c.area(), c.z_areas());
        for f in list {
            ff.core.add(f.focus(), f.area(), f.z_areas(), f.navigable());
        }
        ff
    }

    /// Construct a new focus list with group accumulator.
    ///
    /// This is meant for some loose grouping of widgets, for which
    /// you want an overview.
    ///
    /// The same rules apply as for new_accu(), but with this one
    /// there is no overall area for mouse interaction.
    pub fn new_grp(grp: &'a FocusFlag, list: &[&'a dyn HasFocusFlag]) -> Self {
        let mut ff = Focus::default();
        ff.core.set_container(grp, Rect::ZERO, &[]);
        for f in list {
            ff.core.add(f.focus(), f.area(), f.z_areas(), f.navigable());
        }
        ff
    }

    /// Add a single widget.
    /// This doesn't add any z_areas and assumes navigable is true.
    pub fn add_flag(&mut self, flag: &'a FocusFlag, area: Rect) -> &mut Self {
        self.core.add(flag, area, &[], true);
        self
    }

    /// Add a sub-focus cycle.
    ///
    /// All its widgets are appended to this list. If the sub-cycle
    /// has an accumulator it's added to the sub-accumulators. All
    /// sub-sub-accumulators are appended too.
    pub fn add_focus(&mut self, focus: Focus<'a>) -> &mut Self {
        self.core.add_focus(focus.core);
        self
    }

    /// Add a container widget.
    pub fn add_container(&mut self, c: &'a dyn HasFocus) -> &mut Self {
        let ff = c.focus();
        self.core.add_focus(ff.core);
        self
    }

    /// Add a single widget.
    pub fn add(&mut self, f: &'a dyn HasFocusFlag) -> &mut Self {
        self.core
            .add(f.focus(), f.area(), f.z_areas(), f.navigable());
        self
    }

    /// Add a list of widgets.
    pub fn add_all(&mut self, list: &[&'a dyn HasFocusFlag]) -> &mut Self {
        for f in list {
            self.core
                .add(f.focus(), f.area(), f.z_areas(), f.navigable());
        }
        self
    }

    /// Writes a log for each operation.
    pub fn enable_log(&self, log: bool) {
        self.core.log.set(log)
    }

    /// Set a name for debugging.
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = name.into();
    }

    /// Name for debugging.
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Set the initial state for all widgets.
    ///
    /// This ensures that there is only one focused widget.
    /// The first widget in the list gets the focus.
    pub fn init(&self) {
        if self.core.log.get() {
            debug!("init focus");
        }
        self.core.focus_init();
    }

    /// Sets the focus to the widget.
    ///
    /// Sets the focus, but doesn't set lost or gained.
    /// This can be used to prevent validation of the field.
    pub fn focus_widget_no_lost(&self, widget_state: &'a dyn HasFocusFlag) {
        if self.core.log.get() {
            debug!("focus_no_lost {:?}", widget_state.focus());
        }
        if let Some(n) = self.core.index_of(widget_state.focus()) {
            self.core.focus_no_lost(n);
        }
    }

    /// Sets the focus to the given widget.
    ///
    /// Sets the focus, gained and lost flags.
    ///
    /// If this ends up with the same widget as
    /// before gained and lost flags are not set.
    pub fn focus_widget(&self, widget_state: &'a dyn HasFocusFlag) {
        if self.core.log.get() {
            debug!("focus {:?}", widget_state.focus());
        }
        if let Some(n) = self.core.index_of(widget_state.focus()) {
            self.core.focus_idx(n);
        }
    }

    /// Sets the focus to the widget.
    ///
    /// Sets focus and gained but not lost.
    /// This can be used to prevent validation of the field.
    pub fn focus_no_lost(&self, flag: &FocusFlag) {
        if self.core.log.get() {
            debug!("focus_no_lost {:?}", flag);
        }
        if let Some(n) = self.core.index_of(flag) {
            self.core.focus_no_lost(n);
        }
    }

    /// Sets the focus to the widget with `tag`.
    ///
    /// Sets the focus, gained and lost flags.
    ///
    /// If this ends up with the same widget as
    /// before gained and lost flags are not set.
    pub fn focus(&self, flag: &FocusFlag) {
        if self.core.log.get() {
            debug!("focus {:?}", flag);
        }
        if let Some(n) = self.core.index_of(flag) {
            self.core.focus_idx(n);
        }
    }

    /// Returns the focused widget as FocusFlag.
    ///
    /// This is mainly for debugging purposes.
    /// For control-flow [crate::match_focus] or [crate::on_gained] or [crate::on_lost]
    /// will be nicer.
    pub fn focused(&self) -> Option<&'a FocusFlag> {
        self.core.focused()
    }

    /// Returns the widget that lost the focus as FocusFlag.
    ///
    /// This is mainly for debugging purposes.
    /// For control-flow [crate::match_focus] or [crate::on_gained] or [crate::on_lost]
    /// will be nicer.
    pub fn lost_focus(&self) -> Option<&'a FocusFlag> {
        self.core.lost_focus()
    }

    /// Returns the widget that gained the focus as FocusFlag.
    ///
    /// This is mainly for debugging purposes.
    /// For control-flow [crate::match_focus] or [crate::on_gained] or [crate::on_lost]
    /// will be nicer.
    pub fn gained_focus(&self) -> Option<&'a FocusFlag> {
        self.core.gained_focus()
    }

    /// Reset lost + gained flags.
    /// This is done automatically in `HandleEvent::handle()` for every event.
    pub fn reset_lost_gained(&self) {
        if self.core.log.get() {
            debug!("reset_lost_gained");
        }
        self.core.reset_lost_gained();
    }

    /// Change the focus.
    ///
    /// Sets the focus, gained and lost flags.
    /// If this ends up with the same widget as
    /// before gained and lost flags are not set.
    pub fn focus_idx(&self, idx: usize) {
        if self.core.log.get() {
            debug!("focus_idx {}", idx);
        }
        self.core.focus_idx(idx);
    }

    /// Change to focus to the given position.
    pub fn focus_at(&self, col: u16, row: u16) -> bool {
        if self.core.log.get() {
            debug!("focus_at {},{}", col, row);
        }
        self.core.focus_at(col, row)
    }

    /// Focus the next widget in the cycle.
    ///
    /// Sets the focus, gained and lost flags. If this ends up with the same widget as
    /// before focus, gained and lost flag are all set.
    ///
    /// If no field has the focus the first one gets it.
    pub fn next(&self) -> bool {
        if self.core.log.get() {
            debug!("next {:?}", self.core.focused());
        }
        self.core.next()
    }

    /// Focus the previous widget in the cycle.
    ///
    /// Sets the focus and lost flags. If this ends up with the same widget as
    /// before it returns *true* and sets the focus, gained and lost flag.
    ///
    /// If no field has the focus the first one gets it.
    pub fn prev(&self) -> bool {
        if self.core.log.get() {
            debug!("prev {:?}", self.core.focused());
        }
        self.core.prev()
    }
}

mod core {
    use crate::{FocusFlag, ZRect};
    use log::debug;
    use ratatui::layout::Rect;
    use std::cell::Cell;
    use std::ptr;

    #[derive(Debug, Clone, Copy)]
    struct Container<'a> {
        /// Area for the whole compound. Only valid if container_focus is Some().
        area: Rect,
        /// Area split in regions. Only valid if container_focus is Some().
        z_area: &'a [ZRect],
        /// Summarizes all the contained FocusFlags.
        /// If any of them has the focus set, this will be set too.
        /// This can help if you build compound widgets.
        focus: &'a FocusFlag,
    }

    #[derive(Debug, Default)]
    pub struct FocusCore<'a> {
        /// Focus logging
        pub log: Cell<bool>,

        /// Summary of all focus-flags in one container focus flag.
        container: Option<Container<'a>>,

        /// Areas for each widget.
        areas: Vec<Rect>,
        /// Areas for each widget split in regions.
        z_areas: Vec<&'a [ZRect]>,
        /// Keyboard navigable
        navigable: Vec<bool>,
        /// List of flags.
        focus: Vec<&'a FocusFlag>,

        /// List of sub-containers and their dependencies.
        ///
        /// This is filled if you call [crate::Focus::add_focus]. The
        /// container_focus of the appended Focus and all its focus-flags
        /// are added. And all the sub_container's of it are appended too.
        sub_container: Vec<(Container<'a>, Vec<&'a FocusFlag>)>,
    }

    impl<'a> FocusCore<'a> {
        pub fn container_area(&self) -> Option<Rect> {
            self.container.map(|v| v.area)
        }

        pub fn container_z_area(&self) -> Option<&[ZRect]> {
            self.container.map(|v| v.z_area)
        }

        pub fn container_focus(&self) -> Option<&FocusFlag> {
            self.container.map(|v| v.focus)
        }

        pub fn areas(&self) -> &[Rect] {
            &self.areas
        }

        pub fn z_areas(&self) -> &[&[ZRect]] {
            &self.z_areas
        }

        pub fn navigable(&self) -> &[bool] {
            &self.navigable
        }

        pub fn focus(&self) -> &[&FocusFlag] {
            &self.focus
        }

        pub fn sub_container(&self) -> Vec<(Rect, &'a [ZRect], &'a FocusFlag, Vec<&FocusFlag>)> {
            self.sub_container
                .iter()
                .map(|(c, f)| (c.area, c.z_area, c.focus, f.clone()))
                .collect()
        }

        pub(super) fn set_container(
            &mut self,
            focus: &'a FocusFlag,
            area: Rect,
            z_area: &'a [ZRect],
        ) {
            self.container = Some(Container {
                area,
                z_area,
                focus,
            })
        }

        pub(super) fn add(
            &mut self,
            focus: &'a FocusFlag,
            area: Rect,
            z_areas: &'a [ZRect],
            navigable: bool,
        ) {
            self.focus.push(focus);
            self.areas.push(area);
            self.z_areas.push(z_areas);
            self.navigable.push(navigable)
        }

        pub(super) fn add_focus(&mut self, focus: FocusCore<'a>) {
            if let Some(container) = focus.container {
                self.sub_container.push((container, focus.focus.clone()));
            }
            for v in focus.sub_container {
                self.sub_container.push(v);
            }

            self.focus.extend(focus.focus);
            self.areas.extend(focus.areas);
            self.z_areas.extend(focus.z_areas);
            self.navigable.extend(focus.navigable);
        }

        pub(super) fn index_of(&self, flag: &FocusFlag) -> Option<usize> {
            if let Some((n, _)) = self
                .focus
                .iter()
                .enumerate() //
                .find(|(_, f)| ptr::eq(**f, flag))
            {
                Some(n)
            } else {
                None
            }
        }

        // reset flags for a new round.
        fn __start_change(&self, set_lost: bool) {
            for p in self.focus.iter() {
                if set_lost {
                    p.lost.set(p.focus.get());
                } else {
                    p.lost.set(false);
                }
                p.gained.set(false);
                p.focus.set(false);
            }
        }

        fn __focus(&self, n: usize, set_lost: bool) {
            if let Some(f) = self.focus.get(n) {
                f.focus.set(true);
                if set_lost {
                    if f.lost.get() {
                        // new focus same as old.
                        // reset lost + gained
                        f.lost.set(false);
                        f.gained.set(false);
                    } else {
                        f.gained.set(true);
                    }
                }
            }
        }

        // accumulate everything
        fn __accumulate(&self) {
            if let Some(container) = self.container {
                container.focus.focus.set(false);
                for p in self.focus.iter() {
                    if p.focus.get() {
                        container.focus.focus.set(true);
                        break;
                    }
                }
            }

            for (f, list) in &self.sub_container {
                let mut any_gained = false;
                let mut any_lost = false;
                let mut any_focused = false;

                for f in list {
                    any_gained |= f.gained.get();
                    any_lost |= f.lost.get();
                    any_focused |= f.focus.get();
                }

                f.focus.focus.set(any_focused);
                f.focus.lost.set(any_lost && !any_gained);
                f.focus.gained.set(any_gained && !any_lost);
            }
        }

        pub(super) fn reset_lost_gained(&self) {
            if let Some(container) = &self.container {
                container.focus.gained.set(false);
                container.focus.lost.set(false);
            }
            for p in self.focus.iter() {
                p.lost.set(false);
                p.gained.set(false);
            }
            for (p, _) in self.sub_container.iter() {
                p.focus.gained.set(false);
                p.focus.lost.set(false);
            }
        }

        pub(super) fn focus_init(&self) {
            if self.log.get() {
                debug!("first init");
            }
            self.__start_change(true);
            if let Some(n) = self.first_navigable(0) {
                if self.log.get() {
                    debug!("    -> focus {:?}", self.focus[n]);
                }
                self.__focus(n, true);
            }
            self.__accumulate();
        }

        pub(super) fn focus_no_lost(&self, n: usize) {
            if self.log.get() {
                debug!("focus_no_lost {}", n);
            }
            self.__start_change(false);
            if self.log.get() {
                debug!("    -> focus {:?}", self.focus[n]);
            }
            self.__focus(n, false);
            self.__accumulate();
        }

        pub(super) fn focus_idx(&self, n: usize) {
            if self.log.get() {
                debug!("focus_idx {}", n);
            }
            self.__start_change(true);
            if self.log.get() {
                debug!("    -> focus {:?}", self.focus[n]);
            }
            self.__focus(n, true);
            self.__accumulate();
        }

        pub(super) fn focus_at(&self, col: u16, row: u16) -> bool {
            if self.log.get() {
                debug!("focus_at {}:{}", col, row);
            }

            let pos = (col, row).into();

            let mut z_order = Vec::new();
            for (idx, area) in self.areas.iter().enumerate() {
                if area.contains(pos) {
                    if self.log.get() {
                        debug!("    area-match {:?}", self.focus[idx]);
                    }

                    // check for split areas
                    if !self.z_areas[idx].is_empty() {
                        for z_area in self.z_areas[idx].into_iter() {
                            // use all matching areas. might differ in z.
                            if z_area.contains(pos) {
                                if self.log.get() {
                                    debug!(
                                        "    add z-area-match {:?} -> {:?}",
                                        self.focus[idx], z_area
                                    );
                                }
                                z_order.push((idx, z_area.z));
                            }
                        }
                    } else {
                        if self.log.get() {
                            debug!("    add area-match");
                        }
                        z_order.push((idx, 0));
                    }
                }
            }
            // process in order, last is on top if more than one.
            if let Some((max_last, _)) = z_order.iter().max_by(|v, w| v.1.cmp(&w.1)) {
                if self.log.get() {
                    debug!("    -> focus {:?}", self.focus[*max_last]);
                }
                self.__start_change(true);
                self.__focus(*max_last, true);
                self.__accumulate();
                return true;
            }

            // look through the sub-containers
            let mut z_order = Vec::new();
            for (sub, focus) in &self.sub_container {
                if sub.area.contains(pos) {
                    if self.log.get() {
                        debug!("    container area-match {:?}", sub.focus);
                    }

                    // check for split areas
                    if !sub.z_area.is_empty() {
                        for z_area in sub.z_area.into_iter() {
                            // use all matching areas. might differ in z.
                            if z_area.contains(pos) {
                                if self.log.get() {
                                    debug!("    add z-area-match {:?} -> {:?}", sub.focus, z_area);
                                }
                                z_order.push((focus.first(), z_area.z));
                                break;
                            }
                        }
                    } else {
                        z_order.push((focus.first(), 0));
                    }

                    // process in order, last is on top if more than one.
                    if let Some((max_last, _)) = z_order.iter().max_by(|v, w| v.1.cmp(&w.1)) {
                        if self.log.get() {
                            debug!("    -> focus {:?}", max_last);
                        }
                        if let Some(max_last) = max_last {
                            if let Some(max_last) = self.index_of(max_last) {
                                if let Some(n) = self.first_navigable(max_last) {
                                    self.__start_change(true);
                                    self.__focus(n, true);
                                    self.__accumulate();
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            // main container
            // look through the sub-containers

            if let Some(con) = &self.container {
                let mut change = false;

                if con.area.contains(pos) {
                    if self.log.get() {
                        debug!("    main container area-match {:?}", con.focus);
                    }

                    // check for split areas
                    if !con.z_area.is_empty() {
                        for z_area in con.z_area.into_iter() {
                            // use all matching areas. might differ in z.
                            if z_area.contains(pos) {
                                if self.log.get() {
                                    debug!("    add z-area-match {:?} -> {:?}", con.focus, z_area);
                                }
                                change = true;
                                break;
                            }
                        }
                    } else {
                        change = true;
                    }

                    if change {
                        if let Some(n) = self.first_navigable(0) {
                            self.__start_change(true);
                            self.__focus(n, true);
                            self.__accumulate();
                            return true;
                        }
                    }
                }
            }

            false
        }

        pub(super) fn next(&self) -> bool {
            if self.log.get() {
                debug!("next");
            }
            self.__start_change(true);
            for (n, p) in self.focus.iter().enumerate() {
                if p.lost.get() {
                    if self.log.get() {
                        debug!("    current {:?}", p);
                    }
                    let n = self.next_navigable(n);
                    if self.log.get() {
                        debug!("    -> focus {:?}", self.focus[n]);
                    }
                    self.__focus(n, true);
                    self.__accumulate();
                    return true;
                }
            }
            if let Some(n) = self.first_navigable(0) {
                if self.log.get() {
                    debug!("    -> focus {:?}", self.focus[n]);
                }
                self.__focus(n, true);
                self.__accumulate();
                return true;
            }
            false
        }

        pub(super) fn prev(&self) -> bool {
            if self.log.get() {
                debug!("prev");
            }
            self.__start_change(true);
            for (i, p) in self.focus.iter().enumerate() {
                if p.lost.get() {
                    if self.log.get() {
                        debug!("    current {:?}", p);
                    }
                    let n = self.prev_navigable(i);
                    if self.log.get() {
                        debug!("    -> focus {:?}", self.focus[n]);
                    }
                    self.__focus(n, true);
                    self.__accumulate();
                    return true;
                }
            }
            if let Some(n) = self.first_navigable(0) {
                if self.log.get() {
                    debug!("    -> focus {:?}", self.focus[n]);
                }
                self.__focus(n, true);
                self.__accumulate();
                return true;
            }
            false
        }

        pub(super) fn focused(&self) -> Option<&'a FocusFlag> {
            self.focus.iter().find(|v| v.get()).copied()
        }

        pub(super) fn lost_focus(&self) -> Option<&'a FocusFlag> {
            self.focus.iter().find(|v| v.lost()).copied()
        }

        pub(super) fn gained_focus(&self) -> Option<&'a FocusFlag> {
            self.focus.iter().find(|v| v.gained()).copied()
        }

        fn len(&self) -> usize {
            self.focus.len()
        }

        // first navigable starting at n.
        fn first_navigable(&self, start: usize) -> Option<usize> {
            if self.log.get() {
                debug!("first navigable {:?}", self.focus[start].name);
            }
            for n in start..self.len() {
                if self.navigable[n] {
                    if self.log.get() {
                        debug!("first navigable -> {:?}", self.focus[n].name);
                    }
                    return Some(n);
                }
            }
            if self.log.get() {
                debug!("first navigable -> None");
            }
            return None;
        }

        fn next_navigable(&self, start: usize) -> usize {
            if self.log.get() {
                debug!("next navigable {:?}", self.focus[start].name);
            }

            let mut n = start;
            loop {
                n = if n + 1 < self.len() { n + 1 } else { 0 };
                if self.navigable[n] {
                    if self.log.get() {
                        debug!("next navigable -> {:?}", self.focus[n].name);
                    }
                    return n;
                }
                if n == start {
                    if self.log.get() {
                        debug!("next navigable -> same as start");
                    }
                    return n;
                }
            }
        }

        fn prev_navigable(&self, start: usize) -> usize {
            if self.log.get() {
                debug!("prev navigable {:?}", self.focus[start].name);
            }

            let mut n = start;
            loop {
                n = if n > 0 { n - 1 } else { self.len() - 1 };
                if self.navigable[n] {
                    if self.log.get() {
                        debug!("prev navigable -> {:?}", self.focus[n].name);
                    }
                    return n;
                }
                if n == start {
                    if self.log.get() {
                        debug!("prev navigable -> same as start");
                    }
                    return n;
                }
            }
        }
    }
}

impl<'a> HandleEvent<crossterm::event::Event, FocusKeys, Outcome> for Focus<'a> {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: FocusKeys) -> Outcome {
        match event {
            ct_event!(keycode press Tab) => {
                if self.core.log.get() {
                    debug!("Tab {:?}", self.focused());
                }
                self.next();
                if self.core.log.get() {
                    debug!("=> {:?}", self.focused());
                }
                Outcome::Changed
            }
            ct_event!(keycode press SHIFT-Tab) | ct_event!(keycode press SHIFT-BackTab) => {
                if self.core.log.get() {
                    debug!("BackTab {:?}", self.focused());
                }
                self.prev();
                if self.core.log.get() {
                    debug!("=> {:?}", self.focused());
                }
                Outcome::Changed
            }
            _ => self.handle(event, MouseOnly),
        }
    }
}

impl<'a> HandleEvent<crossterm::event::Event, MouseOnly, Outcome> for Focus<'a> {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: MouseOnly) -> Outcome {
        match event {
            ct_event!(mouse down Left for column, row) => {
                if self.core.log.get() {
                    debug!("mouse down {},{}", column, row);
                }
                if self.focus_at(*column, *row) {
                    if self.core.log.get() {
                        debug!("=> {:?}", self.focused());
                    }
                    Outcome::Changed
                } else {
                    if self.core.log.get() {
                        debug!("=> None");
                    }
                    self.reset_lost_gained();
                    Outcome::NotUsed
                }
            }
            _ => {
                self.reset_lost_gained();
                Outcome::NotUsed
            }
        }
    }
}

/// Handle all events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_focus(focus: &mut Focus<'_>, event: &crossterm::event::Event) -> Outcome {
    HandleEvent::handle(focus, event, FocusKeys)
}

/// Handle only mouse-events.
pub fn handle_mouse_focus(focus: &mut Focus<'_>, event: &crossterm::event::Event) -> Outcome {
    HandleEvent::handle(focus, event, MouseOnly)
}