egui_stack 0.33.0

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
//! A window's whole space as a tree of zones: which zone is where, how
//! big, within which bounds. The layout knows nothing about tabs: a zone
//! holds a dock by name ([`Content::Dock`]), the application's own
//! drawing ([`Content::App`]) or nothing ([`Content::Empty`]).
//!
//! This module is the model only: the tree ([`Layout`], [`Zone`]), the
//! constraints set from code ([`Constraints`]), what the user changed
//! ([`ZoneState`]), and the solver that turns them into rects
//! ([`Layout::solve`], [`Laid`]). [`LayoutArea`] draws it: each zone's
//! content through a [`ZoneViewer`], and sashes between zones that resize
//! them, painted by a [`LayoutPainter`].
//!
//! The solver works one split at a time along the split's axis. Folded,
//! lying-over and hidden zones take their fixed breadth first; the others
//! take their wanted size within their bounds, and the zone that grows
//! (the centre) takes the rest. When the rest is under the centre's least
//! size, the others give way, the lowest [`Priority`] first and, among
//! equals, the nearest to the centre first, each down to its least size
//! and never in proportion: the rule [`crate::sections::plan`] applies to
//! sections. If even the least sizes do not fit, zones that opted in
//! ([`Constraints::auto_fold`]) fold to their strip, lowest priority
//! first, and come back when the room does.
//!
//! ```
//! use egui_stack::egui::{Rect, pos2};
//! use egui_stack::layout::{Content, Dir, Layout, Size, Solve, Zone};
//!
//! let layout = Layout::new(Zone::split(
//!     "root",
//!     Dir::Horizontal,
//!     vec![
//!         Zone::leaf("left", Content::Dock("left".into()))
//!             .with(|c| c.default = Some(Size::Points(200.0))),
//!         Zone::leaf("centre", Content::Dock("centre".into())).with(|c| {
//!             c.grow = true;
//!             c.min = Some(Size::Points(300.0));
//!         }),
//!     ],
//! ));
//! let laid = layout.solve(Rect::from_min_size(pos2(0.0, 0.0), [400.0, 300.0].into()), &Solve::default());
//! // The centre keeps its least size: the side gives way.
//! assert_eq!(laid.rect("left").unwrap().width(), 100.0);
//! assert_eq!(laid.rect("centre").unwrap().width(), 300.0);
//! ```

mod area;
mod float;
mod fold;
#[cfg(feature = "serde")]
pub(crate) mod saved;
mod solve;

pub use area::{
    DefaultLayoutPainter, LayoutArea, LayoutPainter, LayoutStyle, SashPaint, SnapGuidePaint,
    SnapKind, ZoneViewer,
};
pub use float::{Float, FloatHost, Place, Repaired, Screen, ScreenGone};
pub use fold::{
    Dismiss, Flyout, FlyoutPaint, Inside, StripAction, StripOrientation, StripPaint, StripTitle,
    VerticalReading,
};

#[cfg(feature = "serde")]
pub use saved::{LAYOUT_VERSION, VersionError};
pub use solve::{Laid, LaidZone, LayoutEvent, Restore, Shown, Solve};

use std::collections::BTreeMap;
use std::fmt;

/// A zone's name: stable, saved, chosen by the application ("left",
/// "centre", "status"). Names are unique in a layout.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(transparent)
)]
pub struct ZoneName(pub String);

impl fmt::Display for ZoneName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<&str> for ZoneName {
    fn from(name: &str) -> Self {
        Self(name.to_owned())
    }
}

impl From<String> for ZoneName {
    fn from(name: String) -> Self {
        Self(name)
    }
}

impl PartialEq<str> for ZoneName {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

/// The whole layout: one value, serialisable with the `serde` feature.
///
/// Saved, it holds the tree and each zone's [`ZoneState`]; constraints
/// stay the code's: after loading, [`Layout::reconcile`] takes them from
/// the tree the code builds, and adds or drops the zones the code added or
/// removed since.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(try_from = "saved::SavedLayout", into = "saved::SavedLayout")
)]
pub struct Layout {
    /// The zone holding all others; it takes the whole rect it is solved in.
    pub root: Zone,
    /// Each flyout's breadth, by its key ([`Flyout::key`]), once the user
    /// resized it.
    pub flyouts: BTreeMap<String, f32>,
    /// The floating roots, by their order of opening; [`Float::z`] orders
    /// them front to back. Saved with their place.
    pub floats: Vec<Float>,
    /// The places of the floats closed, by key, so a float opened again
    /// with [`open_float`](Self::open_float) comes back where it was.
    pub closed: BTreeMap<String, Place>,
}

