egui_stack 0.30.2

Docking system for egui, continuing egui_dock
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
//! [`LayoutArea`]: a [`Layout`] drawn in a [`Ui`], with sashes between its
//! zones.

use std::collections::HashMap;

use egui::{
    Color32, CornerRadius, CursorIcon, EventFilter, Id, Key, LayerId, Order, Painter, Pos2, Rect,
    Response, Sense, Shadow, Stroke, StrokeKind, Ui, UiBuilder, WidgetInfo,
    accesskit::{Action, ActionData, Orientation, Role},
};

use super::fold::{
    self, Dismiss, Flyout, FlyoutPaint, Inside, StripAction, StripOrientation, StripPaint,
    StripTitle,
};
use super::solve::{along, span};
use super::{
    Dir, Fold, Laid, LaidZone, Layout, LayoutEvent, Shown, Solve, Zone, ZoneKind, ZoneName,
};
use crate::{Labels, PartState, SeparatorAxis};

/// How a [`LayoutArea`] looks and moves: sizes and colours its
/// [`LayoutPainter`] reads, and the keyboard steps of its sashes.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct LayoutStyle {
    /// A folded zone's strip breadth. By default 24 points.
    pub strip: f32,
    /// A sash's drawn thickness. By default 1 point.
    pub sash_width: f32,
    /// A sash's thickness for the pointer, centred on the boundary. By
    /// default 6 points.
    pub sash_grab: f32,
    /// A sash at rest. By default transparent: the boundary shows on hover.
    pub sash_idle: Color32,
    /// A sash hovered or focused.
    pub sash_hovered: Color32,
    /// A sash dragged.
    pub sash_dragged: Color32,
    /// What an arrow key moves a focused sash by, in points. By default 16.
    pub key_step: f32,
    /// What an arrow key with Shift moves a focused sash by. By default 48.
    pub large_key_step: f32,
    /// A strip's background.
    pub strip_fill: Color32,
    /// The line between a strip and its neighbours.
    pub strip_stroke: Stroke,
    /// A strip's grip, the button that unfolds or folds its zone.
    pub grip: Color32,
    /// A strip's grip hovered.
    pub grip_hovered: Color32,
    /// The background of a zone lying over its neighbour, and of a flyout.
    pub flyout_fill: Color32,
    /// Their border.
    pub flyout_stroke: Stroke,
    /// Their shadow.
    pub flyout_shadow: Shadow,
    /// A flyout's breadth before the user resizes it. By default 240.
    pub flyout_size: f32,
    /// How near, in points, a dragged sash catches a snap target: its
    /// zone's default size, or another sash's line. By default 8; 0 turns
    /// snapping off. Alt (Option on macOS) suspends it during a drag.
    pub snap: f32,
    /// The guide line showing what a dragged sash caught.
    pub snap_guide: Stroke,
    /// Whether a folded zone's strip edge facing its neighbour drags the
    /// zone out of its strip. The edge's band is [`sash_grab`](Self::sash_grab)
    /// thick, across the edge, or just outside a strip narrower than twice
    /// that; a click on it acts like the grip's. By default `true`.
    pub strip_drag: bool,
    /// The title a folded zone's strip shows after its grip, broadening
    /// the strip to fit it ([`StripTitle`]). By default `None`: the strip
    /// shows its grip and what [`ZoneViewer::strip`] draws.
    pub strip_title: Option<StripTitle>,
}

impl Default for LayoutStyle {
    fn default() -> Self {
        Self::from_egui(&egui::Style::default())
    }
}

impl LayoutStyle {
    /// A style drawn from egui's: the sash takes the widgets' colours.
    pub fn from_egui(style: &egui::Style) -> Self {
        let widgets = &style.visuals.widgets;
        Self {
            strip: 24.0,
            sash_width: 1.0,
            sash_grab: 6.0,
            sash_idle: Color32::TRANSPARENT,
            sash_hovered: widgets.hovered.bg_stroke.color,
            sash_dragged: widgets.active.bg_stroke.color,
            key_step: 16.0,
            large_key_step: 48.0,
            strip_fill: style.visuals.faint_bg_color,
            strip_stroke: widgets.noninteractive.bg_stroke,
            grip: widgets.noninteractive.fg_stroke.color,
            grip_hovered: widgets.hovered.fg_stroke.color,
            flyout_fill: style.visuals.panel_fill,
            flyout_stroke: style.visuals.window_stroke,
            flyout_shadow: style.visuals.popup_shadow,
            flyout_size: 240.0,
            snap: 8.0,
            snap_guide: Stroke::new(1.0, style.visuals.selection.stroke.color),
            strip_drag: true,
            strip_title: None,
        }
    }
}

/// A sash to paint: the boundary between two zones.
#[derive(Debug)]
#[non_exhaustive]
pub struct SashPaint<'a> {
    /// The sash, [`LayoutStyle::sash_width`] thick.
    pub rect: Rect,
    /// Which way it runs.
    pub axis: SeparatorAxis,
    /// Its state: hovered, focused, dragged.
    pub state: PartState,
    /// The zone it resizes.
    pub zone: &'a ZoneName,
    /// The layout's style.
    pub style: &'a LayoutStyle,
}

