teksilo-core 0.23.0

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
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
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! An intent sent from an overlay's content walks on from the widget the
//! overlay is attached to.
//!
//! An overlay's content is a detached root: its arena parent chain ends at
//! the content, so a walk up from a menu row, a popover's button or a field in
//! a dialog used to stop there, and only window-global actions could take its
//! intent. The walk now continues at the overlay's anchor, and up from there,
//! through every overlay the anchor itself sits in (a submenu's trigger is a
//! row of its parent menu). A scoped shortcut does not: a popup is a window of
//! its own for the keyboard, so focus in a popover anchored inside the
//! shortcut's scope is outside it, and the key goes to the popover's field.

use std::cell::RefCell;
use std::rc::Rc;

use teksilo_canvas::SizeProposal;

use crate::event::{EventResponse, Key, Modifiers, WidgetEvent};
use crate::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
use crate::shortcut::{KeyStroke, Shortcut};
use crate::test_widgets::{FillWidget, StackWidget};
use crate::window::NoopWindowOps;
use crate::{Action, BuildContext, Intent, LayoutContext, LayoutResponse, Widget, WidgetId};

use super::WidgetTree;

type Calls = Rc<RefCell<Vec<&'static str>>>;

/// The window's root: a scoped action for `test.save`, a scoped shortcut
/// (Ctrl+S) for it, and two children: the button overlays are attached to,
/// and an editor answering `test.save` itself.
#[derive(Debug)]
struct Root {
    calls: Calls,
    button: Rc<RefCell<Option<WidgetId>>>,
    editor: Rc<RefCell<Option<WidgetId>>>,
}

/// A focusable widget answering `test.save` with "editor".
#[derive(Debug)]
struct Editor {
    calls: Calls,
}

impl Widget for Editor {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let calls = self.calls.clone();
        ctx.register_action(Action::new("test.save").on_invoke(move |_, _| {
            calls.borrow_mut().push("editor");
        }));
        ctx.apply_self_handlers(crate::widget_builder::HandlerSet::new().focusable(true));
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(100.0, 20.0).into()
    }
}

impl Widget for Root {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let calls = self.calls.clone();
        ctx.register_action(Action::new("test.save").on_invoke(move |_, _| {
            calls.borrow_mut().push("root");
        }));
        ctx.register_shortcut(
            Shortcut::new("test.save")
                .primary(KeyStroke::ctrl(Key::S))
                .build(),
        );
        let button = ctx.add(FillWidget::new().focusable());
        *self.button.borrow_mut() = Some(button);
        let editor = ctx.add(Editor {
            calls: self.calls.clone(),
        });
        *self.editor.borrow_mut() = Some(editor);
        vec![button, editor]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(400.0, 300.0).into()
    }
}

/// A window with its root, the root's button and editor, and the calls
/// their actions made.
struct Window {
    tree: WidgetTree,
    button: WidgetId,
    editor: WidgetId,
    calls: Calls,
}

impl Window {
    fn new() -> Self {
        let calls = Calls::default();
        let button = Rc::new(RefCell::new(None));
        let editor = Rc::new(RefCell::new(None));
        let mut tree = WidgetTree::new();
        tree.add(Root {
            calls: calls.clone(),
            button: button.clone(),
            editor: editor.clone(),
        });
        tree.layout(SizeProposal::exact(400.0, 300.0));
        let button = button.borrow().expect("the root built its button");
        let editor = editor.borrow().expect("the root built its editor");
        Self {
            tree,
            button,
            editor,
            calls,
        }
    }

    /// Show `content`, a detached root, as an overlay attached to `anchor`.
    fn show(&mut self, content: WidgetId, anchor: WidgetId) {
        self.tree.show_overlay(OverlayRequest::new(
            content,
            anchor,
            OverlayPlacement::Below,
            DismissBehavior::Manual,
        ));
        self.tree.layout(SizeProposal::exact(400.0, 300.0));
    }

    /// A focusable field in a new popup attached to `anchor`, focused.
    fn focused_popup(&mut self, anchor: WidgetId) -> WidgetId {
        let field = self.tree.add(FillWidget::new().focusable());
        let content = self.tree.add(StackWidget::new().child(field));
        self.show(content, anchor);
        self.tree.focus(field);
        field
    }

    fn send_save_from_focus(&mut self) {
        self.tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.save"));
        });
    }

    fn calls(&self) -> Vec<&'static str> {
        self.calls.borrow().clone()
    }
}