/// One zone of the tree: a split of zones, or a leaf with content.
#[derive(Clone, Debug, PartialEq)]
pub struct Zone {
    /// Its name, unique in the layout.
    pub name: ZoneName,
    /// A split or a leaf.
    pub kind: ZoneKind,
    /// Its bounds and behaviour, set from code (never saved).
    pub constraints: Constraints,
    /// What the user changed (saved).
    pub state: ZoneState,
}

/// What a zone is.
#[derive(Clone, Debug, PartialEq)]
pub enum ZoneKind {
    /// Children side by side ([`Dir::Horizontal`]) or one above the other
    /// ([`Dir::Vertical`]).
    Split {
        /// The axis the children follow each other on.
        dir: Dir,
        /// The children, left to right or top to bottom.
        children: Vec<Zone>,
    },
    /// A zone with content and no children.
    Leaf {
        /// What it shows.
        content: Content,
    },
}

/// The axis a split's children follow each other on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(rename_all = "kebab-case")
)]
pub enum Dir {
    /// Side by side, left to right.
    #[default]
    Horizontal,
    /// One above the other, top to bottom.
    Vertical,
}

/// What a leaf zone shows.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(rename_all = "kebab-case")
)]
#[non_exhaustive]
pub enum Content {
    /// The `DockSpace` dock of that name.
    Dock(String),
    /// Anything the application draws: a toolbar, a status bar, a viewer.
    App,
    /// Room left empty.
    #[default]
    Empty,
}

/// A size along the parent split's axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Size {
    /// Points.
    Points(f32),
    /// A share of the parent split's length (0.25: a quarter); of the
    /// solved rect at the root.
    Share(f32),
}

impl Size {
    /// The size in points, in a parent of length `length`.
    pub fn points(self, length: f32) -> f32 {
        match self {
            Self::Points(points) => points,
            Self::Share(share) => share * length,
        }
    }
}

/// Who gives way first when room is short: `Low` before `Normal` before
/// `High`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Priority {
    /// Gives way first.
    Low,
    /// Gives way after `Low`.
    #[default]
    Normal,
    /// Gives way last.
    High,
}

/// Whether a zone may fold to a strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Fold {
    /// It never folds.
    #[default]
    Never,
    /// It folds to a strip, which keeps its place in the flow.
    ToStrip,
    /// It collapses to nothing: folded ([`ZoneState::folded`]), it takes no
    /// room and shows no strip ([`Shown::Collapsed`]), and keeps its name,
    /// its constraints and its last size. While a tab is dragged, a thin
    /// restore band at its former boundary brings it back: a tab released
    /// there joins the dock it holds, and the zone is reported to unfold
    /// ([`DockSpace::take_unfolds`](crate::DockSpace::take_unfolds)), at its
    /// remembered size within its current bounds.
    /// [`DockSpace::collapse_empty`](crate::DockSpace::collapse_empty)
    /// collapses those whose docks are empty. A sash never collapses it, and
    /// [`Constraints::auto_fold`] does not apply. A zone the application
    /// hides ([`ZoneState::hidden`]) shows no band.
    Collapse,
}

/// Whether a dragged item may be dropped in a zone. The layout only
/// carries it: the dock layer reads it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Drops {
    /// Drops are accepted (the dock's own rules still apply).
    #[default]
    Accept,
    /// Nothing is dropped here.
    Refuse,
}

/// A zone's bounds and behaviour, set from code; never saved.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Constraints {
    /// The least size; 0 when `None`.
    pub min: Option<Size>,
    /// The largest size; none when `None`.
    pub max: Option<Size>,
    /// The size a zone starts with, before the user sizes it.
    pub default: Option<Size>,
    /// The zone takes what its siblings leave (the centre). One per split
    /// at most: the first one counts. It never folds.
    pub grow: bool,
    /// Who gives way first when room is short.
    pub priority: Priority,
    /// The least size includes what the content asked for last frame
    /// ([`Solve::content`]).
    pub fit_content: bool,
    /// Whether the zone may fold to a strip.
    pub fold: Fold,
    /// With [`Fold::ToStrip`] (not [`Fold::Collapse`]), the zone folds by itself when even the least
    /// sizes do not fit, and comes back when the room does. Off by default.
    pub auto_fold: bool,
    /// Whether a dragged item may be dropped here.
    pub drops: Drops,
    /// While the zone is folded, a tab dropped on its strip joins the dock
    /// it holds ([`Content::Dock`]), if [`drops`](Self::drops) and the dock
    /// accept it ([`DockSpace::bind`](crate::DockSpace::bind)). On a split
    /// zone, the tab joins one of the docks the split holds that accept
    /// drops: the one holding the focused leaf (the last active), else the
    /// first, depth first. Either way the zone stays folded and is reported
    /// to unfold ([`DockSpace::take_unfolds`](crate::DockSpace::take_unfolds)),
    /// for the application to unfold it or not.
    /// Off by default: the strip takes no drops.
    pub strip_drops: bool,
}

