egui_stack 0.30.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
//! The layout's solver: the rect of every zone, one split at a time.

use std::collections::HashMap;

use egui::{Pos2, Rect, pos2};

use super::{Content, Dir, Drops, Fold, Layout, Zone, ZoneKind, ZoneName};
use crate::sections::plan::give_in_turn;

/// What the solver needs besides the layout.
#[derive(Clone, Debug, PartialEq)]
pub struct Solve {
    /// A folded zone's strip breadth, along its parent's axis.
    pub strip: f32,
    /// The size each zone's content asked for last frame, along its
    /// parent's axis: a least size for zones with
    /// [`Constraints::fit_content`](super::Constraints::fit_content).
    pub content: HashMap<ZoneName, f32>,
}

impl Default for Solve {
    fn default() -> Self {
        Self {
            strip: 24.0,
            content: HashMap::new(),
        }
    }
}

/// How a zone is shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Shown {
    /// In the flow, at its solved size.
    Open,
    /// Folded by the user ([`ZoneState::folded`](super::ZoneState::folded)):
    /// its strip only.
    Folded,
    /// Folded by the solver, short of room
    /// ([`Constraints::auto_fold`](super::Constraints::auto_fold)): its strip
    /// only, until the room comes back.
    AutoFolded,
    /// Its strip in the flow, its body over the neighbour towards the zone
    /// that grows ([`ZoneState::over`](super::ZoneState::over)).
    Over,
    /// Not shown, taking no room.
    Hidden,
    /// Collapsed ([`Fold::Collapse`](super::Fold::Collapse) and
    /// [`ZoneState::folded`](super::ZoneState::folded)): taking no room and
    /// showing no strip; [`LaidZone::restore`] says where it would come back.
    Collapsed,
}

/// One zone as solved.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct LaidZone {
    /// Its name.
    pub name: ZoneName,
    /// Where its content goes: its strip when folded, its body when over,
    /// an empty rect when hidden. Cut at the parent's edge when even the
    /// least sizes do not fit.
    pub rect: Rect,
    /// How it is shown.
    pub shown: Shown,
    /// Its strip, when folded or over.
    pub strip: Option<Rect>,
    /// Its least size along its parent's axis, as solved (0 at the root).
    pub least: f32,
    /// Its largest size along its parent's axis, as solved (infinite when
    /// unbounded, and at the root).
    pub most: f32,
    /// Its content, for a leaf; `None` for a split.
    pub content: Option<Content>,
    /// Whether a dragged item may be dropped in it.
    pub drops: Drops,
    /// Whether a tab dropped on its strip, while folded, joins its dock
    /// ([`Constraints::strip_drops`](super::Constraints::strip_drops)).
    pub strip_drops: bool,
    /// For a split, the docks its leaves hold ([`Content::Dock`]), depth first, leaving out
    /// the zones hidden, collapsed or refusing drops; empty for a leaf.
    pub docks: Vec<String>,
    /// For a collapsed zone ([`Shown::Collapsed`]), where it would come back.
    pub restore: Option<Restore>,
}

/// Where a collapsed zone ([`Shown::Collapsed`]) would come back, in
/// [`LaidZone::restore`].
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Restore {
    /// Its former boundary: a line across its parent split, where the zone
    /// lies with no breadth; the parent's outer edge when no zone is left
    /// between it and that edge.
    pub line: Rect,
    /// Its parent split's axis.
    pub dir: Dir,
    /// Whether the zone comes back after the line along `dir` (to its right
    /// or below it), else before it.
    pub towards_end: bool,
    /// The rect it would take back: its remembered size
    /// ([`ZoneState::size`](super::ZoneState::size), else its default) within
    /// its current bounds, its siblings giving way as when it is unfolded.
    pub rect: Rect,
}

impl LaidZone {
    /// The dock it shows, for a leaf holding [`Content::Dock`].
    pub fn dock(&self) -> Option<&str> {
        match &self.content {
            Some(Content::Dock(name)) => Some(name),
            _ => None,
        }
    }
}