#[test]
fn focus_in_an_overlay_reaches_a_scoped_action_on_the_root() {
    let mut window = Window::new();
    let button = window.button;
    window.focused_popup(button);
    window.send_save_from_focus();
    assert_eq!(window.calls(), ["root"]);
}

#[test]
fn the_walk_crosses_nested_overlays() {
    let mut window = Window::new();
    let button = window.button;
    // A menu attached to the button, and a submenu attached to a row of it.
    let row = window.tree.add(FillWidget::new().focusable());
    let menu = window.tree.add(StackWidget::new().child(row));
    window.show(menu, button);
    window.focused_popup(row);
    window.send_save_from_focus();
    assert_eq!(window.calls(), ["root"]);
}

/// Run `f` on a thread of its own and return what it returns, failing after
/// ten seconds rather than hanging: a walk that loops is a failure, not a
/// test run that never ends.
fn bounded<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
    let (done, result) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = done.send(f());
    });
    result
        .recv_timeout(std::time::Duration::from_secs(10))
        .expect("the walk did not end")
}

#[test]
fn an_overlay_anchored_inside_itself_ends_the_walk() {
    let (chain, field, content, calls) = bounded(|| {
        let mut window = Window::new();
        let field = window.tree.add(FillWidget::new().focusable());
        let content = window.tree.add(StackWidget::new().child(field));
        window.show(content, field);
        window.tree.focus(field);
        let chain = window.tree.intent_walk(field, &[]).0;
        window.send_save_from_focus();
        (chain, field, content, window.calls())
    });
    assert_eq!(chain, [field, content], "back at the field, the walk ends");
    assert!(calls.is_empty(), "nothing on the way takes it");
}

/// Two overlays each attached to a widget in the other: the walk crosses
/// from one to the other once, and ends when it comes back.
#[test]
fn two_overlays_attached_to_each_other_end_the_walk() {
    let (chain, ids, calls) = bounded(|| {
        let mut window = Window::new();
        let first_field = window.tree.add(FillWidget::new().focusable());
        let first = window.tree.add(StackWidget::new().child(first_field));
        let second_field = window.tree.add(FillWidget::new().focusable());
        let second = window.tree.add(StackWidget::new().child(second_field));
        window.show(first, second_field);
        window.show(second, first_field);
        window.tree.focus(first_field);
        let chain = window.tree.intent_walk(first_field, &[]).0;
        window.send_save_from_focus();
        (
            chain,
            [first_field, first, second_field, second],
            window.calls(),
        )
    });
    assert_eq!(chain, ids, "each overlay crossed once");
    assert!(calls.is_empty(), "the root is not on the way");
}

/// A row that, pressed with Enter, closes the overlay it is in and sends
/// `test.save` from itself, as a popover's button does.
fn closing_row(content: Rc<RefCell<Option<WidgetId>>>) -> impl Widget {
    use crate::widget_builder::WidgetBuilder;
    FillWidget::new()
        .focusable()
        .on_key(move |event, ctx| match event {
            WidgetEvent::KeyDown {
                key: Key::Enter, ..
            } => {
                let content = content.borrow().expect("the row is in an overlay");
                ctx.dismiss_overlay_by_content(content);
                ctx.send_intent(Intent::new("test.save"));
                EventResponse::Handled
            }
            _ => EventResponse::Ignored,
        })
}

#[test]
fn an_intent_sent_as_its_overlay_closes_still_reaches_the_anchor() {
    let mut window = Window::new();
    let button = window.button;
    let content_slot = Rc::new(RefCell::new(None));
    let row = window.tree.add(closing_row(content_slot.clone()));
    let content = window.tree.add(StackWidget::new().child(row));
    *content_slot.borrow_mut() = Some(content);
    window.show(content, button);
    window.tree.focus(row);

    window.tree.press_key(Key::Enter, Modifiers::NONE);

    assert!(
        window
            .tree
            .overlay_manager()
            .find_by_content(content)
            .is_none(),
        "the row closed its overlay"
    );
    assert_eq!(window.calls(), ["root"]);
}