/// What a dragged sash, or a strip's edge, caught: the reason a guide line
/// shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SnapKind {
    /// The zone's default size.
    Default,
    /// The line of another sash running the same way.
    Sash,
    /// The zone folds to its strip on release.
    Fold,
    /// The folded zone unfolds on release, at the guide.
    Unfold,
}

/// A guide line to paint while a sash is dragged.
#[derive(Debug)]
#[non_exhaustive]
pub struct SnapGuidePaint<'a> {
    /// The line's two ends.
    pub line: [Pos2; 2],
    /// Which way it runs.
    pub axis: SeparatorAxis,
    /// What was caught.
    pub kind: SnapKind,
    /// The zone being resized.
    pub zone: &'a ZoneName,
    /// The layout's style.
    pub style: &'a LayoutStyle,
}

/// Paints a layout's parts. Every method has a default drawn from
/// [`LayoutStyle`]; a host overrides the ones it styles itself.
pub trait LayoutPainter {
    /// A sash between two zones.
    fn sash(&self, painter: &Painter, sash: &SashPaint<'_>) {
        let style = sash.style;
        let color = if sash.state.contains(PartState::DRAGGED) {
            style.sash_dragged
        } else if sash.state.contains(PartState::HOVERED) || sash.state.contains(PartState::FOCUSED)
        {
            style.sash_hovered
        } else {
            style.sash_idle
        };
        painter.rect_filled(sash.rect, CornerRadius::ZERO, color);
    }

    /// A folded zone's strip, with its grip (painted before the
    /// [`ZoneViewer::strip`] content).
    fn strip(&self, painter: &Painter, strip: &StripPaint<'_>) {
        let style = strip.style;
        painter.rect_filled(strip.rect, CornerRadius::ZERO, style.strip_fill);
        painter.rect_stroke(
            strip.rect,
            CornerRadius::ZERO,
            style.strip_stroke,
            StrokeKind::Inside,
        );
        let color = if strip.grip_state.contains(PartState::HOVERED)
            || strip.grip_state.contains(PartState::FOCUSED)
        {
            style.grip_hovered
        } else {
            style.grip
        };
        // Three dots across the strip.
        let centre = strip.grip.center();
        let gap = egui::vec2(4.0, 0.0);
        let gap = if strip.axis == SeparatorAxis::Vertical {
            gap.yx()
        } else {
            gap
        };
        for offset in [-1.0, 0.0, 1.0] {
            painter.circle_filled(centre + gap * offset, 1.5, color);
        }
    }

    /// The guide line of a dragged sash that caught a snap target, or of a
    /// fold or unfold to come on release; painted above everything.
    fn snap_guide(&self, painter: &Painter, guide: &SnapGuidePaint<'_>) {
        painter.line_segment(guide.line, guide.style.snap_guide);
    }

    /// The free edge of a zone lying over its neighbour, the edge that
    /// resizes it, painted above the zone's content. `edge.rect` is
    /// [`LayoutStyle::sash_width`] thick, centred on the edge; `edge.state`
    /// tells whether it is hovered or dragged, as a sash's. By default
    /// nothing: the zone's frame ([`LayoutPainter::flyout_frame`]) is its
    /// only border. A host that styles its sashes' hover and drag can
    /// paint the same line here, so both kinds of edge look alike.
    fn over_edge(&self, painter: &Painter, edge: &SashPaint<'_>) {
        let _ = (painter, edge);
    }

    /// The frame of a zone lying over its neighbour, or of a flyout: shadow,
    /// background and border, painted before its content.
    fn flyout_frame(&self, painter: &Painter, frame: &FlyoutPaint<'_>) {
        let style = frame.style;
        painter.add(style.flyout_shadow.as_shape(frame.rect, CornerRadius::ZERO));
        painter.rect(
            frame.rect,
            CornerRadius::ZERO,
            style.flyout_fill,
            style.flyout_stroke,
            StrokeKind::Inside,
        );
    }
}

/// The painter a [`LayoutArea`] uses unless given one: every default of
/// [`LayoutPainter`].
#[derive(Clone, Copy, Debug, Default)]
pub struct DefaultLayoutPainter;

impl LayoutPainter for DefaultLayoutPainter {}

/// What the application draws in a [`LayoutArea`].
pub trait ZoneViewer {
    /// A leaf zone's content, in its rect; also while it lies over its
    /// neighbour.
    fn ui(&mut self, ui: &mut Ui, zone: &ZoneName);

    /// A folded zone's strip, after the painter's background and grip: the
    /// application's icons, say. The `Ui` is the strip less its grip. A
    /// click on the strip that none of these widgets takes acts like the
    /// grip's, so a strip left empty is a button as a whole. By default
    /// nothing.
    fn strip(&mut self, ui: &mut Ui, zone: &ZoneName) {
        let _ = (ui, zone);
    }

    /// Called after a folded zone's strip is shown, every frame, as
    /// [`TabViewer::on_tab_button`](crate::TabViewer::on_tab_button) is
    /// after a tab button: `response` covers the strip and its grip, for a
    /// tooltip or a context menu. When the strip is clicked this frame, the
    /// returned [`StripAction`] says what the click does: by default
    /// ([`StripAction::Default`]) a zone the user folded unfolds, a zone the
    /// solver folded short of room ([`Shown::AutoFolded`]) opens over its
    /// neighbour, and a zone lying over closes. The click is reported
    /// ([`LayoutEvent::StripClicked`]) whatever the action.
    ///
    /// The hook lives here, not on `TabViewer`: strips belong to the layout,
    /// which draws them with this viewer and knows no tabs.
    fn on_strip(
        &mut self,
        _zone: &ZoneName,
        _shown: Shown,
        _response: &egui::Response,
    ) -> StripAction {
        StripAction::Default
    }