/// What changed in a layout while a [`LayoutArea`](super::LayoutArea) drew
/// it: the user's acts, each already applied to the [`Layout`], and the zones
/// the solver folded or brought back by itself. The application's own
/// changes ([`Layout::set_folded`](super::Layout::set_folded) and the like)
/// are not reported: it made them.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LayoutEvent {
    /// A sash, or the keyboard, gave the zone this size in points.
    Resized {
        /// The zone.
        zone: ZoneName,
        /// Its new [`ZoneState::size`](super::ZoneState::size).
        size: f32,
    },
    /// The zone went back to its default size (a sash's double click or
    /// Enter).
    Reset {
        /// The zone.
        zone: ZoneName,
    },
    /// The zone folded to its strip: a sash dragged it under half its
    /// least size, its grip was clicked while it lay over, or it lay over
    /// and Escape or a click outside closed it.
    Folded {
        /// The zone.
        zone: ZoneName,
    },
    /// The zone unfolded, back in the flow: its strip's grip was clicked.
    Unfolded {
        /// The zone.
        zone: ZoneName,
    },
    /// The flyout asked to close (Escape, a click outside it, its strip's
    /// grip, its zone unfolded): the application stops giving it to
    /// [`LayoutArea::flyout`](super::LayoutArea::flyout).
    FlyoutClosed {
        /// The flyout's key.
        key: String,
    },
    /// The flyout's free edge gave it this breadth, kept in
    /// [`Layout::flyouts`].
    FlyoutResized {
        /// The flyout's key.
        key: String,
        /// Its breadth, in points.
        size: f32,
    },
    /// The solver folded the zone by itself, short of room
    /// ([`Constraints::auto_fold`](super::Constraints::auto_fold)): it shows
    /// as [`Shown::AutoFolded`]. Its [`ZoneState::folded`](super::ZoneState::folded)
    /// is not touched: the zone comes back with the room.
    AutoFolded {
        /// The zone.
        zone: ZoneName,
    },
    /// The room came back for a zone the solver had folded
    /// ([`AutoFolded`](Self::AutoFolded)): it is no longer
    /// [`Shown::AutoFolded`]. A zone opened over from its auto-folded strip
    /// ([`OpenedOver`](Self::OpenedOver)) still counts as auto-folded: it is
    /// reported once it is closed with the room back.
    AutoUnfolded {
        /// The zone.
        zone: ZoneName,
    },
    /// A folded zone's strip was clicked (its grip, its bare body or its
    /// edge), whatever [`ZoneViewer::on_strip`](super::ZoneViewer::on_strip)
    /// made of it; what it did follows as its own event.
    StripClicked {
        /// The zone.
        zone: ZoneName,
        /// How it was shown when clicked: [`Shown::Folded`],
        /// [`Shown::AutoFolded`] or [`Shown::Over`].
        shown: Shown,
    },
    /// The zone opened over its neighbour from its strip
    /// ([`StripAction::Over`](super::StripAction::Over), by default on an
    /// auto-folded strip).
    OpenedOver {
        /// The zone.
        zone: ZoneName,
    },
    /// A zone opened over from its auto-folded strip was closed (its strip,
    /// Escape or a press outside): it is back in its automatic state,
    /// neither folded nor over, and unfolds by itself once the room comes
    /// back. A zone the user had folded reports [`Folded`](Self::Folded)
    /// instead.
    ClosedOver {
        /// The zone.
        zone: ZoneName,
    },
}

/// Where every zone goes: the solver's output, parents first. Zones under a
/// folded or hidden zone are not laid.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Laid {
    /// The zones, parents first.
    pub zones: Vec<LaidZone>,
    /// What the user changed this frame, when drawn by a
    /// [`LayoutArea`](super::LayoutArea); empty from [`Layout::solve`].
    pub events: Vec<LayoutEvent>,
    /// The flyout's rect, when one was drawn.
    pub flyout: Option<Rect>,
}

impl Laid {
    /// The zone named `name`, when laid.
    pub fn get(&self, name: &str) -> Option<&LaidZone> {
        self.zones.iter().find(|zone| zone.name == *name)
    }

    /// The rect of the zone named `name`, when laid.
    pub fn rect(&self, name: &str) -> Option<Rect> {
        self.get(name).map(|zone| zone.rect)
    }
}

impl Layout {
    /// Lays the zones out in `rect`; the root takes all of it. Pure: the
    /// layout is not changed, and a zone the solver shows smaller, or folds,
    /// keeps its state.
    pub fn solve(&self, rect: Rect, solve: &Solve) -> Laid {
        let mut laid = Laid::default();
        laid.zones.push(LaidZone {
            name: self.root.name.clone(),
            rect,
            shown: Shown::Open,
            strip: None,
            least: 0.0,
            most: f32::INFINITY,
            content: leaf_content(&self.root),
            drops: self.root.constraints.drops,
            strip_drops: false,
            docks: split_docks(&self.root),
            restore: None,
        });
        lay_children(&self.root, rect, solve, &mut laid);
        laid
    }
}

/// A child's place in a split, before positions.
#[derive(Clone, Copy, Debug)]
struct Sized {
    shown: Shown,
    least: f32,
    most: f32,
    /// Its size in the flow.
    size: f32,
    /// Its body's size, when over.
    body: f32,
}