/// A scoped shortcut does not cross from a popup to the widget it is
/// attached to, as a key pressed in a Qt popup (a window of its own) or a GTK
/// popover (whose entry hears it first) does not: a list's Delete must not
/// fire from the field of a rename popover attached to a row. Its intent,
/// sent from the same focus, still crosses.
#[test]
fn a_scoped_shortcut_does_not_cross_from_an_overlay_to_its_anchor() {
    let mut window = Window::new();
    let button = window.button;
    let field = window.focused_popup(button);
    window.tree.press_key(Key::S, Modifiers::COMMAND);
    assert!(window.calls().is_empty(), "the root's Ctrl+S stays outside");
    assert_eq!(window.tree.focused(), Some(field));
    window.send_save_from_focus();
    assert_eq!(window.calls(), ["root"], "the intent still crosses");
}

#[test]
fn a_scoped_shortcut_does_not_apply_to_an_overlay_attached_outside_its_scope() {
    let mut window = Window::new();
    // A second root, outside the first one's scope, with its own widget to
    // attach to.
    let elsewhere = window.tree.add(FillWidget::new());
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.focused_popup(elsewhere);
    window.tree.press_key(Key::S, Modifiers::COMMAND);
    assert!(window.calls().is_empty());
}

/// A menu row that, chosen with Enter, closes its menu the way `close`
/// says and sends `test.save` from focus, as a menu-bar row does.
fn row_sending_from_focus(close: fn(&mut crate::widget::EventContext)) -> impl Widget {
    use crate::widget_builder::WidgetBuilder;
    FillWidget::new()
        .focusable()
        .on_key(move |event, ctx| match event {
            WidgetEvent::KeyDown {
                key: Key::Enter, ..
            } => {
                close(ctx);
                ctx.send_intent_from_focus(Intent::new("test.save"));
                EventResponse::Handled
            }
            _ => EventResponse::Ignored,
        })
}

/// A menu attached to the window's button holding a row made by `row`,
/// opened over the editor (focus goes back there when the menu closes),
/// with focus on the row. Returns the row.
fn menu_over_the_editor(window: &mut Window, row: impl Widget + 'static) -> WidgetId {
    let (button, editor) = (window.button, window.editor);
    let row = window.tree.add(row);
    let menu = window.tree.add(StackWidget::new().child(row));
    window.tree.focus(editor);
    window.show(menu, button);
    window
        .tree
        .overlay_manager_mut()
        .set_top_focus_restore(editor);
    window.tree.focus(row);
    row
}

#[test]
fn a_rows_intent_from_focus_starts_where_closing_its_menu_put_focus() {
    let mut window = Window::new();
    menu_over_the_editor(
        &mut window,
        row_sending_from_focus(|ctx| ctx.dismiss_self_overlay_chain()),
    );
    window.tree.press_key(Key::Enter, Modifiers::NONE);
    assert_eq!(window.tree.focused(), Some(window.editor));
    assert_eq!(
        window.calls(),
        ["editor"],
        "the editor focus went back to answers, not the menu's button"
    );
}

#[test]
fn with_no_focus_left_a_rows_intent_from_focus_crosses_its_closed_menu() {
    let mut window = Window::new();
    let button = window.button;
    let row = window
        .tree
        .add(row_sending_from_focus(|ctx| ctx.dismiss_all_overlays()));
    let menu = window.tree.add(StackWidget::new().child(row));
    window.show(menu, button);
    window.tree.focus(row);
    window.tree.press_key(Key::Enter, Modifiers::NONE);
    assert_eq!(window.tree.focused(), None, "nothing handed focus back");
    assert_eq!(window.calls(), ["root"], "from the row, through the button");
}

/// A panel answering `test.save` with "panel", holding a focusable field whose
/// context-menu factory sends `test.save` and declines to show a menu.
#[derive(Debug)]
struct Panel {
    calls: Calls,
    field: Rc<RefCell<Option<WidgetId>>>,
}

impl Widget for Panel {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        use crate::widget_builder::WidgetBuilder;
        let calls = self.calls.clone();
        ctx.register_action(Action::new("test.save").on_invoke(move |_, _| {
            calls.borrow_mut().push("panel");
        }));
        let field = ctx.add(FillWidget::new().focusable().context_menu(|_, ctx| {
            ctx.send_intent(Intent::new("test.save"));
            None
        }));
        *self.field.borrow_mut() = Some(field);
        vec![field]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(100.0, 20.0).into()
    }
}

/// The window's root over a [`Panel`], answering `test.save` with "root".
#[derive(Debug)]
struct PanelRoot {
    calls: Calls,
    field: Rc<RefCell<Option<WidgetId>>>,
}