/// What the user changed; saved with the layout.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(default)
)]
#[non_exhaustive]
pub struct ZoneState {
    /// The size the user gave, in points, kept even while the zone is
    /// shown smaller.
    pub size: Option<f32>,
    /// Folded to its strip, or collapsed with [`Fold::Collapse`].
    pub folded: bool,
    /// Open over its neighbour, next to its strip, without taking room.
    pub over: bool,
    /// Not shown, and taking no room.
    pub hidden: bool,
    /// Lying over because its auto-folded strip was clicked
    /// ([`StripAction::Over`]): closed, it goes back to its automatic state
    /// rather than folded. Never saved.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub(crate) over_from_auto: bool,
}

impl ZoneState {
    /// Whether the zone lies over its neighbour because its auto-folded
    /// strip was clicked ([`Shown::AutoFolded`], [`StripAction::Over`]):
    /// closing it puts it back in its automatic state, not folded, so that
    /// it unfolds by itself once the room comes back. Not saved.
    pub fn over_from_auto(&self) -> bool {
        self.over_from_auto
    }
}

impl Zone {
    /// A leaf zone with default constraints and state.
    pub fn leaf(name: impl Into<ZoneName>, content: Content) -> Self {
        Self {
            name: name.into(),
            kind: ZoneKind::Leaf { content },
            constraints: Constraints::default(),
            state: ZoneState::default(),
        }
    }

    /// A split zone with default constraints and state.
    pub fn split(name: impl Into<ZoneName>, dir: Dir, children: Vec<Self>) -> Self {
        Self {
            name: name.into(),
            kind: ZoneKind::Split { dir, children },
            constraints: Constraints::default(),
            state: ZoneState::default(),
        }
    }

    /// The zone with its constraints changed by `constrain`.
    pub fn with(mut self, constrain: impl FnOnce(&mut Constraints)) -> Self {
        constrain(&mut self.constraints);
        self
    }

    /// The zone with its state changed by `change`.
    pub fn with_state(mut self, change: impl FnOnce(&mut ZoneState)) -> Self {
        change(&mut self.state);
        self
    }

    /// Its children: none for a leaf.
    pub fn children(&self) -> &[Self] {
        match &self.kind {
            ZoneKind::Split { children, .. } => children,
            ZoneKind::Leaf { .. } => &[],
        }
    }

    /// The zone named `name`: this one or one under it.
    pub fn find(&self, name: &str) -> Option<&Self> {
        if self.name == *name {
            return Some(self);
        }
        self.children().iter().find_map(|child| child.find(name))
    }

    /// Calls `visit` on this zone and every zone under it, parents first,
    /// mutably.
    pub fn visit_mut(&mut self, visit: &mut impl FnMut(&mut Self)) {
        visit(self);
        if let ZoneKind::Split { children, .. } = &mut self.kind {
            for child in children {
                child.visit_mut(visit);
            }
        }
    }

    /// The zone named `name`, mutably: this one or one under it.
    pub fn find_mut(&mut self, name: &str) -> Option<&mut Self> {
        if self.name == *name {
            return Some(self);
        }
        match &mut self.kind {
            ZoneKind::Split { children, .. } => {
                children.iter_mut().find_map(|child| child.find_mut(name))
            }
            ZoneKind::Leaf { .. } => None,
        }
    }

    /// Calls `visit` on this zone and every zone under it, parents first.
    pub fn visit(&self, visit: &mut impl FnMut(&Self)) {
        visit(self);
        for child in self.children() {
            child.visit(visit);
        }
    }
}