fn lay_children(zone: &Zone, rect: Rect, solve: &Solve, laid: &mut Laid) {
    let ZoneKind::Split { dir, children } = &zone.kind else {
        return;
    };
    if children.is_empty() {
        return;
    }
    let length = along(*dir, rect.size());
    let (sized, taker) = sizes(children, length, solve, None);
    let mut pos = along(*dir, rect.min.to_vec2());
    let start = pos;
    let end = start + length;
    for (i, (child, s)) in children.iter().zip(&sized).enumerate() {
        let span = |a: f32, b: f32| span(*dir, rect, a.clamp(start, end), b.clamp(start, end));
        let flow = span(pos, pos + s.size);
        let (child_rect, strip) = match s.shown {
            Shown::Open => (flow, None),
            Shown::Folded | Shown::AutoFolded => (flow, Some(flow)),
            Shown::Hidden | Shown::Collapsed => (span(pos, pos), None),
            Shown::Over => {
                let towards_end = taker.is_none_or(|t| i < t);
                let body = if towards_end {
                    span(pos + s.size, pos + s.size + s.body)
                } else {
                    span(pos - s.body, pos)
                };
                (body, Some(flow))
            }
        };
        let restore = (s.shown == Shown::Collapsed).then(|| {
            // Solved again with the zone unfolded: where it would come back.
            let (unfolded, _) = sizes(children, length, solve, Some(i));
            let from = start + unfolded[..i].iter().map(|u| u.size).sum::<f32>();
            let rect = span(from, from + unfolded[i].size);
            let line = span(pos, pos);
            Restore {
                line,
                dir: *dir,
                towards_end: along(*dir, rect.center().to_vec2()) >= pos,
                rect,
            }
        });
        pos += s.size;
        laid.zones.push(LaidZone {
            name: child.name.clone(),
            rect: child_rect,
            shown: s.shown,
            strip,
            least: s.least,
            most: s.most,
            content: leaf_content(child),
            drops: child.constraints.drops,
            strip_drops: child.constraints.strip_drops,
            docks: split_docks(child),
            restore,
        });
        if matches!(s.shown, Shown::Open | Shown::Over) {
            lay_children(child, child_rect, solve, laid);
        }
    }
}

/// Each child's size along a split of `length`, and the child that takes
/// the rest (the one that grows, else the last open one): lying-over zones
/// open towards it.
/// With `unfold`, that child is solved as if it were not folded.
fn sizes(
    children: &[Zone],
    length: f32,
    solve: &Solve,
    unfold: Option<usize>,
) -> (Vec<Sized>, Option<usize>) {
    let grow = children
        .iter()
        .position(|c| c.constraints.grow && !c.state.hidden);
    let mut auto_folded: Vec<usize> = Vec::new();
    loop {
        let (sized, short) = fit(children, length, solve, grow, &auto_folded, unfold);
        if short <= 0.0 {
            let taker = taker(&sized, grow);
            return (sized, taker);
        }
        // Even the least sizes do not fit: the next zone that opted in
        // folds, lowest priority first, then the nearest to the one that
        // takes the rest.
        let taker = taker(&sized, grow);
        let next = giving_order(children, &sized, taker)
            .into_iter()
            .find(|&i| {
                let c = &children[i].constraints;
                c.fold == Fold::ToStrip && c.auto_fold && !auto_folded.contains(&i)
            });
        match next {
            Some(i) => auto_folded.push(i),
            None => return (sized, taker),
        }
    }
}

/// The child that takes the rest: the one that grows, else the last open one.
fn taker(sized: &[Sized], grow: Option<usize>) -> Option<usize> {
    grow.or_else(|| sized.iter().rposition(|s| s.shown == Shown::Open))
}

/// The open children other than `taker`, in the order they give way: the
/// lowest priority first, then the nearest to `taker`, then the first.
fn giving_order(children: &[Zone], sized: &[Sized], taker: Option<usize>) -> Vec<usize> {
    let Some(taker) = taker else {
        return Vec::new();
    };
    let mut order: Vec<usize> = (0..children.len())
        .filter(|&i| i != taker && sized[i].shown == Shown::Open)
        .collect();
    order.sort_by_key(|&i| (children[i].constraints.priority, i.abs_diff(taker), i));
    order
}