    /// A folded zone's strip title, when [`LayoutStyle::strip_title`] is
    /// set: the application draws it in `rect`, the strip less its grip and
    /// the title's padding, reading the way `orientation` says, and returns
    /// `true`; the layout keeps the strip's background, grip, clicks, drag
    /// and drops. The `Ui` is clipped to `rect`; a widget that senses
    /// clicks there takes them from the strip. Painted before
    /// [`ZoneViewer::strip`]. By default `false`: the layout draws the
    /// zone's title ([`ZoneViewer::title`]) and icon
    /// ([`ZoneViewer::strip_icon`]).
    fn strip_title(
        &mut self,
        ui: &mut Ui,
        zone: &ZoneName,
        rect: Rect,
        orientation: StripOrientation,
    ) -> bool {
        let _ = (ui, zone, rect, orientation);
        false
    }

    /// The icon the built-in strip title shows before the zone's title,
    /// upright, in the title's font: a glyph of an icon font, say. Asked
    /// each frame while [`LayoutStyle::strip_title`] is set, for every
    /// zone that folds to a strip, so that the strips fit the widest. By
    /// default none.
    fn strip_icon(&mut self, zone: &ZoneName) -> Option<String> {
        let _ = zone;
        None
    }

    /// The content of the [`Flyout`] given to [`LayoutArea::flyout`]. By
    /// default nothing.
    fn flyout(&mut self, ui: &mut Ui, flyout: &Flyout) {
        let _ = (ui, flyout);
    }

    /// A zone's title, as screen readers and tests name it: its leaf's
    /// pane, and `{zone}` in the [`Labels`] of its sash and grip
    /// ([`LayoutArea::labels`]). Translate it here. By default the zone's
    /// name.
    fn title(&mut self, zone: &ZoneName) -> String {
        zone.0.clone()
    }

    /// A flyout's title: `{flyout}` in [`Labels::resize_flyout`]. By
    /// default its key.
    fn flyout_title(&mut self, flyout: &Flyout) -> String {
        flyout.key.clone()
    }
}

/// The accessible names of a layout's parts this frame: the [`Labels`]
/// with each zone's title.
pub(super) struct Names<'a> {
    labels: &'a Labels,
    titles: HashMap<ZoneName, String>,
}

impl<'a> Names<'a> {
    fn new(labels: &'a Labels, laid: &Laid, viewer: &mut dyn ZoneViewer) -> Self {
        let titles = laid
            .zones
            .iter()
            .map(|zone| (zone.name.clone(), viewer.title(&zone.name)))
            .collect();
        Self { labels, titles }
    }

    /// The zone's title.
    pub(super) fn title<'s>(&'s self, zone: &'s ZoneName) -> &'s str {
        self.titles.get(zone).map_or(&zone.0, String::as_str)
    }

    fn with_zone(&self, template: &str, zone: &ZoneName) -> String {
        template.replace("{zone}", self.title(zone))
    }

    pub(super) fn resize(&self, zone: &ZoneName) -> String {
        self.with_zone(&self.labels.resize_zone, zone)
    }

    pub(super) fn fold(&self, zone: &ZoneName) -> String {
        self.with_zone(&self.labels.fold_zone, zone)
    }

    pub(super) fn unfold(&self, zone: &ZoneName) -> String {
        self.with_zone(&self.labels.unfold_zone, zone)
    }

    pub(super) fn resize_flyout(&self, title: &str) -> String {
        self.labels.resize_flyout.replace("{flyout}", title)
    }
}

/// Draws a [`Layout`] in a [`Ui`]: solves it in the `Ui`'s rect, calls the
/// [`ZoneViewer`] for each leaf zone shown, and puts a sash between
/// neighbouring zones.
///
/// A sash resizes the zone on its side away from the zone that takes the
/// rest (the one that grows, else the last one): dragged, or focused and
/// moved with the arrow keys (by [`LayoutStyle::key_step`], further with
/// Shift). It honours the zone's least and largest sizes and the least size
/// of the zone that takes the rest. Enter or a double click gives the zone
/// back its default size. Each sash is a splitter for assistive technology
/// ("Resize left"), whose value is the zone's size, and each leaf zone a
/// pane named after it. The names are the zones' titles
/// ([`ZoneViewer::title`]) in the [`Labels`] given to [`LayoutArea::labels`].
///
/// A dragged sash snaps to its zone's default size and to the line of
/// another sash running the same way, within [`LayoutStyle::snap`], with a
/// guide line ([`LayoutPainter::snap_guide`]); Alt suspends it. A zone whose
/// least size is its largest has no sash. A folded zone's strip edge facing
/// its neighbour drags the zone out of its strip.
///
/// The user's changes are written to the layout's [`ZoneState`](super::ZoneState)
/// at once and listed in the returned [`Laid::events`].
///
/// ```
/// use egui_stack::layout::{Content, Dir, Layout, LayoutArea, Size, Zone, ZoneName, ZoneViewer};
///
/// struct Viewer;
/// impl ZoneViewer for Viewer {
///     fn ui(&mut self, ui: &mut egui::Ui, zone: &ZoneName) {
///         ui.label(zone.to_string());
///     }
/// }
///
/// let mut layout = Layout::new(Zone::split(
///     "root",
///     Dir::Horizontal,
///     vec![
///         Zone::leaf("side", Content::App).with(|c| c.default = Some(Size::Points(200.0))),
///         Zone::leaf("main", Content::App).with(|c| c.grow = true),
///     ],
/// ));
/// # egui::__run_test_ui(|ui| {
/// let laid = LayoutArea::new(&mut layout).show_inside(ui, &mut Viewer);
/// # let _ = laid;
/// # });
/// ```
pub struct LayoutArea<'a> {
    layout: &'a mut Layout,
    id: Id,
    style: Option<LayoutStyle>,
    painter: &'a dyn LayoutPainter,
    flyout: Option<Flyout>,
    flyout_dismiss: Dismiss,
    over_dismiss: Dismiss,
    inside: Option<Inside<'a>>,
    labels: Labels,
    sublayer_of: Option<LayerId>,
}