impl Layout {
    /// A layout of `root`.
    pub fn new(root: Zone) -> Self {
        Self {
            root,
            flyouts: BTreeMap::new(),
            floats: Vec::new(),
            closed: BTreeMap::new(),
        }
    }

    /// The float keyed `key`.
    pub fn float(&self, key: &str) -> Option<&Float> {
        self.floats.iter().find(|float| float.key == key)
    }

    /// The float keyed `key`, mutably.
    pub fn float_mut(&mut self, key: &str) -> Option<&mut Float> {
        self.floats.iter_mut().find(|float| float.key == key)
    }

    /// The float showing the dock named `dock`.
    pub fn float_of_dock(&self, dock: &str) -> Option<&Float> {
        self.floats
            .iter()
            .find(|float| float.dock_name() == Some(dock))
    }

    /// Opens `float` in front of the others, replacing a float of the same
    /// key. When a float of that key was closed ([`close_float`](Self::close_float)),
    /// it comes back at that place, not `float`'s.
    pub fn open_float(&mut self, mut float: Float) -> &mut Float {
        if let Some(place) = self.closed.remove(&float.key) {
            float.place = place;
        }
        self.floats.retain(|open| open.key != float.key);
        float.z = self.front_z();
        self.floats.push(float);
        let last = self.floats.len() - 1;
        &mut self.floats[last]
    }

    /// Closes the float keyed `key` and returns it; its place is kept in
    /// [`closed`](Self::closed) for when it opens again.
    pub fn close_float(&mut self, key: &str) -> Option<Float> {
        let index = self.floats.iter().position(|float| float.key == key)?;
        let float = self.floats.remove(index);
        self.closed.insert(float.key.clone(), float.place.clone());
        Some(float)
    }

    /// The place the float keyed `key` had when it was closed.
    pub fn closed_place(&self, key: &str) -> Option<&Place> {
        self.closed.get(key)
    }

    /// Brings the float keyed `key` in front of the others; says whether it
    /// exists.
    pub fn raise_float(&mut self, key: &str) -> bool {
        let behind = self
            .floats
            .iter()
            .filter(|float| float.key != key)
            .map(|float| float.z)
            .max();
        let Some(float) = self.float_mut(key) else {
            return false;
        };
        if let Some(behind) = behind
            && float.z <= behind
        {
            float.z = behind.saturating_add(1);
        }
        true
    }

    /// The floats, back to front.
    pub fn floats_back_to_front(&self) -> Vec<&Float> {
        let mut floats: Vec<&Float> = self.floats.iter().collect();
        floats.sort_by_key(|float| float.z);
        floats
    }

    /// Brings every native float ([`FloatHost::Native`]) back onto
    /// `screens` ([`Place::repair`]): the floats moved get their new place;
    /// those whose screen is gone, with [`ScreenGone::DockBack`], are closed
    /// (their place kept) and returned for the application to put their
    /// tabs back. Floats over the main window are left alone: their place is
    /// in the window, not on a screen.
    pub fn repair_floats(&mut self, screens: &[Screen], gone: ScreenGone) -> FloatsRepair {
        let mut repair = FloatsRepair::default();
        let mut back = Vec::new();
        for float in &mut self.floats {
            if float.host != FloatHost::Native {
                continue;
            }
            match float.place.repair(screens, gone) {
                Repaired::Unchanged => (),
                Repaired::Moved(place) => {
                    float.place = place;
                    repair.moved.push(float.key.clone());
                }
                Repaired::DockBack => back.push(float.key.clone()),
            }
        }
        repair.docked_back = back
            .iter()
            .filter_map(|key| self.close_float(key))
            .collect();
        repair
    }

    /// The z a float takes to be in front of every other.
    fn front_z(&self) -> u32 {
        self.floats
            .iter()
            .map(|float| float.z.saturating_add(1))
            .max()
            .unwrap_or(0)
    }

    /// Folds the zone named `name` to its strip, or unfolds it; either way
    /// it no longer lies over its neighbour. Says whether the zone exists.
    /// The zone that grows never folds: the solver ignores its state. No
    /// [`LayoutEvent`] reports it: the events are the user's acts and the
    /// solver's, not the application's.
    ///
    /// Unfolding a zone the solver folded short of room
    /// ([`Shown::AutoFolded`]) changes nothing while the room is short: to
    /// show it anyway, open it over its neighbour with
    /// [`set_over`](Self::set_over), as a click on its strip does
    /// ([`StripAction::Over`]).
    pub fn set_folded(&mut self, name: &str, folded: bool) -> bool {
        self.zone_mut(name)
            .map(|zone| {
                zone.state.folded = folded;
                zone.state.over = false;
                zone.state.over_from_auto = false;
            })
            .is_some()
    }