impl Widget for PanelRoot {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let calls = self.calls.clone();
        ctx.register_action(Action::new("test.save").on_invoke(move |_, _| {
            calls.borrow_mut().push("root");
        }));
        vec![ctx.add(Panel {
            calls: self.calls.clone(),
            field: self.field.clone(),
        })]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(400.0, 300.0).into()
    }
}

#[test]
fn the_intent_of_a_declining_context_menu_factory_starts_where_the_menu_was_asked_for() {
    let calls = Calls::default();
    let field = Rc::new(RefCell::new(None));
    let mut tree = WidgetTree::new();
    tree.add(PanelRoot {
        calls: calls.clone(),
        field: field.clone(),
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));
    tree.focus(field.borrow().expect("the panel built its field"));
    tree.press_key(Key::F10, Modifiers::SHIFT);
    assert_eq!(
        *calls.borrow(),
        ["panel"],
        "the walk starts at the field, so the panel around it answers first"
    );
}

// An open modal overlay (a dialog, a command palette) goes first: an intent
// sent inside it is offered to its own actions, then to the window-global
// actions registered inside it, and only what it leaves walks on to the page
// behind it, from the widget the modal is attached to, then to the page's
// global actions; what the window leaves goes to the application tree, as
// with a native dialog window, whose leftovers go to the window it blocks.
// Keys stop at the modal: of the window's shortcuts only those registered
// inside it apply, and a shortcut's intent is offered to nothing behind it.
// Once the modal has closed, an intent sent as it closed walks on as from any
// other overlay.

/// Registers a window-global action for `test.global` and a global shortcut
/// (Ctrl+G) for it, recording "global".
#[derive(Debug)]
struct GlobalCommands {
    calls: Calls,
}

impl Widget for GlobalCommands {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let calls = self.calls.clone();
        ctx.register_action_global(Action::new("test.global").on_invoke(move |_, _| {
            calls.borrow_mut().push("global");
        }));
        ctx.register_shortcut_global(
            Shortcut::new("test.global")
                .primary(KeyStroke::ctrl(Key::G))
                .build(),
        );
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(0.0, 0.0).into()
    }
}

impl Window {
    /// A focusable field in a new modal attached to `anchor`, focused.
    fn focused_modal(&mut self, anchor: WidgetId) -> (WidgetId, WidgetId) {
        let field = self.tree.add(FillWidget::new().focusable());
        let content = self.tree.add(StackWidget::new().child(field));
        self.tree.show_overlay(OverlayRequest::new(
            content,
            anchor,
            OverlayPlacement::Centered,
            DismissBehavior::Manual,
        ));
        self.tree.layout(SizeProposal::exact(400.0, 300.0));
        self.tree.focus(field);
        (content, field)
    }

    fn with_global_commands(mut self) -> Self {
        self.tree.add(GlobalCommands {
            calls: self.calls.clone(),
        });
        self.tree.layout(SizeProposal::exact(400.0, 300.0));
        self
    }
}

/// Nothing in the modal takes it: it walks on to the page, from the widget
/// the modal is attached to, while the modal is still open.
#[test]
fn an_intent_a_modal_leaves_walks_on_to_the_page_from_its_anchor() {
    let mut window = Window::new();
    let button = window.button;
    window.focused_modal(button);
    window.send_save_from_focus();
    assert_eq!(
        window.calls(),
        ["root"],
        "the root above the anchor, not the editor focus was on before"
    );
}

#[test]
fn a_popover_inside_a_modal_walks_on_through_the_modal_to_the_page() {
    let mut window = Window::new();
    let button = window.button;
    let (_, field) = window.focused_modal(button);
    window.focused_popup(field);
    window.send_save_from_focus();
    assert_eq!(window.calls(), ["root"]);
}

/// The modal goes first: an action inside it takes its intent, and the
/// page behind it never sees it.
#[test]
fn a_modals_own_action_takes_its_intent_before_the_page() {
    let mut window = Window::new();
    let button = window.button;
    let editor = window.tree.add(Editor {
        calls: window.calls.clone(),
    });
    let content = window.tree.add(StackWidget::new().child(editor));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.focus(editor);
    window.send_save_from_focus();
    assert_eq!(
        window.calls(),
        ["editor"],
        "the dialog's editor, not the root"
    );
}