impl<'a> LayoutArea<'a> {
    /// An area drawing `layout`.
    pub fn new(layout: &'a mut Layout) -> Self {
        Self {
            layout,
            id: Id::unique("egui_stack::LayoutArea"),
            style: None,
            painter: &DefaultLayoutPainter,
            flyout: None,
            flyout_dismiss: Dismiss::ANY,
            over_dismiss: Dismiss::ANY,
            inside: None,
            labels: Labels::ENGLISH,
            sublayer_of: None,
        }
    }

    /// Sets the area's id, which keeps its sashes' state. Two layouts shown
    /// at once need different ids.
    #[inline]
    pub fn id(mut self, id: Id) -> Self {
        self.id = id;
        self
    }

    /// Sets the style; by default [`LayoutStyle::from_egui`] of the `Ui`'s.
    #[inline]
    pub fn style(mut self, style: LayoutStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Sets the painter; by default [`DefaultLayoutPainter`].
    #[inline]
    pub fn painter(mut self, painter: &'a dyn LayoutPainter) -> Self {
        self.painter = painter;
        self
    }

    /// Sets the accessible names of the sashes, grips and flyout edge
    /// ([`Labels::resize_zone`], [`unfold_zone`](Labels::unfold_zone),
    /// [`fold_zone`](Labels::fold_zone),
    /// [`resize_flyout`](Labels::resize_flyout)), to translate them. By
    /// default [`Labels::ENGLISH`].
    #[inline]
    pub fn labels(mut self, labels: Labels) -> Self {
        self.labels = labels;
        self
    }

    /// Shows a flyout: an item of a folded zone ([`Flyout::zone`]) over its
    /// neighbour, next to the zone's strip, drawn by
    /// [`ZoneViewer::flyout`]. The application keeps it open by giving it
    /// every frame, and drops it on [`LayoutEvent::FlyoutClosed`] (Escape, a
    /// click outside it, the strip's grip, or the zone unfolding; the first
    /// two as [`Self::flyout_dismiss`] says).
    #[inline]
    pub fn flyout(mut self, flyout: Option<Flyout>) -> Self {
        self.flyout = flyout;
        self
    }

    /// Sets what closes the flyout besides its strip's grip and its zone
    /// unfolding; by default [`Dismiss::ANY`], a press outside it or
    /// Escape.
    #[inline]
    pub fn flyout_dismiss(mut self, dismiss: Dismiss) -> Self {
        self.flyout_dismiss = dismiss;
        self
    }

    /// Sets what folds back a zone lying over its neighbour
    /// ([`ZoneState::over`](super::ZoneState::over)) besides its strip's
    /// grip; by default [`Dismiss::ANY`], a press outside it or Escape.
    /// [`Dismiss::NEVER`] makes lying over a lasting placement.
    #[inline]
    pub fn over_dismiss(mut self, dismiss: Dismiss) -> Self {
        self.over_dismiss = dismiss;
        self
    }

    /// Lets the host count a press outside the flyout's or a lying-over
    /// zone's rect as inside it: `inside` gets the press and the egui
    /// layer on top there, and says whether it is inside. A combo box's
    /// list or a context menu opened from the flyout, or the host's own
    /// overlays, are such layers. By default no press outside is inside.
    #[inline]
    pub fn inside(mut self, inside: Inside<'a>) -> Self {
        self.inside = Some(inside);
        self
    }

    /// Draws the zones lying over their neighbour and the flyout as
    /// sublayers of `parent` ([`egui::Context::set_sublayer`]), a layer in
    /// the foreground order: egui then keeps them directly above `parent`,
    /// whatever was shown or clicked last. A host keeping a fixed z-order
    /// gives a layer it holds under its own overlays, so that the
    /// overlays stay above the zones lying over and the flyout. By
    /// default they are plain foreground areas, raised when clicked.
    #[inline]
    pub fn sublayer_of(mut self, parent: LayerId) -> Self {
        self.sublayer_of = Some(parent);
        self
    }

    /// Draws the layout in the `Ui`'s whole rect, and returns where each
    /// zone went with what the user changed.
    pub fn show_inside(self, ui: &mut Ui, viewer: &mut dyn ZoneViewer) -> Laid {
        let mut style = self
            .style
            .unwrap_or_else(|| LayoutStyle::from_egui(ui.style()));
        if let Some(title) = &style.strip_title {
            let mut icons = Vec::new();
            self.layout.root.visit(&mut |zone| {
                if zone.constraints.fold == Fold::ToStrip
                    && let Some(icon) = viewer.strip_icon(&zone.name)
                {
                    icons.push(icon);
                }
            });
            style.strip = style.strip.max(title.breadth(ui.painter(), &icons));
        }
        let rect = ui.max_rect();
        let content_id = self.id.with("content");
        let content: HashMap<ZoneName, f32> = ui
            .ctx()
            .data(|d| d.get_temp(content_id))
            .unwrap_or_default();
        let solve = Solve {
            strip: style.strip,
            content,
        };
        let laid = self.layout.solve(rect, &solve);

        // The sashes' moves first, read from where they were last frame, so
        // that the zones are drawn at the size their sash shows this frame.
        let mut events = Vec::new();
        let mut guides = HashMap::new();
        let moved = sashes(&self.layout.root, &laid);
        for sash in &moved {
            if let Some(guide) =
                sash_input(ui, self.id, self.layout, sash, &moved, &style, &mut events)
            {
                guides.insert(sash.zone.clone(), guide);
            }
        }
        let laid = if events.is_empty() {
            laid
        } else {
            self.layout.solve(rect, &solve)
        };
        let names = Names::new(&self.labels, &laid, viewer);

        // The zones' contents, then the sashes over them.
        let mut asked = HashMap::new();
        draw_zones(
            ui,
            self.id,
            &self.layout.root,
            None,
            &laid,
            &names,
            viewer,
            &mut asked,
        );
        ui.ctx().data_mut(|d| d.insert_temp(content_id, asked));

        let resized = events.len();
        let painter = self.painter;
        fold::strips(
            ui,
            self.id,
            self.layout,
            &laid,
            &style,
            painter,
            viewer,
            &names,
            self.flyout.as_ref(),
            &mut events,
        );
        fold::overs(
            ui,
            self.id,
            self.layout,
            &laid,
            &style,
            painter,
            viewer,
            &names,
            (self.over_dismiss, self.inside),
            self.sublayer_of,
            &mut events,
        );
        let flyout_rect = self.flyout.as_ref().and_then(|flyout| {
            fold::flyout(
                ui,
                self.id,
                self.layout,
                &laid,
                flyout,
                &style,
                painter,
                viewer,
                &names,
                (self.flyout_dismiss, self.inside),
                self.sublayer_of,
                &mut events,
            )
        });
        // Painted from the same layout as the zones.
        for sash in &sashes(&self.layout.root, &laid) {
            sash_ui(
                ui,
                self.id,
                sash,
                guides.remove(&sash.zone),
                &style,
                painter,
                &names,
            );
        }

        if !events.is_empty() {
            ui.ctx().request_repaint();
        }
        let mut laid = if events.len() == resized {
            laid
        } else {
            self.layout.solve(rect, &solve)
        };
        auto_folds(ui, self.id, self.layout, &laid, &mut events);
        laid.events = events;
        laid.flyout = flyout_rect;
        laid
    }
}

/// Draws the leaf zones under `zone` that are laid and open.
#[expect(
    clippy::too_many_arguments,
    reason = "the area's parts, borrowed apart"
)]
fn draw_zones(
    ui: &mut Ui,
    id: Id,
    zone: &Zone,
    parent: Option<Dir>,
    laid: &Laid,
    names: &Names<'_>,
    viewer: &mut dyn ZoneViewer,
    asked: &mut HashMap<ZoneName, f32>,
) {
    let Some(at) = laid.get(&zone.name.0) else {
        return;
    };
    match &zone.kind {
        ZoneKind::Split { dir, children } => {
            if at.shown == Shown::Open {
                for child in children {
                    draw_zones(ui, id, child, Some(*dir), laid, names, viewer, asked);
                }
            }
        }
        ZoneKind::Leaf { .. } => {
            if at.shown == Shown::Open {
                let size = zone_ui(ui, id, at, names, viewer);
                if zone.constraints.fit_content
                    && let Some(dir) = parent
                {
                    asked.insert(zone.name.clone(), along(dir, size));
                }
            }
        }
    }
}