    /// Opens the zone named `name` over its neighbour, next to its strip,
    /// without taking room (`over`), or folds it back to its strip. Says
    /// whether the zone exists. A zone lying over takes only its strip in
    /// the flow, so the solver does not fold it short of room.
    pub fn set_over(&mut self, name: &str, over: bool) -> bool {
        self.zone_mut(name)
            .map(|zone| {
                zone.state.over = over;
                zone.state.folded = !over;
                zone.state.over_from_auto = false;
            })
            .is_some()
    }

    /// Opens the auto-folded zone named `name` over its neighbour, as
    /// [`set_over`](Self::set_over) does, remembering that closing it puts
    /// it back in its automatic state.
    pub(crate) fn open_over_from_auto(&mut self, name: &str) {
        self.set_over(name, true);
        if let Some(zone) = self.zone_mut(name) {
            zone.state.over_from_auto = true;
        }
    }

    /// Closes a zone lying over its neighbour: back to its strip when the
    /// user had folded it, back to its automatic state (neither folded nor
    /// over) when it was opened from its auto-folded strip. The event that
    /// says so.
    pub(crate) fn close_over(&mut self, name: &ZoneName) -> Option<LayoutEvent> {
        let zone = self.zone_mut(&name.0)?;
        let event = if zone.state.over_from_auto {
            zone.state.folded = false;
            zone.state.over = false;
            zone.state.over_from_auto = false;
            LayoutEvent::ClosedOver { zone: name.clone() }
        } else {
            zone.state.folded = true;
            zone.state.over = false;
            LayoutEvent::Folded { zone: name.clone() }
        };
        Some(event)
    }

    /// A layout of one leaf, `name`, holding the dock of the same name.
    pub fn single(name: &str) -> Self {
        Self::new(Zone::leaf(name, Content::Dock(name.to_owned())))
    }

    /// The zone named `name`.
    pub fn zone(&self, name: &str) -> Option<&Zone> {
        self.root.find(name)
    }

    /// The zone named `name`, mutably.
    pub fn zone_mut(&mut self, name: &str) -> Option<&mut Zone> {
        self.root.find_mut(name)
    }

    /// Changes the constraints of the zone named `name`, as code may every
    /// frame; says whether the zone exists.
    pub fn constrain(&mut self, name: &str, constrain: impl FnOnce(&mut Constraints)) -> bool {
        self.zone_mut(name)
            .map(|zone| constrain(&mut zone.constraints))
            .is_some()
    }

    /// Every zone's name, parents first.
    pub fn names(&self) -> Vec<ZoneName> {
        names_under(&self.root)
    }

    /// Makes a layout loaded from storage agree with `code`, the layout the
    /// application builds: every zone takes its constraints from `code`,
    /// zones `code` no longer has are dropped, and zones only `code` has are
    /// added under the same parent, after the same sibling as in `code`,
    /// with their state from `code`; the zones under a dropped split take
    /// its place. The loaded tree's shape, directions, contents and states
    /// are kept otherwise: a zone the code moved elsewhere stays where it
    /// was saved. A zone that is a leaf in one
    /// and a split in the other takes `code`'s zone, keeping its loaded
    /// state. When the roots' names differ, the loaded tree and flyout
    /// widths are replaced by `code`'s.
    ///
    /// Floats are the user's: the loaded ones are kept, those the code does
    /// not know included (a window the user detached), with the places of
    /// the closed ones. A float of `code` whose key the loaded layout knows
    /// neither open nor closed is added, so a layout saved before floats
    /// existed gets the code's. Whether a float's dock exists is
    /// [`Docked::repair`](crate::Docked::repair)'s concern.
    pub fn reconcile(&mut self, code: &Self) -> Repair {
        for float in &code.floats {
            if self.float(&float.key).is_none() && !self.closed.contains_key(&float.key) {
                self.floats.push(float.clone());
            }
        }
        let before = self.names();
        if self.root.name != code.root.name {
            // The floats are the user's, not the tree's.
            self.root = code.root.clone();
            self.flyouts = code.flyouts.clone();
        } else {
            let in_code = code.names();
            drop_missing(&mut self.root, &in_code);
            follow_kinds(&mut self.root, &code.root);
            add_missing(&mut self.root, &code.root);
            let root = &code.root;
            self.root.visit_mut(&mut |zone| {
                if let Some(code) = root.find(&zone.name.0) {
                    zone.constraints = code.constraints;
                }
            });
        }
        let after = self.names();
        Repair {
            added: after
                .iter()
                .filter(|n| !before.contains(n))
                .cloned()
                .collect(),
            removed: before.into_iter().filter(|n| !after.contains(n)).collect(),
        }
    }
}