/// The sizes with the children in `auto_folded` folded, and how much the
/// taker's least size is still short of.
fn fit(
    children: &[Zone],
    length: f32,
    solve: &Solve,
    grow: Option<usize>,
    auto_folded: &[usize],
    unfold: Option<usize>,
) -> (Vec<Sized>, f32) {
    let folded = |i: usize, c: &Zone| c.state.folded && Some(i) != unfold;
    // A zone that collapses never lies over its neighbour: it has no strip.
    let over = |c: &Zone| c.state.over && c.constraints.fold != Fold::Collapse;
    let fixed = |i: usize, c: &Zone| {
        Some(i) != grow && (c.state.hidden || folded(i, c) || auto_folded.contains(&i))
    };
    let flexible = children
        .iter()
        .enumerate()
        .filter(|&(i, c)| !fixed(i, c) && (!over(c) || Some(i) == grow))
        .count()
        .max(1);
    let even = length / flexible as f32;
    let mut sized: Vec<Sized> = children
        .iter()
        .enumerate()
        .map(|(i, child)| {
            let c = &child.constraints;
            let mut least = c.min.map_or(0.0, |s| s.points(length)).max(0.0);
            if c.fit_content
                && let Some(&asked) = solve.content.get(&child.name)
            {
                least = least.max(asked);
            }
            let most = c.max.map_or(f32::INFINITY, |s| s.points(length)).max(least);
            let wanted = child
                .state
                .size
                .or_else(|| c.default.map(|s| s.points(length)))
                .unwrap_or(even);
            let open = wanted.clamp(least, most);
            let is_grow = Some(i) == grow;
            let (shown, size) = if child.state.hidden && !is_grow {
                (Shown::Hidden, 0.0)
            } else if auto_folded.contains(&i) {
                (Shown::AutoFolded, solve.strip)
            } else if folded(i, child) && !is_grow && c.fold == Fold::Collapse {
                (Shown::Collapsed, 0.0)
            } else if folded(i, child) && !is_grow {
                (Shown::Folded, solve.strip)
            } else if over(child) && !is_grow {
                (Shown::Over, solve.strip)
            } else {
                (Shown::Open, open)
            };
            Sized {
                shown,
                least,
                most,
                size,
                body: open,
            }
        })
        .collect();
    let Some(taker) = taker(&sized, grow) else {
        return (sized, 0.0);
    };
    let others: f32 = (0..sized.len())
        .filter(|&i| i != taker)
        .map(|i| sized[i].size)
        .sum();
    let rest = length - others;
    let order = giving_order(children, &sized, taker.into());
    let mut short = 0.0;
    if rest < sized[taker].least {
        // The others give way, in turn, each down to its least size.
        let mut sizes: Vec<f32> = sized.iter().map(|s| s.size).collect();
        let owed = sized[taker].least - rest;
        let given = give_in_turn(&mut sizes, |i| sized[i].least, order, owed);
        for (s, size) in sized.iter_mut().zip(sizes) {
            s.size = size;
        }
        short = owed - given;
        sized[taker].size = sized[taker].least;
    } else if rest > sized[taker].most {
        // The others take the surplus up to their largest size, the
        // highest priority first; what is left stays with the zone that
        // grows, or empty after the last zone.
        let mut surplus = rest - sized[taker].most;
        let mut by_priority = order;
        by_priority.sort_by_key(|&i| std::cmp::Reverse(children[i].constraints.priority));
        for i in by_priority {
            let took = (sized[i].most - sized[i].size).max(0.0).min(surplus);
            sized[i].size += took;
            surplus -= took;
        }
        sized[taker].size = sized[taker].most;
        if grow.is_some() {
            sized[taker].size += surplus;
        }
    } else {
        sized[taker].size = rest;
    }
    (sized, short)
}

/// The docks a split's leaves hold, depth first, but those hidden, collapsed or refusing drops;
/// none for a leaf.
fn split_docks(zone: &Zone) -> Vec<String> {
    fn visit(zone: &Zone, docks: &mut Vec<String>) {
        let collapsed = zone.state.folded && zone.constraints.fold == Fold::Collapse;
        if zone.state.hidden || collapsed || zone.constraints.drops == Drops::Refuse {
            return;
        }
        match &zone.kind {
            ZoneKind::Leaf {
                content: Content::Dock(name),
            } => docks.push(name.clone()),
            ZoneKind::Leaf { .. } => {}
            ZoneKind::Split { children, .. } => {
                for child in children {
                    visit(child, docks);
                }
            }
        }
    }
    let mut docks = Vec::new();
    if let ZoneKind::Split { children, .. } = &zone.kind {
        for child in children {
            visit(child, &mut docks);
        }
    }
    docks
}

fn leaf_content(zone: &Zone) -> Option<Content> {
    match &zone.kind {
        ZoneKind::Leaf { content } => Some(content.clone()),
        ZoneKind::Split { .. } => None,
    }
}

pub(super) fn along(dir: Dir, v: egui::Vec2) -> f32 {
    match dir {
        Dir::Horizontal => v.x,
        Dir::Vertical => v.y,
    }
}

/// The part of `rect` between `a` and `b` along `dir`.
pub(super) fn span(dir: Dir, rect: Rect, a: f32, b: f32) -> Rect {
    let (min, max): (Pos2, Pos2) = match dir {
        Dir::Horizontal => (pos2(a, rect.min.y), pos2(b, rect.max.y)),
        Dir::Vertical => (pos2(rect.min.x, a), pos2(rect.max.x, b)),
    };
    Rect::from_min_max(min, max)
}