/// Draws one zone's content in its rect, leaves as panes named after their
/// title.
pub(super) fn zone_ui_at(
    ui: &mut Ui,
    id: Id,
    zone: &Zone,
    laid: &Laid,
    names: &Names<'_>,
    viewer: &mut dyn ZoneViewer,
) {
    let mut asked = HashMap::new();
    match &zone.kind {
        ZoneKind::Leaf { .. } => {
            if let Some(at) = laid.get(&zone.name.0) {
                zone_ui(ui, id, at, names, viewer);
            }
        }
        ZoneKind::Split { dir, children } => {
            for child in children {
                draw_zones(ui, id, child, Some(*dir), laid, names, viewer, &mut asked);
            }
        }
    }
}

/// Draws one leaf zone's content in its rect, as a pane named after its
/// title: the content's `Ui` is the pane, so assistive technology finds the
/// zone's controls inside it. Returns the size its content took.
pub(super) fn zone_ui(
    ui: &mut Ui,
    id: Id,
    at: &LaidZone,
    names: &Names<'_>,
    viewer: &mut dyn ZoneViewer,
) -> egui::Vec2 {
    let zone_id = id.with(("zone", &at.name.0));
    let mut child = ui.new_child(
        UiBuilder::new()
            .id_salt(zone_id)
            .max_rect(at.rect)
            .layout(*ui.layout())
            .accessibility_role(Role::Pane)
            .accessibility_label(names.title(&at.name)),
    );
    child.set_clip_rect(at.rect.intersect(ui.clip_rect()));
    // A `Ui` gets no bounds of its own: the pane covers the zone's rect.
    set_bounds(ui.ctx(), child.unique_id(), at.rect);
    viewer.ui(&mut child, &at.name);
    child.min_rect().size()
}