/// A modal opened inside another walks on through both: the one below
/// answers before the page.
#[test]
fn an_intent_walks_on_through_nested_modals() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    let editor = window.tree.add(Editor {
        calls: window.calls.clone(),
    });
    let content = window.tree.add(StackWidget::new().child(editor));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.focused_modal(editor);
    window.send_save_from_focus();
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.global"));
        });
    assert_eq!(
        window.calls(),
        ["editor", "global"],
        "the lower dialog's editor, then the page's global action"
    );
}

/// A modal attached to a widget that is no longer up (a row of the menu
/// that opened it, closed since) walks on from the focus it gives back,
/// and with none from the content root; so does an intent sent as it
/// closes.
#[test]
fn a_modal_whose_anchor_is_gone_walks_on_from_the_focus_it_gives_back() {
    let mut window = Window::new();
    let editor = window.editor;
    let gone = window.tree.add(FillWidget::new());
    window.tree.set_dormant(gone);
    let field = window.tree.add(FillWidget::new().focusable());
    let content = window.tree.add(StackWidget::new().child(field));
    let modal = window.tree.show_overlay(OverlayRequest::new(
        content,
        gone,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window
        .tree
        .overlay_manager_mut()
        .set_top_focus_restore(editor);
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.focus(field);
    window.send_save_from_focus();
    assert_eq!(window.calls(), ["editor"], "from the focus it gives back");

    window.tree.dismiss_overlay(modal);
    window.tree.clear_focus();
    window.calls.borrow_mut().clear();
    let closing = window.tree.add(ClosingButton {
        send: |ctx| ctx.send_intent(Intent::new("test.save")),
    });
    let content = window.tree.add(StackWidget::new().child(closing));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        gone,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.click(closing);
    assert_eq!(
        window.calls(),
        ["root"],
        "closing, with no focus to give back: from the content root"
    );
}

#[test]
fn a_scoped_shortcut_outside_a_modal_does_not_apply_to_focus_in_it() {
    let mut window = Window::new();
    let button = window.button;
    window.focused_modal(button);
    window.tree.press_key(Key::S, Modifiers::COMMAND);
    assert!(window.calls().is_empty());
}

#[test]
fn a_modals_leftover_intent_reaches_the_pages_global_action() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    window.focused_modal(button);
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.global"));
        });
    assert_eq!(window.calls(), ["global"]);
}

#[test]
fn a_global_shortcut_of_the_page_does_not_fire_with_focus_in_a_modal() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    window.focused_modal(button);
    window.tree.press_key(Key::G, Modifiers::COMMAND);
    assert!(window.calls().is_empty());
}

/// With a modal open and nothing focused (focus cleared by a click on the
/// dialog's background, or the dialog took none), a key is judged as if focus
/// were in the topmost modal: the page's global shortcut stays out.
#[test]
fn a_global_shortcut_of_the_page_does_not_fire_under_a_modal_with_nothing_focused() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    window.focused_modal(button);
    window.tree.clear_focus();
    assert_eq!(window.tree.focused(), None);
    window.tree.press_key(Key::G, Modifiers::COMMAND);
    assert!(window.calls().is_empty());
}

/// A command sent from focus with nothing focused while a modal is up (a
/// native menu item, an app callback) starts in the modal, as if focus were
/// there, not at the page's root behind it: the modal's own action answers
/// first, and what it leaves goes on to the page.
#[test]
fn an_intent_from_focus_with_nothing_focused_under_a_modal_starts_in_it() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    let content = window.tree.add(Editor {
        calls: window.calls.clone(),
    });
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    assert_eq!(window.tree.focused(), None);
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.save"));
            ctx.send_intent_from_focus(Intent::new("test.global"));
        });
    assert_eq!(
        window.calls(),
        ["editor", "global"],
        "the modal's own action, not the root's; then the page's global"
    );
}

/// Registers a global shortcut (Ctrl+K) for `test.page`, which nothing
/// registering it takes.
#[derive(Debug)]
struct PageShortcut;

impl Widget for PageShortcut {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        ctx.register_shortcut_global(
            Shortcut::new("test.page")
                .primary(KeyStroke::ctrl(Key::K))
                .build(),
        );
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(0.0, 0.0).into()
    }
}

/// Registers a window-global action for `test.page`, recording "page".
#[derive(Debug)]
struct PageCommand {
    calls: Calls,
}