/// What [`Layout::repair_floats`] changed.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct FloatsRepair {
    /// The keys of the floats given a new place.
    pub moved: Vec<String>,
    /// The floats closed because their screen is gone
    /// ([`ScreenGone::DockBack`]); their places are kept in
    /// [`Layout::closed`].
    pub docked_back: Vec<Float>,
}

/// What [`Layout::reconcile`] changed in the loaded tree.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Repair {
    /// Zones the code has that the loaded layout had not, parents first.
    pub added: Vec<ZoneName>,
    /// Zones the loaded layout had that the code has not.
    pub removed: Vec<ZoneName>,
}

impl Repair {
    /// Whether the loaded tree already matched the code's.
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.removed.is_empty()
    }
}

/// Drops from `zone`'s children, at any depth, the zones not in `keep`; the
/// kept zones under a dropped split take its place.
fn drop_missing(zone: &mut Zone, keep: &[ZoneName]) {
    if let ZoneKind::Split { children, .. } = &mut zone.kind {
        for mut child in std::mem::take(children) {
            drop_missing(&mut child, keep);
            if keep.contains(&child.name) {
                children.push(child);
            } else if let ZoneKind::Split {
                children: lifted, ..
            } = child.kind
            {
                children.extend(lifted);
            }
        }
    }
}

/// A copy of `code` without the zones under it that `loaded` has.
fn without_loaded(code: &Zone, loaded: &[ZoneName]) -> Zone {
    let mut zone = code.clone();
    drop_loaded(&mut zone, loaded);
    zone
}

fn drop_loaded(zone: &mut Zone, loaded: &[ZoneName]) {
    if let ZoneKind::Split { children, .. } = &mut zone.kind {
        children.retain(|child| !loaded.contains(&child.name));
        for child in children {
            drop_loaded(child, loaded);
        }
    }
}

/// Gives the loaded zones that are a leaf in one tree and a split in the
/// other the code's kind (and children), keeping their state.
fn follow_kinds(root: &mut Zone, code: &Zone) {
    let mut mismatched = Vec::new();
    root.visit(&mut |zone| {
        if let Some(code) = code.find(&zone.name.0) {
            let same = matches!(
                (&zone.kind, &code.kind),
                (ZoneKind::Split { .. }, ZoneKind::Split { .. })
                    | (ZoneKind::Leaf { .. }, ZoneKind::Leaf { .. })
            );
            if !same {
                mismatched.push(zone.name.clone());
            }
        }
    });
    for name in mismatched {
        let Some(zone) = root.find_mut(&name.0) else {
            continue;
        };
        // Its loaded children go with its loaded kind.
        zone.kind = ZoneKind::Leaf {
            content: Content::Empty,
        };
        let Some(code) = code.find(&name.0) else {
            continue;
        };
        let loaded = names_under(root);
        let kind = without_loaded(code, &loaded).kind;
        if let Some(zone) = root.find_mut(&name.0) {
            zone.kind = kind;
        }
    }
}

/// Adds the zones only `code` has, under the same parent and after the
/// same sibling as in `code` (first when none is loaded).
fn add_missing(root: &mut Zone, code: &Zone) {
    for (at, child) in code.children().iter().enumerate() {
        let loaded = names_under(root);
        if !loaded.contains(&child.name) {
            let added = without_loaded(child, &loaded);
            if let Some(ZoneKind::Split { children, .. }) =
                root.find_mut(&code.name.0).map(|parent| &mut parent.kind)
            {
                let place = code.children()[..at]
                    .iter()
                    .rev()
                    .find_map(|before| children.iter().position(|c| c.name == before.name))
                    .map_or(0, |i| i + 1);
                children.insert(place, added);
            }
        }
        add_missing(root, child);
    }
}

fn names_under(zone: &Zone) -> Vec<ZoneName> {
    let mut names = Vec::new();
    zone.visit(&mut |under| names.push(under.name.clone()));
    names
}

#[cfg(test)]
mod tests;