/// Sets the bounds of the AccessKit node `id` (a `Ui` given a role, which egui leaves without
/// bounds) to `rect`.
pub(super) fn set_bounds(ctx: &egui::Context, id: Id, rect: Rect) {
    ctx.accesskit_node_builder(id, |node| {
        node.set_bounds(egui::accesskit::Rect {
            x0: rect.min.x.into(),
            y0: rect.min.y.into(),
            x1: rect.max.x.into(),
            y1: rect.max.y.into(),
        });
    });
}

/// A sash between two neighbouring open zones of a split.
pub(super) struct Sash {
    dir: Dir,
    /// The boundary, across the split's breadth.
    rect: Rect,
    /// The zone it resizes.
    zone: ZoneName,
    /// Whether the zone is before the boundary (it grows as the sash moves
    /// right or down).
    before: bool,
    /// The zone's size now, and its bounds.
    size: f32,
    least: f32,
    most: f32,
    /// The zone's default size in points, within its bounds.
    default: Option<f32>,
}

impl Sash {
    /// The boundary's position along the split's axis.
    fn boundary(&self) -> f32 {
        along(self.dir, self.rect.min.to_vec2())
    }

    /// The boundary where it would be with the zone at `size`.
    fn line_at(&self, size: f32) -> Rect {
        let sign = if self.before { 1.0 } else { -1.0 };
        let shift = sign * (size - self.size);
        match self.dir {
            Dir::Horizontal => self.rect.translate(egui::vec2(shift, 0.0)),
            Dir::Vertical => self.rect.translate(egui::vec2(0.0, shift)),
        }
    }

    /// The zone's size with the boundary at `boundary`.
    fn size_at(&self, boundary: f32) -> f32 {
        let sign = if self.before { 1.0 } else { -1.0 };
        self.size + sign * (boundary - self.boundary())
    }
}

/// The sashes of every split laid open under `zone`. A zone whose least
/// size is its largest has none: nothing to resize.
fn sashes(zone: &Zone, laid: &Laid) -> Vec<Sash> {
    let mut out = Vec::new();
    zone.visit(&mut |zone| {
        let ZoneKind::Split { dir, children } = &zone.kind else {
            return;
        };
        let Some(parent) = laid.get(&zone.name.0).filter(|at| at.shown == Shown::Open) else {
            return;
        };
        let length = along(*dir, parent.rect.size());
        let shown: Vec<&LaidZone> = children
            .iter()
            .filter_map(|child| laid.get(&child.name.0))
            // Collapsed zones take no room either: their neighbours meet.
            .filter(|at| !matches!(at.shown, Shown::Hidden | Shown::Collapsed))
            .collect();
        let child = |at: &LaidZone| children.iter().find(|c| c.name == at.name);
        let taker = shown
            .iter()
            .position(|at| child(at).is_some_and(|c| c.constraints.grow))
            .or_else(|| shown.iter().rposition(|at| at.shown == Shown::Open));
        let Some(taker) = taker else {
            return;
        };
        let taker_slack = {
            let at = shown[taker];
            (along(*dir, at.rect.size()) - at.least).max(0.0)
        };
        for i in 0..shown.len().saturating_sub(1) {
            let (a, b) = (shown[i], shown[i + 1]);
            if a.shown != Shown::Open || b.shown != Shown::Open {
                continue;
            }
            let (resized, before) = if taker > i { (a, true) } else { (b, false) };
            if resized.least >= resized.most {
                // A fixed size: no sash, no focus stop.
                continue;
            }
            let size = along(*dir, resized.rect.size());
            let boundary = along(*dir, a.rect.max.to_vec2());
            let rect = span(*dir, a.rect.union(b.rect), boundary, boundary);
            let most = resized.most.min(size + taker_slack).max(resized.least);
            let default = child(resized)
                .and_then(|c| c.constraints.default)
                .map(|d| d.points(length).clamp(resized.least, resized.most));
            out.push(Sash {
                dir: *dir,
                rect,
                zone: resized.name.clone(),
                before,
                size,
                least: resized.least,
                most,
                default,
            });
        }
    });
    out
}