impl Widget for PageCommand {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let calls = self.calls.clone();
        ctx.register_action_global(Action::new("test.page").on_invoke(move |_, _| {
            calls.borrow_mut().push("page");
        }));
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(0.0, 0.0).into()
    }
}

/// Keys stop at the modal: a shortcut the modal registers whose intent only
/// the page takes runs nothing behind it, and its key reaches the focused
/// field instead, while the same intent sent by a button there does reach
/// the page.
#[test]
fn a_modals_shortcut_runs_nothing_behind_it() {
    let mut window = Window::new();
    window.tree.add(PageCommand {
        calls: window.calls.clone(),
    });
    let button = window.button;
    use crate::widget_builder::WidgetBuilder;
    let keys = Calls::default();
    let heard = keys.clone();
    let field = window
        .tree
        .add(FillWidget::new().focusable().on_key(move |event, _| {
            if let WidgetEvent::KeyDown { key: Key::K, .. } = event {
                heard.borrow_mut().push("field");
            }
            EventResponse::Handled
        }));
    let shortcut = window.tree.add(PageShortcut);
    let content = window
        .tree
        .add(StackWidget::new().child(field).child(shortcut));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.focus(field);
    window.tree.press_key(Key::K, Modifiers::COMMAND);
    assert!(window.calls().is_empty(), "the page's action did not run");
    assert_eq!(*keys.borrow(), ["field"], "the key went to the field");
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.page"));
        });
    assert_eq!(window.calls(), ["page"], "an intent sent there does");
}

/// ... and a global shortcut registered inside the modal applies, its intent
/// starting in the modal.
#[test]
fn a_modals_own_global_shortcut_fires_in_it_with_nothing_focused() {
    let mut window = Window::new();
    let button = window.button;
    let commands = window.tree.add(GlobalCommands {
        calls: window.calls.clone(),
    });
    let content = window.tree.add(StackWidget::new().child(commands));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    assert_eq!(window.tree.focused(), None);
    window.tree.press_key(Key::G, Modifiers::COMMAND);
    assert_eq!(window.calls(), ["global"]);
}

/// A widget that, tapped, closes the modal it is in and sends what `send`
/// sends, as a dialog's button or a command palette's row does.
struct ClosingButton {
    send: fn(&mut crate::widget::EventContext),
}

impl std::fmt::Debug for ClosingButton {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ClosingButton")
    }
}

impl Widget for ClosingButton {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let send = self.send;
        ctx.apply_self_handlers(
            crate::widget_builder::HandlerSet::new().on_tap(move |_, ctx| {
                ctx.dismiss_modal();
                send(ctx);
            }),
        );
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
        proposal.resolve(100.0, 20.0).into()
    }
}

impl Window {
    /// A modal attached to `anchor` holding a [`ClosingButton`] that sends
    /// what `send` sends, clicked. Focus is wherever it was before.
    fn click_closing_button_in_a_modal(
        &mut self,
        anchor: WidgetId,
        send: fn(&mut crate::widget::EventContext),
    ) {
        let closing = self.tree.add(ClosingButton { send });
        let content = self.tree.add(StackWidget::new().child(closing));
        self.tree.show_overlay(OverlayRequest::new(
            content,
            anchor,
            OverlayPlacement::Centered,
            DismissBehavior::Manual,
        ));
        self.tree.layout(SizeProposal::exact(400.0, 300.0));
        self.tree.click(closing);
        assert!(self.tree.active_overlays().is_empty(), "the modal closed");
    }
}

/// A modal is a barrier only while it is open: an intent sent as it closes
/// is dispatched once it has, and walks on from the widget it was attached
/// to, as a dialog's button that closes the dialog and then asks the page
/// for something expects.
#[test]
fn an_intent_sent_as_its_modal_closes_walks_on_from_its_anchor() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    window.click_closing_button_in_a_modal(button, |ctx| {
        ctx.send_intent(Intent::new("test.save"));
        ctx.send_intent(Intent::new("test.global"));
    });
    assert_eq!(
        window.calls(),
        ["root", "global"],
        "the root above the anchor, and the page's global action"
    );
}