/// What a sash dragged to `at` (its zone's size) catches within `magnet`:
/// its zone's default size, or the line of another sash running the same
/// way; the nearest wins. Returns the size and the guide line.
fn snap(sash: &Sash, all: &[Sash], at: f32, magnet: f32) -> Option<(f32, SnapKind, Rect)> {
    let mut best: Option<(f32, f32, SnapKind, Rect)> = None;
    let mut consider = |size: f32, kind: SnapKind, line: Rect| {
        let distance = (size - at).abs();
        let within = sash.least <= size && size <= sash.most && distance <= magnet;
        if within && best.is_none_or(|(d, ..)| distance < d) {
            best = Some((distance, size, kind, line));
        }
    };
    if let Some(default) = sash.default {
        consider(default, SnapKind::Default, sash.line_at(default));
    }
    for other in all
        .iter()
        .filter(|other| other.dir == sash.dir && other.zone != sash.zone)
    {
        let size = sash.size_at(other.boundary());
        consider(size, SnapKind::Sash, sash.line_at(size).union(other.rect));
    }
    best.map(|(_, size, kind, line)| (size, kind, line))
}

/// Paints a guide line above everything.
pub(super) fn paint_guide(
    ui: &Ui,
    id: Id,
    painter: &dyn LayoutPainter,
    guide: &SnapGuidePaint<'_>,
) {
    let layer = ui
        .ctx()
        .layer_painter(LayerId::new(Order::Foreground, id.with("guide")));
    painter.snap_guide(&layer, guide);
}

/// Applies what the user did to `sash` this frame (drag, keys, double
/// click, accessibility actions) to its zone's size, before the zones are
/// drawn. Its response is read from where it was last frame, `sash`'s
/// rect; [`sash_ui`] registers it again where it is drawn. Returns the
/// snap guide to paint, if any.
fn sash_input(
    ui: &Ui,
    id: Id,
    layout: &mut Layout,
    sash: &Sash,
    all: &[Sash],
    style: &LayoutStyle,
    events: &mut Vec<LayoutEvent>,
) -> Option<(SnapKind, Rect)> {
    let horizontal = sash.dir == Dir::Horizontal;
    let sash_id = id.with(("sash", &sash.zone.0));
    // Not there last frame: nothing done to it yet.
    let response = ui.ctx().read_response(sash_id)?;

    // Moving the sash by `delta` (right or down) changes the zone by
    // `delta` before it, by `-delta` after it.
    let sign = if sash.before { 1.0 } else { -1.0 };
    let mut target = sash.size;
    let mut moved = false;
    let delta = along(sash.dir, response.drag_delta());
    let start_id = sash_id.with("start");
    // Where the drag puts the zone, unbounded and before snapping.
    let mut dragged_to = None;
    if response.dragged() || delta != 0.0 {
        // The drag's total, so a pointer past a bound comes back in step.
        let total: f32 = ui.ctx().data_mut(|d| {
            let start = d.get_temp_mut_or_insert_with(start_id, || (sash.size, 0.0_f32));
            start.1 += delta;
            start.0 + sign * start.1
        });
        dragged_to = Some(total);
    }
    let mut size_before = sash.size;
    if !response.dragged() {
        let start = ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(start_id));
        if let Some((size, total)) = start {
            size_before = size;
            dragged_to = Some(size + sign * total);
        }
    }
    // Dragged under half its least size, a zone that folds folds on
    // release.
    let folds = layout
        .zone(&sash.zone.0)
        .is_some_and(|zone| zone.constraints.fold == Fold::ToStrip);
    let fold_below = sash.least * 0.5;
    let folding = folds && dragged_to.is_some_and(|to| to < fold_below);
    if folding && response.drag_stopped() {
        // It unfolds at the size it had before the drag.
        if let Some(zone) = layout.zone_mut(&sash.zone.0) {
            zone.state.size = Some(size_before);
        }
        layout.set_folded(&sash.zone.0, true);
        events.push(LayoutEvent::Folded {
            zone: sash.zone.clone(),
        });
        return None;
    }
    let mut guide = None;
    if let Some(to) = dragged_to {
        target = to;
        moved = true;
        let alt = ui.input(|i| i.modifiers.alt);
        if folding {
            guide = Some((SnapKind::Fold, sash.line_at(style.strip)));
        } else if style.snap > 0.0
            && !alt
            && let Some((size, kind, line)) =
                snap(sash, all, to.clamp(sash.least, sash.most), style.snap)
        {
            target = size;
            guide = response.dragged().then_some((kind, line));
        }
    }
    let mut reset = response.double_clicked();
    if response.has_focus() {
        ui.memory_mut(|m| {
            m.set_focus_lock_filter(
                response.id,
                EventFilter {
                    horizontal_arrows: horizontal,
                    vertical_arrows: !horizontal,
                    tab: false,
                    escape: false,
                },
            );
        });
        let (back, forward) = if horizontal {
            (Key::ArrowLeft, Key::ArrowRight)
        } else {
            (Key::ArrowUp, Key::ArrowDown)
        };
        ui.input(|i| {
            let step = if i.modifiers.shift {
                style.large_key_step
            } else {
                style.key_step
            };
            if i.key_pressed(back) {
                target -= sign * step;
                moved = true;
            }
            if i.key_pressed(forward) {
                target += sign * step;
                moved = true;
            }
            reset |= i.key_pressed(Key::Enter);
        });
    }
    ui.input(|i| {
        let steps = i.num_accesskit_action_requests(response.id, Action::Increment) as f32
            - i.num_accesskit_action_requests(response.id, Action::Decrement) as f32;
        if steps != 0.0 {
            target += steps * style.key_step;
            moved = true;
        }
        if let Some(value) = i
            .accesskit_action_requests(response.id, Action::SetValue)
            .filter_map(|request| match request.data {
                Some(ActionData::NumericValue(value)) => Some(value as f32),
                _ => None,
            })
            .last()
        {
            target = value;
            moved = true;
        }
    });

    if reset {
        if let Some(zone) = layout.zone_mut(&sash.zone.0) {
            zone.state.size = None;
        }
        events.push(LayoutEvent::Reset {
            zone: sash.zone.clone(),
        });
    } else if moved {
        let clamped = target.clamp(sash.least, sash.most);
        if clamped != sash.size
            && let Some(zone) = layout.zone_mut(&sash.zone.0)
        {
            zone.state.size = Some(clamped);
            events.push(LayoutEvent::Resized {
                zone: sash.zone.clone(),
                size: clamped,
            });
        }
    }
    guide
}

/// Registers and paints `sash` where it is laid this frame, with the snap
/// guide its drag shows.
fn sash_ui(
    ui: &mut Ui,
    id: Id,
    sash: &Sash,
    guide: Option<(SnapKind, Rect)>,
    style: &LayoutStyle,
    painter: &dyn LayoutPainter,
    names: &Names<'_>,
) {
    let horizontal = sash.dir == Dir::Horizontal;
    let mid = along(sash.dir, sash.rect.min.to_vec2());
    let thick = |grow: f32| span(sash.dir, sash.rect, mid - grow * 0.5, mid + grow * 0.5);
    let sash_id = id.with(("sash", &sash.zone.0));
    let cursor = if horizontal {
        CursorIcon::ResizeHorizontal
    } else {
        CursorIcon::ResizeVertical
    };
    let response = ui
        .interact(thick(style.sash_grab), sash_id, Sense::click_and_drag())
        .on_hover_and_drag_cursor(cursor);
    let axis = if horizontal {
        SeparatorAxis::Vertical
    } else {
        SeparatorAxis::Horizontal
    };
    painter.sash(
        ui.painter(),
        &SashPaint {
            rect: thick(style.sash_width),
            axis,
            state: PartState::NONE
                .with(PartState::HOVERED, response.hovered())
                .with(PartState::PRESSED, response.is_pointer_button_down_on())
                .with(PartState::FOCUSED, response.has_focus())
                .with(PartState::DRAGGED, response.dragged()),
            zone: &sash.zone,
            style,
        },
    );
    if let Some((kind, line)) = guide {
        paint_guide(
            ui,
            id,
            painter,
            &SnapGuidePaint {
                line: [line.min, line.max],
                axis,
                kind,
                zone: &sash.zone,
                style,
            },
        );
    }
    describe_sash(ui, &response, sash, sash.size, style.key_step, names);
}

/// The sash as a splitter whose value is its zone's size, stepped by `key_step` points.
fn describe_sash(
    ui: &Ui,
    response: &Response,
    sash: &Sash,
    size: f32,
    key_step: f32,
    names: &Names<'_>,
) {
    let label = names.resize(&sash.zone);
    let enabled = ui.is_enabled();
    response.widget_info(|| {
        let mut info = WidgetInfo::labeled(Role::Splitter, enabled, &label);
        info.value = Some(f64::from(size));
        info
    });
    ui.ctx().accesskit_node_builder(response.id, |node| {
        node.set_orientation(if sash.dir == Dir::Horizontal {
            Orientation::Vertical
        } else {
            Orientation::Horizontal
        });
        node.set_min_numeric_value(f64::from(sash.least));
        node.set_max_numeric_value(f64::from(sash.most));
        node.set_numeric_value_step(f64::from(key_step));
        if sash.least < sash.most {
            node.add_action(Action::SetValue);
            if size < sash.most {
                node.add_action(Action::Increment);
            }
            if sash.least < size {
                node.add_action(Action::Decrement);
            }
        }
    });
}

/// Reports the zones the solver folded by itself ([`Shown::AutoFolded`]) since
/// the area was last drawn, and those it brought back, from the auto-folded
/// zones it remembers between frames. A zone no longer laid (under a folded
/// zone) is forgotten without an event. A zone opened over from its
/// auto-folded strip counts as auto-folded until it is closed.
fn auto_folds(ui: &Ui, id: Id, layout: &Layout, laid: &Laid, events: &mut Vec<LayoutEvent>) {
    let memory = id.with("auto_folded");
    let before: Vec<ZoneName> = ui.ctx().data(|d| d.get_temp(memory)).unwrap_or_default();
    let now: Vec<ZoneName> = laid
        .zones
        .iter()
        .filter(|zone| {
            zone.shown == Shown::AutoFolded
                || zone.shown == Shown::Over
                    && layout
                        .zone(&zone.name.0)
                        .is_some_and(|z| z.state.over_from_auto)
        })
        .map(|zone| zone.name.clone())
        .collect();
    for zone in &now {
        if !before.contains(zone) {
            events.push(LayoutEvent::AutoFolded { zone: zone.clone() });
        }
    }
    for zone in before {
        if !now.contains(&zone) && laid.get(&zone.0).is_some() {
            events.push(LayoutEvent::AutoUnfolded { zone });
        }
    }
    ui.ctx().data_mut(|d| d.insert_temp(memory, now));
}