/// Sent from focus as its modal closes with nothing focused before it opened
/// (a command palette opened from a shortcut with nothing focused), the
/// intent starts at the content root, as one with no source widget does: not
/// at the modal's anchor, which focus was never on.
#[test]
fn an_intent_from_focus_sent_as_its_modal_closes_with_nothing_focused_starts_at_the_root() {
    let mut window = Window::new().with_global_commands();
    let editor = window.editor;
    assert_eq!(window.tree.focused(), None);
    window.click_closing_button_in_a_modal(editor, |ctx| {
        ctx.send_intent_from_focus(Intent::new("test.save"));
        ctx.send_intent_from_focus(Intent::new("test.global"));
    });
    assert_eq!(window.tree.focused(), None);
    assert_eq!(window.calls(), ["root", "global"]);
}

/// With focus to give back, closing the modal puts it there and the intent
/// sent from focus starts there.
#[test]
fn an_intent_from_focus_sent_as_its_modal_closes_starts_at_the_focus_given_back() {
    let mut window = Window::new().with_global_commands();
    let (button, editor) = (window.button, window.editor);
    window.tree.focus(editor);
    let closing = window.tree.add(ClosingButton {
        send: |ctx| ctx.send_intent_from_focus(Intent::new("test.save")),
    });
    let content = window.tree.add(StackWidget::new().child(closing));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window
        .tree
        .overlay_manager_mut()
        .set_top_focus_restore(editor);
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.click(closing);
    assert_eq!(window.tree.focused(), Some(editor));
    assert_eq!(window.calls(), ["editor"]);
}

#[test]
fn global_actions_and_shortcuts_registered_inside_a_modal_apply_in_it() {
    let mut window = Window::new();
    let button = window.button;
    let field = window.tree.add(FillWidget::new().focusable());
    let commands = window.tree.add(GlobalCommands {
        calls: window.calls.clone(),
    });
    let content = window
        .tree
        .add(StackWidget::new().child(field).child(commands));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.tree.focus(field);
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.global"));
        });
    window.tree.press_key(Key::G, Modifiers::COMMAND);
    assert_eq!(window.calls(), ["global", "global"]);
}

/// An intent nothing in the window takes, the modal or the page behind it,
/// still goes to the application tree; one the page takes does not.
#[test]
fn a_modals_intent_nothing_in_the_window_takes_goes_to_the_application() {
    let mut window = Window::new().with_global_commands();
    let scope = crate::action::ApplicationScope::new();
    scope.replace(vec![
        ("test.app", None, None, None),
        ("test.global", None, None, None),
    ]);
    window.tree.set_application_scope(Some(scope));
    window.tree.set_records_unclaimed_intents(true);
    let button = window.button;
    window.focused_modal(button);
    window
        .tree
        .run_with_event_context(&mut NoopWindowOps, |ctx| {
            ctx.send_intent_from_focus(Intent::new("test.app"));
            ctx.send_intent_from_focus(Intent::new("test.global"));
        });
    assert_eq!(window.calls(), ["global"], "the page's global action");
    let kept: Vec<_> = window
        .tree
        .take_unclaimed_intents()
        .into_iter()
        .map(|intent| intent.name)
        .collect();
    assert_eq!(kept, ["test.app"]);
}

/// An intent sent from outside the modal (programmatically: no input reaches
/// the page while it is up) is the page's and reaches its global actions, as
/// before.
#[test]
fn an_intent_sent_from_outside_a_modal_still_reaches_the_page_globals() {
    let mut window = Window::new().with_global_commands();
    let button = window.button;
    window.focused_modal(button);
    let page = window.tree.roots()[0];
    window
        .tree
        .run_with_event_context_from(Some(page), &mut NoopWindowOps, |ctx| {
            ctx.send_intent(Intent::new("test.global"));
        });
    assert_eq!(window.calls(), ["global"]);
}

#[test]
fn a_popover_attached_inside_a_modal_reaches_the_modals_own_actions() {
    let mut window = Window::new();
    let button = window.button;
    let editor = window.tree.add(Editor {
        calls: window.calls.clone(),
    });
    let content = window.tree.add(StackWidget::new().child(editor));
    window.tree.show_overlay(OverlayRequest::new(
        content,
        button,
        OverlayPlacement::Centered,
        DismissBehavior::Manual,
    ));
    window.tree.layout(SizeProposal::exact(400.0, 300.0));
    window.focused_popup(editor);
    window.send_save_from_focus();
    assert_eq!(
        window.calls(),
        ["editor"],
        "the dialog's editor, not the root"
    );
}