Skip to main content

egui_pop_model/
layout.rs

1//! A workspace's arrangement: which panels sit in which area, in which
2//! tabs and splits, which ones were detached into auxiliary windows and on
3//! which screen. Saved as the `layout` document, restored at start-up,
4//! repaired when it no longer matches the panels or the screens.
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use serde::{Deserialize, Serialize};
9use serde_json::Value as Json;
10
11use crate::doc::{Schema, same};
12use crate::ids::PanelId;
13use crate::panels::{Area, Panels};
14
15/// The main application window's id in a layout: its areas, its detached
16/// windows and its floating groups ([`Layout::panels_in_window`]); every
17/// other window is named by its own id ([`Layout::windows`]).
18pub const MAIN_WINDOW: &str = "main";
19
20/// Tabs, splits and grids of one area.
21///
22/// A row or a column of more than two is saved as splits nested on their
23/// second side (`b`), each `ratio` the share of `a` in its split.
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25#[serde(tag = "kind", rename_all = "lowercase")]
26pub enum Node {
27    /// Panels as tabs; `active` is the shown one.
28    Tabs { panels: Vec<PanelId>, active: usize },
29    Split {
30        vertical: bool,
31        ratio: f32,
32        a: Box<Node>,
33        b: Box<Node>,
34    },
35    /// Two or more nodes in rows and columns, row by row.
36    Grid {
37        /// The number of columns; none for as many as the square root of
38        /// the number of children, rounded up.
39        #[serde(default, skip_serializing_if = "Option::is_none")]
40        columns: Option<usize>,
41        /// One share per column and one per row (even when empty or when
42        /// they do not match the layout).
43        #[serde(default, skip_serializing_if = "Vec::is_empty")]
44        col_shares: Vec<f32>,
45        #[serde(default, skip_serializing_if = "Vec::is_empty")]
46        row_shares: Vec<f32>,
47        children: Vec<Node>,
48    },
49}
50
51impl Node {
52    /// One tab.
53    pub fn tab(panel: PanelId) -> Node {
54        Node::Tabs {
55            panels: vec![panel],
56            active: 0,
57        }
58    }
59
60    pub fn panels(&self) -> Vec<&PanelId> {
61        match self {
62            Node::Tabs { panels, .. } => panels.iter().collect(),
63            Node::Split { a, b, .. } => {
64                let mut v = a.panels();
65                v.extend(b.panels());
66                v
67            }
68            Node::Grid { children, .. } => children.iter().flat_map(Node::panels).collect(),
69        }
70    }
71
72    /// Makes a panel the shown tab of its tabs; whether it is here.
73    fn activate(&mut self, panel: &PanelId) -> bool {
74        match self {
75            Node::Tabs { panels, active } => match panels.iter().position(|p| p == panel) {
76                Some(i) => {
77                    *active = i;
78                    true
79                }
80                None => false,
81            },
82            Node::Split { a, b, .. } => a.activate(panel) || b.activate(panel),
83            Node::Grid { children, .. } => children.iter_mut().any(|c| c.activate(panel)),
84        }
85    }
86
87    /// Adds a panel to the first tabs, shown.
88    fn push(&mut self, panel: PanelId) {
89        match self {
90            Node::Tabs { panels, active } => {
91                panels.push(panel);
92                *active = panels.len() - 1;
93            }
94            Node::Split { a, .. } => a.push(panel),
95            Node::Grid { children, .. } => {
96                if let Some(first) = children.first_mut() {
97                    first.push(panel);
98                }
99            }
100        }
101    }
102
103    /// The tabs holding a panel: the other panels there and its index.
104    fn tabs_of(&self, panel: &PanelId) -> Option<(Vec<PanelId>, usize)> {
105        match self {
106            Node::Tabs { panels, .. } => panels.iter().position(|p| p == panel).map(|i| {
107                let others = panels.iter().filter(|p| *p != panel).cloned().collect();
108                (others, i)
109            }),
110            Node::Split { a, b, .. } => a.tabs_of(panel).or_else(|| b.tabs_of(panel)),
111            Node::Grid { children, .. } => children.iter().find_map(|c| c.tabs_of(panel)),
112        }
113    }
114
115    /// Puts a panel back at `index` in the tabs holding one of `beside`,
116    /// the shown tab kept shown; whether some tabs held one.
117    fn insert_beside(&mut self, panel: &PanelId, beside: &[PanelId], index: usize) -> bool {
118        match self {
119            Node::Tabs { panels, active } => {
120                if !panels.iter().any(|p| beside.contains(p)) {
121                    return false;
122                }
123                let at = index.min(panels.len());
124                panels.insert(at, panel.clone());
125                if *active >= at && panels.len() > 1 {
126                    *active += 1;
127                }
128                true
129            }
130            Node::Split { a, b, .. } => {
131                a.insert_beside(panel, beside, index) || b.insert_beside(panel, beside, index)
132            }
133            Node::Grid { children, .. } => children
134                .iter_mut()
135                .any(|c| c.insert_beside(panel, beside, index)),
136        }
137    }
138
139    /// Drops panels that are not in `keep`; `None` when nothing is left.
140    fn retain(self, keep: &dyn Fn(&PanelId) -> bool) -> Option<Node> {
141        match self {
142            Node::Tabs { panels, active } => {
143                let shown = panels.get(active).cloned();
144                let panels: Vec<PanelId> = panels.into_iter().filter(|p| keep(p)).collect();
145                if panels.is_empty() {
146                    return None;
147                }
148                let active = shown
149                    .and_then(|s| panels.iter().position(|p| *p == s))
150                    .unwrap_or(0);
151                Some(Node::Tabs { panels, active })
152            }
153            Node::Split {
154                vertical,
155                ratio,
156                a,
157                b,
158            } => match (a.retain(keep), b.retain(keep)) {
159                (Some(a), Some(b)) => Some(Node::Split {
160                    vertical,
161                    ratio: ratio.clamp(0.05, 0.95),
162                    a: Box::new(a),
163                    b: Box::new(b),
164                }),
165                (Some(n), None) | (None, Some(n)) => Some(n),
166                (None, None) => None,
167            },
168            Node::Grid {
169                columns,
170                col_shares,
171                row_shares,
172                children,
173            } => {
174                let before = children.len();
175                let mut children: Vec<Node> = children
176                    .into_iter()
177                    .filter_map(|c| c.retain(keep))
178                    .collect();
179                match children.len() {
180                    0 => None,
181                    1 => children.pop(),
182                    n => {
183                        // A grid that lost children lays them out evenly.
184                        let kept = n == before;
185                        Some(Node::Grid {
186                            columns,
187                            col_shares: if kept { col_shares } else { Vec::new() },
188                            row_shares: if kept { row_shares } else { Vec::new() },
189                            children,
190                        })
191                    }
192                }
193            }
194        }
195    }
196}
197
198/// A panel detached into its own window, and the panels that joined it
199/// there as tabs.
200///
201/// Saved as the window it was before tabs (its first panel under
202/// `panel`), the others under `tabs`: an application that predates them
203/// reads the first panel and puts the others back as it does any panel
204/// missing from a layout (docked in its default area).
205///
206/// ```
207/// use egui_pop_model::ids::PanelId;
208/// use egui_pop_model::layout::Auxiliary;
209///
210/// let log = PanelId::from_static("app.log");
211/// let notes = PanelId::from_static("app.notes");
212/// let mut w = Auxiliary::window(log.clone(), "main", [0.0, 0.0, 640.0, 480.0]);
213/// w.join(notes.clone());
214/// assert_eq!(w.panels().count(), 2);
215/// assert_eq!(w.shown(), &notes);
216/// ```
217#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
218pub struct Auxiliary {
219    /// The panel detached first: it names the window.
220    pub panel: PanelId,
221    /// The screen it was on, by name, and its position there.
222    pub screen: String,
223    pub rect: [f32; 4],
224    /// The panels that joined the window as tabs, after `panel`.
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    pub tabs: Vec<PanelId>,
227    /// The shown tab: 0 for `panel`, `n` for `tabs[n - 1]`.
228    #[serde(default, skip_serializing_if = "is_zero")]
229    pub shown: usize,
230    /// Maximized: it opens so again, `rect` keeping its normal size.
231    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
232    pub maximized: bool,
233    /// In full screen: it opens so again.
234    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
235    pub fullscreen: bool,
236}
237
238impl Auxiliary {
239    /// A window showing one panel.
240    pub fn window(panel: PanelId, screen: &str, rect: [f32; 4]) -> Auxiliary {
241        Auxiliary {
242            panel,
243            screen: screen.to_string(),
244            rect,
245            tabs: Vec::new(),
246            shown: 0,
247            maximized: false,
248            fullscreen: false,
249        }
250    }
251
252    /// Its panels, in order.
253    pub fn panels(&self) -> impl Iterator<Item = &PanelId> {
254        std::iter::once(&self.panel).chain(&self.tabs)
255    }
256
257    /// Whether a panel is one of its panels.
258    pub fn holds(&self, panel: &PanelId) -> bool {
259        self.panels().any(|p| p == panel)
260    }
261
262    /// The panel shown.
263    pub fn shown(&self) -> &PanelId {
264        match self.shown.min(self.tabs.len()) {
265            0 => &self.panel,
266            n => &self.tabs[n - 1],
267        }
268    }
269
270    /// Shows one of its tabs; whether it holds it.
271    pub fn show(&mut self, panel: &PanelId) -> bool {
272        let at = self.panels().position(|p| p == panel);
273        if let Some(i) = at {
274            self.shown = i;
275        }
276        at.is_some()
277    }
278
279    /// A panel joins it as its last tab, shown (already there: shown).
280    pub fn join(&mut self, panel: PanelId) {
281        if !self.holds(&panel) {
282            self.tabs.push(panel.clone());
283        }
284        self.show(&panel);
285    }
286
287    /// Its panels in another order (the same panels): the shown one
288    /// stays shown.
289    pub fn reorder(&mut self, panels: &[PanelId]) {
290        let mut now: Vec<&PanelId> = self.panels().collect();
291        let mut next: Vec<&PanelId> = panels.iter().collect();
292        now.sort();
293        next.sort();
294        if panels.is_empty() || now != next {
295            return;
296        }
297        let shown = self.shown().clone();
298        self.panel = panels[0].clone();
299        self.tabs = panels[1..].to_vec();
300        self.show(&shown);
301    }
302
303    /// Takes a panel out; `false` when it was its only one (the window
304    /// is left as it was, to be dropped). The shown tab out, its
305    /// neighbour on the right is shown, or on the left at the end.
306    fn take(&mut self, panel: &PanelId) -> bool {
307        let Some(i) = self.panels().position(|p| p == panel) else {
308            return true;
309        };
310        if self.tabs.is_empty() {
311            return false;
312        }
313        let shown = self.shown.min(self.tabs.len());
314        if i == 0 {
315            self.panel = self.tabs.remove(0);
316        } else {
317            self.tabs.remove(i - 1);
318        }
319        self.shown = if shown > i || (shown == i && shown > self.tabs.len()) {
320            shown - 1
321        } else {
322            shown
323        };
324        true
325    }
326}
327
328/// One member of a floating group: a palette, or palettes held as tabs
329/// in one slot of a stack (a tab group nested in the stack, one level
330/// only).
331///
332/// Saved as the palette it was before nesting (its first tab's `panel`),
333/// the other tabs under `tabs`: an application that predates nesting
334/// reads the first tab and puts the others back as it does any panel
335/// missing from a layout (a palette floats again on its own).
336///
337/// ```
338/// use egui_pop_model::ids::PanelId;
339/// use egui_pop_model::layout::Member;
340///
341/// let tools = PanelId::from_static("app.tools");
342/// let m = Member::palette(tools.clone());
343/// assert!(!m.is_tabs());
344/// assert_eq!(m.shown(), &tools);
345/// ```
346#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
347pub struct Member {
348    /// The palette, or the first of its tabs.
349    pub panel: PanelId,
350    /// Rolled up to its header band (each member of a stack rolls up on
351    /// its own; a tab group rolls up as one).
352    #[serde(default, skip_serializing_if = "is_false")]
353    pub rolled: bool,
354    /// The panels held as tabs with `panel`, after it: empty for a
355    /// palette.
356    #[serde(default, skip_serializing_if = "Vec::is_empty")]
357    pub tabs: Vec<PanelId>,
358    /// The shown tab: 0 for `panel`, `n` for `tabs[n - 1]`.
359    #[serde(default, skip_serializing_if = "is_zero")]
360    pub shown: usize,
361}
362
363impl Member {
364    /// A palette, rolled down.
365    pub fn palette(panel: PanelId) -> Member {
366        Member {
367            panel,
368            rolled: false,
369            tabs: Vec::new(),
370            shown: 0,
371        }
372    }
373
374    /// Whether it holds tabs (a tab group nested in a stack).
375    pub fn is_tabs(&self) -> bool {
376        !self.tabs.is_empty()
377    }
378
379    /// Its panels, in order.
380    pub fn panels(&self) -> impl Iterator<Item = &PanelId> {
381        std::iter::once(&self.panel).chain(&self.tabs)
382    }
383
384    /// Whether a panel is one of its panels.
385    pub fn holds(&self, panel: &PanelId) -> bool {
386        self.panels().any(|p| p == panel)
387    }
388
389    /// The panel shown: the palette, or its shown tab.
390    pub fn shown(&self) -> &PanelId {
391        match self.shown.min(self.tabs.len()) {
392            0 => &self.panel,
393            n => &self.tabs[n - 1],
394        }
395    }
396
397    /// Shows one of its tabs; whether it holds it.
398    pub fn show(&mut self, panel: &PanelId) -> bool {
399        let at = self.panels().position(|p| p == panel);
400        if let Some(i) = at {
401            self.shown = i;
402        }
403        at.is_some()
404    }
405
406    /// Its panels as a list, and back.
407    fn list(&self) -> Vec<PanelId> {
408        self.panels().cloned().collect()
409    }
410
411    fn from_list(mut panels: Vec<PanelId>, shown: usize, rolled: bool) -> Member {
412        let panel = panels.remove(0);
413        Member {
414            panel,
415            rolled,
416            shown: shown.min(panels.len()),
417            tabs: panels,
418        }
419    }
420
421    /// Takes one of its tabs out (not its only panel); the shown tab out,
422    /// its neighbour on the right is shown, or on the left at the end.
423    fn take_tab(&mut self, panel: &PanelId) -> bool {
424        let mut list = self.list();
425        let Some(i) = list.iter().position(|p| p == panel) else {
426            return false;
427        };
428        if list.len() == 1 {
429            return false;
430        }
431        list.remove(i);
432        let shown = shown_after_removal(self.shown, i, list.len());
433        *self = Member::from_list(list, shown, self.rolled);
434        true
435    }
436
437    /// Its panels as palettes of their own (a tab group taken apart).
438    fn split(self) -> Vec<Member> {
439        let rolled = self.rolled;
440        self.panels()
441            .cloned()
442            .map(|p| Member {
443                rolled,
444                ..Member::palette(p)
445            })
446            .collect()
447    }
448}
449
450/// The shown index once the item at `removed` is out of a list now `len`
451/// long: an earlier one shifts it left; the shown one out, its right
452/// neighbour (now at its index) shows, or the left one at the end.
453fn shown_after_removal(shown: usize, removed: usize, len: usize) -> usize {
454    let shown = if removed < shown { shown - 1 } else { shown };
455    shown.min(len.saturating_sub(1))
456}
457
458/// How the members of a floating group are laid out.
459#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
460#[serde(rename_all = "snake_case")]
461pub enum Arrangement {
462    /// One under the other, in a column.
463    #[default]
464    Stack,
465    /// As tabs, one shown at a time.
466    Tabs,
467}
468
469impl Arrangement {
470    fn is_stack(&self) -> bool {
471        *self == Arrangement::Stack
472    }
473
474    /// Its name in documents and arguments.
475    pub fn as_str(self) -> &'static str {
476        match self {
477            Arrangement::Stack => "stack",
478            Arrangement::Tabs => "tabs",
479        }
480    }
481}
482
483/// Where a palette joins another one's group: above it, below it (a
484/// stack), or as a tab of it.
485#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
486pub enum Join {
487    Above,
488    Below,
489    Tab,
490}
491
492impl Join {
493    /// Its name in step arguments.
494    pub fn as_str(self) -> &'static str {
495        match self {
496            Join::Above => "above",
497            Join::Below => "below",
498            Join::Tab => "tab",
499        }
500    }
501
502    /// A place from its name.
503    pub fn parse(name: &str) -> Option<Join> {
504        [Join::Above, Join::Below, Join::Tab]
505            .into_iter()
506            .find(|j| j.as_str() == name)
507    }
508}
509
510/// Panels floating over the interface as one unit: a palette alone (a
511/// group of one), or palettes stacked in a column or held as tabs. A
512/// stack's member may itself be a tab group ([`Member::tabs`]): one level
513/// of nesting, a tab group never holding a stack. The group moves, pins,
514/// anchors and is resized as one; each member rolls up on its own.
515///
516/// Saved as the floating panel it was before groups (its first member's
517/// `panel` and `rolled`, the group's `pos`, `pinned` and `anchor`), the
518/// other members under `group`: an application that predates groups
519/// reads the first member and floats the others again as new palettes.
520/// A nested tab group is saved as its first tab with the others under
521/// `tabs` (see [`Member`]).
522///
523/// ```
524/// use egui_pop_model::ids::PanelId;
525/// use egui_pop_model::layout::{Arrangement, FloatingGroup};
526///
527/// let tools = PanelId::from_static("app.tools");
528/// let g = FloatingGroup::lone(tools.clone(), [16.0, 16.0]);
529/// assert_eq!(g.panels().collect::<Vec<_>>(), [&tools]);
530/// assert_eq!(g.arrangement, Arrangement::Stack);
531/// ```
532#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
533#[serde(from = "GroupDoc", into = "GroupDoc")]
534pub struct FloatingGroup {
535    /// Its members, in order (never empty): top to bottom in a stack,
536    /// start to end as tabs.
537    pub members: Vec<Member>,
538    pub arrangement: Arrangement,
539    /// The shown member of tabs.
540    pub active: usize,
541    /// Its top-left corner, in points from the workbench's top-left.
542    pub pos: [f32; 2],
543    /// Pinned: it stays where it is and in sight (not dragged, not
544    /// hidden with the others, not faded).
545    pub pinned: bool,
546    /// The workbench edges it sticks to: set when it is dropped on them,
547    /// kept as the window is resized or the layout restored.
548    pub anchor: Anchor,
549    /// Its size, in points, once the user resized it (its frame, bands
550    /// included); `None`: sized by its content.
551    pub size: Option<[f32; 2]>,
552}
553
554/// A floating group as saved (see [`FloatingGroup`]).
555#[derive(Clone, Serialize, Deserialize)]
556struct GroupDoc {
557    panel: PanelId,
558    pos: [f32; 2],
559    #[serde(default, skip_serializing_if = "is_false")]
560    rolled: bool,
561    /// The first member's other tabs, when it is a nested tab group.
562    #[serde(default, skip_serializing_if = "Vec::is_empty")]
563    tabs: Vec<PanelId>,
564    /// The first member's shown tab.
565    #[serde(default, skip_serializing_if = "is_zero")]
566    shown: usize,
567    #[serde(default, skip_serializing_if = "is_false")]
568    pinned: bool,
569    #[serde(default, skip_serializing_if = "Anchor::is_none")]
570    anchor: Anchor,
571    /// The other members, after the first.
572    #[serde(default, skip_serializing_if = "Vec::is_empty")]
573    group: Vec<Member>,
574    #[serde(default, skip_serializing_if = "Arrangement::is_stack")]
575    arrangement: Arrangement,
576    #[serde(default, skip_serializing_if = "is_zero")]
577    active: usize,
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    size: Option<[f32; 2]>,
580}
581
582fn is_zero(n: &usize) -> bool {
583    *n == 0
584}
585
586impl From<GroupDoc> for FloatingGroup {
587    fn from(d: GroupDoc) -> Self {
588        let mut members = vec![Member {
589            panel: d.panel,
590            rolled: d.rolled,
591            tabs: d.tabs,
592            shown: d.shown,
593        }];
594        members.extend(d.group);
595        let mut g = FloatingGroup {
596            members,
597            arrangement: d.arrangement,
598            active: d.active,
599            pos: d.pos,
600            pinned: d.pinned,
601            anchor: d.anchor,
602            size: d.size,
603        };
604        g.tidy();
605        g
606    }
607}
608
609impl From<FloatingGroup> for GroupDoc {
610    fn from(g: FloatingGroup) -> Self {
611        let mut members = g.members.into_iter();
612        let first = members.next().expect("a floating group has a member");
613        GroupDoc {
614            panel: first.panel,
615            pos: g.pos,
616            rolled: first.rolled,
617            tabs: first.tabs,
618            shown: first.shown,
619            pinned: g.pinned,
620            anchor: g.anchor,
621            group: members.collect(),
622            arrangement: g.arrangement,
623            active: g.active,
624            size: g.size,
625        }
626    }
627}
628
629impl FloatingGroup {
630    /// A palette floating alone at `pos`.
631    pub fn lone(panel: PanelId, pos: [f32; 2]) -> FloatingGroup {
632        FloatingGroup {
633            members: vec![Member::palette(panel)],
634            arrangement: Arrangement::Stack,
635            active: 0,
636            pos,
637            pinned: false,
638            anchor: Anchor::default(),
639            size: None,
640        }
641    }
642
643    /// Where the `n`th palette opens when it has no place yet: down and
644    /// right from the workbench's top-left, one step each.
645    pub fn cascade(n: usize) -> [f32; 2] {
646        let at = 16.0 + 28.0 * (n % 8) as f32;
647        [at, at]
648    }
649
650    /// Its panels, in order (a nested tab group's tabs in their order).
651    pub fn panels(&self) -> impl Iterator<Item = &PanelId> {
652        self.members.iter().flat_map(Member::panels)
653    }
654
655    /// Whether a panel is one of its panels.
656    pub fn holds(&self, panel: &PanelId) -> bool {
657        self.members.iter().any(|m| m.holds(panel))
658    }
659
660    /// The member holding a panel (a nested tab group for any of its
661    /// tabs).
662    pub fn member(&self, panel: &PanelId) -> Option<&Member> {
663        self.members.iter().find(|m| m.holds(panel))
664    }
665
666    /// The member holding a panel, to change it.
667    pub fn member_mut(&mut self, panel: &PanelId) -> Option<&mut Member> {
668        self.members.iter_mut().find(|m| m.holds(panel))
669    }
670
671    /// Whether the member holding a panel is rolled up (`false` for a
672    /// panel not in it).
673    pub fn rolled(&self, panel: &PanelId) -> bool {
674        self.member(panel).is_some_and(|m| m.rolled)
675    }
676
677    /// Its first member's first panel: the one that names it in steps.
678    pub fn lead(&self) -> &PanelId {
679        &self.members[0].panel
680    }
681
682    /// The member shown: the active tab, or the first of a stack (its
683    /// shown tab, for a nested tab group).
684    pub fn shown(&self) -> &PanelId {
685        let i = match self.arrangement {
686            Arrangement::Tabs => self.active.min(self.members.len() - 1),
687            Arrangement::Stack => 0,
688        };
689        self.members[i].shown()
690    }
691
692    /// Shows a panel: the tab it is in a group of tabs, or its tab in a
693    /// nested tab group; whether it is one of its panels.
694    pub fn show(&mut self, panel: &PanelId) -> bool {
695        let Some(i) = self.members.iter().position(|m| m.holds(panel)) else {
696            return false;
697        };
698        if self.arrangement == Arrangement::Tabs {
699            self.active = i;
700        }
701        self.members[i].show(panel)
702    }
703
704    /// A palette alone, not grouped with others.
705    pub fn is_lone(&self) -> bool {
706        self.members.len() == 1 && !self.members[0].is_tabs()
707    }
708
709    /// Keeps its fields consistent: nested tab groups only in a stack, a
710    /// stack of one tab group made a group of tabs, the active tab
711    /// inside, and a palette alone a plain stack.
712    fn tidy(&mut self) {
713        if self.arrangement == Arrangement::Tabs && self.members.iter().any(Member::is_tabs) {
714            // Tabs hold palettes: a nested tab group's tabs join them.
715            let shown = self.shown().clone();
716            let members = std::mem::take(&mut self.members);
717            self.members = members.into_iter().flat_map(Member::split).collect();
718            self.active = self
719                .members
720                .iter()
721                .position(|m| m.panel == shown)
722                .unwrap_or(0);
723        }
724        if self.members.len() == 1 && self.members[0].is_tabs() {
725            // A stack of one tab group: the group's tabs.
726            let m = self.members.remove(0);
727            self.active = m.shown.min(m.tabs.len());
728            self.members = m.split();
729            self.arrangement = Arrangement::Tabs;
730        }
731        for m in &mut self.members {
732            m.shown = m.shown.min(m.tabs.len());
733        }
734        if self.members.len() <= 1 {
735            self.arrangement = Arrangement::Stack;
736            self.active = 0;
737        } else if self.arrangement == Arrangement::Stack {
738            self.active = 0;
739        } else {
740            self.active = self.active.min(self.members.len() - 1);
741        }
742    }
743
744    /// Takes a panel out, if it is in: out of its nested tab group, or a
745    /// member out. The shown tab out, its neighbour on the right is
746    /// shown, or the one on the left when it was the last.
747    fn take(&mut self, panel: &PanelId) -> Option<Member> {
748        let i = self.members.iter().position(|m| m.holds(panel))?;
749        let out = if self.members[i].take_tab(panel) {
750            Member {
751                rolled: self.members[i].rolled,
752                ..Member::palette(panel.clone())
753            }
754        } else {
755            let m = self.members.remove(i);
756            self.active = shown_after_removal(self.active, i, self.members.len());
757            m
758        };
759        self.tidy();
760        Some(out)
761    }
762
763    /// Takes out the member holding a panel, whole (a nested tab group
764    /// with its tabs).
765    fn take_member(&mut self, panel: &PanelId) -> Option<Member> {
766        let i = self.members.iter().position(|m| m.holds(panel))?;
767        let m = self.members.remove(i);
768        self.active = shown_after_removal(self.active, i, self.members.len());
769        self.tidy();
770        Some(m)
771    }
772
773    /// Keeps only the panels `keep` says, in their members; members left
774    /// empty go.
775    fn retain_panels(&mut self, keep: impl Fn(&PanelId) -> bool) {
776        let was = self.shown().clone();
777        let members = std::mem::take(&mut self.members);
778        for m in members {
779            let shown = m.shown().clone();
780            let list: Vec<PanelId> = m.panels().filter(|p| keep(p)).cloned().collect();
781            if list.is_empty() {
782                continue;
783            }
784            let at = list.iter().position(|p| *p == shown).unwrap_or(0);
785            self.members.push(Member::from_list(list, at, m.rolled));
786        }
787        if self.members.is_empty() {
788            return;
789        }
790        self.active = self.members.iter().position(|m| m.holds(&was)).unwrap_or(0);
791        self.tidy();
792    }
793}
794
795/// Which workbench edge a floating panel sticks to, on one axis.
796#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
797#[serde(rename_all = "snake_case")]
798pub enum AnchorEdge {
799    /// None: it keeps its place from the workbench's top-left, clamped
800    /// inside.
801    #[default]
802    None,
803    /// The left edge (x) or the top edge (y).
804    Start,
805    /// The right edge (x) or the bottom edge (y).
806    End,
807}
808
809impl AnchorEdge {
810    fn is_none(&self) -> bool {
811        *self == AnchorEdge::None
812    }
813}
814
815/// The workbench edges a floating panel sticks to, horizontally and
816/// vertically, and its distance to each: when the workbench changes size,
817/// an anchored edge keeps that distance.
818///
819/// ```
820/// use egui_pop_model::layout::{Anchor, AnchorEdge};
821///
822/// let right = Anchor { x: AnchorEdge::End, ..Anchor::default() };
823/// assert!(!right.is_none());
824/// assert!(Anchor::default().is_none());
825/// ```
826#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
827pub struct Anchor {
828    #[serde(default, skip_serializing_if = "AnchorEdge::is_none")]
829    pub x: AnchorEdge,
830    #[serde(default, skip_serializing_if = "AnchorEdge::is_none")]
831    pub y: AnchorEdge,
832    /// The distance to the anchored edge on each axis, in points (zero on
833    /// an axis that is not anchored).
834    #[serde(default)]
835    pub offset: [f32; 2],
836}
837
838impl Anchor {
839    /// Anchored on neither axis.
840    pub fn is_none(&self) -> bool {
841        self.x.is_none() && self.y.is_none()
842    }
843}
844
845fn is_false(b: &bool) -> bool {
846    !*b
847}
848
849/// Where a side area lies.
850#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
851pub enum Placement {
852    /// Beside the centre, taking its room (the default).
853    #[default]
854    Beside,
855    /// Over the centre, with a shadow; its folded strip keeps the room in
856    /// the layout, so the centre keeps its width.
857    Over,
858}
859
860impl Placement {
861    /// Its name in documents and arguments.
862    pub fn as_str(self) -> &'static str {
863        match self {
864            Placement::Beside => "beside",
865            Placement::Over => "over",
866        }
867    }
868
869    /// A placement from its name.
870    pub fn parse(name: &str) -> Option<Placement> {
871        [Placement::Beside, Placement::Over]
872            .into_iter()
873            .find(|p| p.as_str() == name)
874    }
875}
876
877#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
878pub struct Layout {
879    pub areas: Vec<(Area, Node)>,
880    #[serde(default)]
881    pub auxiliary: Vec<Auxiliary>,
882    /// Panels the user closed: not put back as new ones are.
883    #[serde(default, skip_serializing_if = "Vec::is_empty")]
884    pub hidden: Vec<PanelId>,
885    /// Areas folded to their strip: their panels stay, unshown.
886    #[serde(default, skip_serializing_if = "Vec::is_empty")]
887    pub folded: Vec<Area>,
888    /// Side areas lying over the centre ([`Placement::Over`]): their
889    /// folded strip keeps their room, the centre its width.
890    #[serde(default, skip_serializing_if = "Vec::is_empty")]
891    pub over: Vec<Area>,
892    /// The width each panel was given as a flyout over the centre, out
893    /// of its folded side area's strip, in points.
894    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
895    pub flyouts: BTreeMap<PanelId, f32>,
896    /// Panels floating over the interface (palettes), each group as one
897    /// unit (a palette alone is a group of one).
898    #[serde(default, skip_serializing_if = "Vec::is_empty")]
899    pub floating: Vec<FloatingGroup>,
900    /// Groups docked whole in an area (their members there as tabs),
901    /// kept so that floating one of them out again gives the group back.
902    #[serde(default, skip_serializing_if = "Vec::is_empty")]
903    pub docked_groups: Vec<FloatingGroup>,
904    /// The place each closed panel had when it closed ([`Layout::hide`]),
905    /// where opening it puts it back ([`Layout::last_place`]); kept only
906    /// for panels in `hidden`.
907    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
908    pub closed: BTreeMap<PanelId, DormantPlace>,
909    /// The instances of panels declared with several
910    /// (`PanelSpec::instances`): each `<kind>#<n>` open, its title when
911    /// renamed and the application's payload for it; the panel declared
912    /// (instance 1) only when it holds a payload. A layout saved without
913    /// them reads as one with none.
914    #[serde(default, skip_serializing_if = "Vec::is_empty")]
915    pub instances: Vec<PanelInstance>,
916    /// The areas of the application windows other than the main one, each
917    /// window's own workbench ([`WindowAreas`]); `areas` are the main
918    /// window's. A layout saved before them reads as one with none.
919    #[serde(default, skip_serializing_if = "Vec::is_empty")]
920    pub windows: Vec<WindowAreas>,
921}
922
923/// An application window's own areas: its centre, start and end sides and
924/// bottom, each with its tabs and splits, as the main window has them
925/// ([`Layout::windows`]).
926///
927/// ```
928/// use egui_pop_model::ids::PanelId;
929/// use egui_pop_model::layout::Layout;
930/// use egui_pop_model::panels::Area;
931///
932/// let notices = PanelId::from_static("app.notices");
933/// let mut layout = Layout::default();
934/// layout.place_in_window(&notices, "library", Area::Bottom);
935/// assert_eq!(layout.window_place(&notices), Some(("library", Area::Bottom)));
936/// assert!(layout.shows(&notices));
937/// assert_eq!(layout.area_of(&notices), None);
938/// ```
939#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
940pub struct WindowAreas {
941    /// The window's id, as the application opened it.
942    pub window: String,
943    pub areas: Vec<(Area, Node)>,
944    /// Its areas folded to their strip (a side area) or out of sight (the
945    /// bottom), as the main window's [`Layout::folded`]. A layout saved
946    /// before them reads as one with none.
947    #[serde(default, skip_serializing_if = "Vec::is_empty")]
948    pub folded: Vec<Area>,
949}
950
951impl WindowAreas {
952    /// Every panel in the window's areas.
953    pub fn panels(&self) -> impl Iterator<Item = &PanelId> {
954        self.areas.iter().flat_map(|(_, n)| n.panels())
955    }
956}
957
958/// An instance of a panel declared with several ([`Layout::instances`]).
959///
960/// ```
961/// use egui_pop_model::ids::PanelId;
962/// use egui_pop_model::layout::{Layout, PanelInstance};
963///
964/// let kind = PanelId::new("app.gallery").unwrap();
965/// let mut layout = Layout::default();
966/// let second = layout.next_instance(&kind);
967/// assert_eq!(second.as_str(), "app.gallery#2");
968/// layout.instances.push(PanelInstance::new(second.clone()).payload(serde_json::json!({ "filter": "red" })));
969/// assert_eq!(layout.next_instance(&kind).as_str(), "app.gallery#3");
970/// assert_eq!(layout.instance(&second).unwrap().payload["filter"], "red");
971/// ```
972#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
973#[non_exhaustive]
974pub struct PanelInstance {
975    /// Its id, `<kind>#<n>` (the kind alone for instance 1).
976    pub id: PanelId,
977    /// Its title when renamed; its kind's title and number otherwise.
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    pub title: Option<String>,
980    /// What the application keeps for it (opaque here): handed back as
981    /// it was saved.
982    #[serde(default, skip_serializing_if = "Json::is_null")]
983    pub payload: Json,
984}
985
986impl PanelInstance {
987    pub fn new(id: PanelId) -> Self {
988        Self {
989            id,
990            title: None,
991            payload: Json::Null,
992        }
993    }
994
995    /// With a payload.
996    pub fn payload(mut self, payload: Json) -> Self {
997        self.payload = payload;
998        self
999    }
1000
1001    /// With a title of its own.
1002    pub fn title(mut self, title: impl Into<String>) -> Self {
1003        self.title = Some(title.into());
1004        self
1005    }
1006}
1007
1008/// A layout as saved: the layout, and the places of panels no longer
1009/// declared (their plugin is off, ADR 0028), kept so that a panel
1010/// declared again goes back where it was ([`Layout::repair_dormant`]).
1011/// Its document is the layout's (`schema`), the places under `dormant`:
1012/// a layout saved without them reads as one with none.
1013#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1014pub struct SavedLayout {
1015    #[serde(flatten)]
1016    pub layout: Layout,
1017    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1018    pub dormant: Vec<Dormant>,
1019}
1020
1021/// The place a panel no longer declared had ([`SavedLayout::dormant`]).
1022#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1023pub struct Dormant {
1024    pub panel: PanelId,
1025    pub place: DormantPlace,
1026}
1027
1028/// Where a dormant panel was.
1029#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1030#[serde(tag = "kind", rename_all = "lowercase")]
1031pub enum DormantPlace {
1032    /// Docked in an area: at `index` in the tabs it shared with `beside`.
1033    Docked {
1034        area: Area,
1035        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1036        beside: Vec<PanelId>,
1037        #[serde(default)]
1038        index: usize,
1039    },
1040    /// Detached in a window on a screen, at `rect`.
1041    Window { screen: String, rect: [f32; 4] },
1042    /// Floating over the interface, its group's corner at `pos`.
1043    Floating { pos: [f32; 2] },
1044    /// Closed by the user.
1045    Hidden,
1046    /// Docked in an area of an application window other than the main
1047    /// one ([`Layout::windows`]): at `index` in the tabs it shared with
1048    /// `beside`.
1049    #[serde(rename = "in_window")]
1050    InWindow {
1051        window: String,
1052        area: Area,
1053        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1054        beside: Vec<PanelId>,
1055        #[serde(default)]
1056        index: usize,
1057    },
1058}
1059
1060impl DormantPlace {
1061    /// The application window the place is in: `None` for the main
1062    /// window's (its areas, its detached panels and its floating ones).
1063    pub fn window(&self) -> Option<&str> {
1064        match self {
1065            DormantPlace::InWindow { window, .. } => Some(window),
1066            _ => None,
1067        }
1068    }
1069}
1070
1071/// Keeps a gone panel's place, once, with its note.
1072fn keep_place(
1073    dormant: &mut Vec<Dormant>,
1074    notes: &mut Vec<String>,
1075    panel: &PanelId,
1076    place: DormantPlace,
1077) {
1078    if dormant.iter().any(|d| d.panel == *panel) {
1079        return;
1080    }
1081    notes.push(format!(
1082        "panel `{panel}` is not declared: its place is kept"
1083    ));
1084    dormant.push(Dormant {
1085        panel: panel.clone(),
1086        place,
1087    });
1088}
1089
1090/// The `layout` document. Version 2 named the areas by start and end
1091/// (`start_side`) instead of primary and secondary; version 3 gave each
1092/// application window areas of its own (`windows`), none in an older one.
1093pub fn schema() -> Schema {
1094    Schema::new("layout", 3)
1095        .migration(0, same)
1096        .migration(1, rename_areas)
1097        .migration(2, no_window_areas)
1098}
1099
1100/// A layout from before each window had its areas: every panel in the
1101/// main window's, as it was.
1102fn no_window_areas(mut json: Json) -> Result<Json, String> {
1103    if let Some(doc) = json.as_object_mut() {
1104        doc.entry("windows")
1105            .or_insert_with(|| Json::Array(Vec::new()));
1106    }
1107    Ok(json)
1108}
1109
1110fn rename_areas(mut json: Json) -> Result<Json, String> {
1111    let rename = |name: &str| {
1112        match name {
1113            "editors" => "center",
1114            "primary_side_bar" => "start_side",
1115            "secondary_side_bar" => "end_side",
1116            "bottom_panel" => "bottom",
1117            other => other,
1118        }
1119        .to_string()
1120    };
1121    if let Some(areas) = json.get_mut("areas").and_then(Json::as_array_mut) {
1122        for pair in areas {
1123            if let Some(name) = pair.get(0).and_then(Json::as_str).map(rename) {
1124                pair[0] = Json::String(name);
1125            }
1126        }
1127    }
1128    Ok(json)
1129}
1130
1131impl Layout {
1132    /// Every declared panel in its default area, as tabs.
1133    pub fn default_for(panels: &Panels) -> Layout {
1134        let mut areas: Vec<(Area, Node)> = Vec::new();
1135        let mut hidden = Vec::new();
1136        let mut floating = Vec::new();
1137        for p in panels.all() {
1138            if !p.open {
1139                hidden.push(p.id.clone());
1140                continue;
1141            }
1142            if p.palette {
1143                floating.push(FloatingGroup::lone(
1144                    p.id.clone(),
1145                    FloatingGroup::cascade(floating.len()),
1146                ));
1147                continue;
1148            }
1149            match areas.iter_mut().find(|(a, _)| *a == p.area) {
1150                Some((_, Node::Tabs { panels, .. })) => panels.push(p.id.clone()),
1151                _ => areas.push((p.area, Node::tab(p.id.clone()))),
1152            }
1153        }
1154        areas.sort_by_key(|(a, _)| *a);
1155        Layout {
1156            areas,
1157            auxiliary: Vec::new(),
1158            hidden,
1159            folded: Vec::new(),
1160            over: Vec::new(),
1161            flyouts: BTreeMap::new(),
1162            floating,
1163            docked_groups: Vec::new(),
1164            closed: BTreeMap::new(),
1165            instances: Vec::new(),
1166            windows: Vec::new(),
1167        }
1168    }
1169
1170    /// Where a side area lies (the centre and the bottom area always
1171    /// lie beside).
1172    pub fn placement(&self, area: Area) -> Placement {
1173        if self.over.contains(&area) {
1174            Placement::Over
1175        } else {
1176            Placement::Beside
1177        }
1178    }
1179
1180    /// Lays a side area over the centre or beside it.
1181    pub fn set_placement(&mut self, area: Area, placement: Placement) {
1182        self.over.retain(|a| *a != area);
1183        if placement == Placement::Over {
1184            self.over.push(area);
1185        }
1186    }
1187
1188    /// Every panel placed, docked, detached or floating.
1189    pub fn placed(&self) -> Vec<&PanelId> {
1190        let mut v: Vec<&PanelId> = self.areas.iter().flat_map(|(_, n)| n.panels()).collect();
1191        v.extend(self.auxiliary.iter().flat_map(|a| a.panels()));
1192        v.extend(self.floating.iter().flat_map(|g| g.panels()));
1193        v.extend(self.windows.iter().flat_map(WindowAreas::panels));
1194        v
1195    }
1196
1197    /// An application window's areas, if it has any.
1198    pub fn window_areas(&self, window: &str) -> Option<&WindowAreas> {
1199        self.windows.iter().find(|w| w.window == window)
1200    }
1201
1202    /// Whether an application window's area is folded
1203    /// ([`WindowAreas::folded`]).
1204    pub fn window_folded(&self, window: &str, area: Area) -> bool {
1205        self.window_areas(window)
1206            .is_some_and(|w| w.folded.contains(&area))
1207    }
1208
1209    /// Folds an application window's area (`true`) or unfolds it; a
1210    /// window without areas has nothing to fold. `false` when nothing
1211    /// changed.
1212    ///
1213    /// ```
1214    /// use egui_pop_model::ids::PanelId;
1215    /// use egui_pop_model::layout::Layout;
1216    /// use egui_pop_model::panels::Area;
1217    ///
1218    /// let outline = PanelId::from_static("app.outline");
1219    /// let mut layout = Layout::default();
1220    /// layout.place_in_window(&outline, "library", Area::StartSide);
1221    /// assert!(layout.fold_in_window("library", Area::StartSide, true));
1222    /// assert!(layout.window_folded("library", Area::StartSide));
1223    /// assert!(layout.shows(&outline));
1224    /// ```
1225    pub fn fold_in_window(&mut self, window: &str, area: Area, folded: bool) -> bool {
1226        let Some(w) = self.windows.iter_mut().find(|w| w.window == window) else {
1227            return false;
1228        };
1229        let was = w.folded.contains(&area);
1230        w.folded.retain(|a| *a != area);
1231        if folded {
1232            w.folded.push(area);
1233            w.folded.sort();
1234        }
1235        was != folded
1236    }
1237
1238    /// The application window (other than the main one) a panel is docked
1239    /// in, and its area there.
1240    pub fn window_place(&self, panel: &PanelId) -> Option<(&str, Area)> {
1241        self.windows.iter().find_map(|w| {
1242            w.areas
1243                .iter()
1244                .find(|(_, n)| n.panels().contains(&panel))
1245                .map(|(a, _)| (w.window.as_str(), *a))
1246        })
1247    }
1248
1249    /// Every panel an application window holds: for [`MAIN_WINDOW`] those
1250    /// in its areas, its detached windows and its floating groups; for
1251    /// another, those docked in its own areas ([`Layout::windows`]).
1252    ///
1253    /// ```
1254    /// use egui_pop_model::ids::PanelId;
1255    /// use egui_pop_model::layout::{Layout, MAIN_WINDOW};
1256    /// use egui_pop_model::panels::Area;
1257    ///
1258    /// let [tree, log] = [PanelId::from_static("app.tree"), PanelId::from_static("app.log")];
1259    /// let mut layout = Layout::default();
1260    /// layout.place(&tree, Area::StartSide);
1261    /// layout.place_in_window(&log, "activity", Area::Bottom);
1262    /// assert_eq!(layout.panels_in_window(MAIN_WINDOW), [&tree]);
1263    /// assert_eq!(layout.panels_in_window("activity"), [&log]);
1264    /// ```
1265    pub fn panels_in_window(&self, window: &str) -> Vec<&PanelId> {
1266        if window == MAIN_WINDOW {
1267            let mut v: Vec<&PanelId> = self.areas.iter().flat_map(|(_, n)| n.panels()).collect();
1268            v.extend(self.auxiliary.iter().flat_map(|a| a.panels()));
1269            v.extend(self.floating.iter().flat_map(|g| g.panels()));
1270            v
1271        } else {
1272            self.window_areas(window)
1273                .map(|w| w.panels().collect())
1274                .unwrap_or_default()
1275        }
1276    }
1277
1278    /// The application window a closed panel belongs to: the one its
1279    /// last place was in, the main window without one.
1280    fn closed_in(&self, panel: &PanelId) -> &str {
1281        self.closed
1282            .get(panel)
1283            .and_then(DormantPlace::window)
1284            .unwrap_or(MAIN_WINDOW)
1285    }
1286
1287    /// This layout with one application window's part taken from `from`,
1288    /// every other window left as it is here: what a change made to one
1289    /// window (a place switched in it) puts in.
1290    ///
1291    /// The part of [`MAIN_WINDOW`] is its areas, its detached windows,
1292    /// its floating groups and what goes with them (folded and overlaid
1293    /// areas, flyouts, docked groups); another window's part is its own
1294    /// areas. A panel this layout shows in another window stays there:
1295    /// `from` cannot take it, show it or close it. Closed panels follow
1296    /// the window they were closed in, and instances the window that
1297    /// holds them.
1298    ///
1299    /// ```
1300    /// use egui_pop_model::ids::PanelId;
1301    /// use egui_pop_model::layout::{Layout, MAIN_WINDOW};
1302    /// use egui_pop_model::panels::Area;
1303    ///
1304    /// let [tree, log] = [PanelId::from_static("app.tree"), PanelId::from_static("app.log")];
1305    /// // Shown: the log docked in a second window.
1306    /// let mut shown = Layout::default();
1307    /// shown.place(&tree, Area::StartSide);
1308    /// shown.place_in_window(&log, "activity", Area::Bottom);
1309    /// // A place's layout for the main window, which had the log there.
1310    /// let mut place = Layout::default();
1311    /// place.place(&tree, Area::EndSide);
1312    /// place.place(&log, Area::Bottom);
1313    /// let merged = shown.with_window_from(&place, MAIN_WINDOW);
1314    /// assert_eq!(merged.area_of(&tree), Some(Area::EndSide));
1315    /// assert_eq!(merged.window_place(&log), Some(("activity", Area::Bottom)));
1316    /// assert_eq!(merged.area_of(&log), None);
1317    /// ```
1318    pub fn with_window_from(&self, from: &Layout, window: &str) -> Layout {
1319        let elsewhere: BTreeSet<PanelId> = {
1320            let here: BTreeSet<&PanelId> = self.panels_in_window(window).into_iter().collect();
1321            self.placed()
1322                .into_iter()
1323                .filter(|p| !here.contains(p))
1324                .cloned()
1325                .collect()
1326        };
1327        let mut out = self.clone();
1328        if window == MAIN_WINDOW {
1329            // The main window's part alone, cut of what other windows show.
1330            let mut part = Layout {
1331                areas: from.areas.clone(),
1332                auxiliary: from.auxiliary.clone(),
1333                folded: from.folded.clone(),
1334                over: from.over.clone(),
1335                flyouts: from.flyouts.clone(),
1336                floating: from.floating.clone(),
1337                docked_groups: from.docked_groups.clone(),
1338                ..Layout::default()
1339            };
1340            for p in &elsewhere {
1341                part.remove(p);
1342                part.flyouts.remove(p);
1343                for g in &mut part.docked_groups {
1344                    g.take(p);
1345                }
1346            }
1347            part.docked_groups.retain(|g| g.panels().count() > 1);
1348            out.areas = part.areas;
1349            out.auxiliary = part.auxiliary;
1350            out.folded = part.folded;
1351            out.over = part.over;
1352            out.flyouts = part.flyouts;
1353            out.floating = part.floating;
1354            out.docked_groups = part.docked_groups;
1355        } else {
1356            let taken = from.window_areas(window).cloned().and_then(|w| {
1357                let mut part = Layout {
1358                    windows: vec![w],
1359                    ..Layout::default()
1360                };
1361                for p in &elsewhere {
1362                    part.remove(p);
1363                }
1364                part.windows.pop()
1365            });
1366            let at = out.windows.iter().position(|w| w.window == window);
1367            match (at, taken) {
1368                (Some(at), Some(w)) => out.windows[at] = w,
1369                (Some(at), None) => {
1370                    out.windows.remove(at);
1371                }
1372                (None, Some(w)) => out.windows.push(w),
1373                (None, None) => {}
1374            }
1375        }
1376        // Closed panels: those of the other windows as they are here, the
1377        // window's own as `from` has them; never one shown.
1378        let shown: BTreeSet<PanelId> = out.placed().into_iter().cloned().collect();
1379        let mut hidden: Vec<PanelId> = Vec::new();
1380        let mut closed: BTreeMap<PanelId, DormantPlace> = BTreeMap::new();
1381        let kept = self.hidden.iter().filter(|p| self.closed_in(p) != window);
1382        let taken = from.hidden.iter().filter(|p| from.closed_in(p) == window);
1383        for (p, layout) in kept.map(|p| (p, self)).chain(taken.map(|p| (p, from))) {
1384            if shown.contains(p) || hidden.contains(p) {
1385                continue;
1386            }
1387            hidden.push(p.clone());
1388            if let Some(place) = layout.closed.get(p) {
1389                closed.insert(p.clone(), place.clone());
1390            }
1391        }
1392        out.hidden = hidden;
1393        out.closed = closed;
1394        // Instances: those another window holds (or closed there) as they
1395        // are here, the others as `from` has them.
1396        let mut instances: Vec<PanelInstance> = self
1397            .instances
1398            .iter()
1399            .filter(|i| {
1400                elsewhere.contains(&i.id)
1401                    || (self.hidden.contains(&i.id) && self.closed_in(&i.id) != window)
1402            })
1403            .cloned()
1404            .collect();
1405        for i in &from.instances {
1406            if !instances.iter().any(|k| k.id == i.id) {
1407                instances.push(i.clone());
1408            }
1409        }
1410        out.instances = instances;
1411        out
1412    }
1413
1414    /// Docks a panel in an area of an application window other than the
1415    /// main one (taken out of where it was, opened if closed), as the
1416    /// shown tab of the area's first tabs.
1417    pub fn place_in_window(&mut self, panel: &PanelId, window: &str, area: Area) {
1418        self.remove(panel);
1419        self.hidden.retain(|h| h != panel);
1420        let at = match self.windows.iter().position(|w| w.window == window) {
1421            Some(at) => at,
1422            None => {
1423                self.windows.push(WindowAreas {
1424                    window: window.to_string(),
1425                    areas: Vec::new(),
1426                    folded: Vec::new(),
1427                });
1428                self.windows.len() - 1
1429            }
1430        };
1431        let areas = &mut self.windows[at].areas;
1432        match areas.iter_mut().find(|(a, _)| *a == area) {
1433            Some((_, node)) => {
1434                node.push(panel.clone());
1435                node.activate(panel);
1436            }
1437            None => {
1438                areas.push((area, Node::tab(panel.clone())));
1439                areas.sort_by_key(|(a, _)| *a);
1440            }
1441        }
1442    }
1443
1444    /// Sets an application window's areas as drawn (its tabs reordered,
1445    /// split, moved between its areas); empty areas are dropped, and the
1446    /// window with them when it has none left.
1447    pub fn set_window_areas(&mut self, window: &str, areas: Vec<(Area, Node)>) {
1448        let folded = self
1449            .window_areas(window)
1450            .map(|w| w.folded.clone())
1451            .unwrap_or_default();
1452        self.windows.retain(|w| w.window != window);
1453        if !areas.is_empty() {
1454            self.windows.push(WindowAreas {
1455                window: window.to_string(),
1456                areas,
1457                folded,
1458            });
1459            self.windows.sort_by(|a, b| a.window.cmp(&b.window));
1460        }
1461    }
1462
1463    /// The window a detached panel is in, if it is detached (alone or
1464    /// as one of its tabs).
1465    pub fn window_of(&self, panel: &PanelId) -> Option<&Auxiliary> {
1466        self.auxiliary.iter().find(|a| a.holds(panel))
1467    }
1468
1469    /// Moves a panel into the window holding `window` (a panel of it), as
1470    /// its last tab, shown; taken out of where it was, opened if closed.
1471    /// A panel in that window already is only shown.
1472    pub fn join_window(&mut self, panel: &PanelId, window: &PanelId) -> Result<(), String> {
1473        if !self.auxiliary.iter().any(|a| a.holds(window)) {
1474            return Err(format!("`{window}` is in no window"));
1475        }
1476        if self.window_of(panel).is_some_and(|a| a.holds(window)) {
1477            if let Some(a) = self.auxiliary.iter_mut().find(|a| a.holds(panel)) {
1478                a.show(panel);
1479            }
1480            return Ok(());
1481        }
1482        self.remove(panel);
1483        self.hidden.retain(|h| h != panel);
1484        // `window` may have named the window `panel` left: still there,
1485        // as `remove` keeps a window's other panels.
1486        let a = (self.auxiliary.iter_mut())
1487            .find(|a| a.holds(window))
1488            .ok_or_else(|| format!("`{window}` is in no window"))?;
1489        a.join(panel.clone());
1490        Ok(())
1491    }
1492
1493    /// The tab group holding a docked or detached panel: its panels in
1494    /// order and the index of the shown one (an area's tabs holding it,
1495    /// or its window's tabs).
1496    ///
1497    /// ```
1498    /// use egui_pop_model::ids::PanelId;
1499    /// use egui_pop_model::layout::{Layout, Node};
1500    /// use egui_pop_model::panels::Area;
1501    ///
1502    /// let [a, b] = [PanelId::from_static("app.a"), PanelId::from_static("app.b")];
1503    /// let mut layout = Layout::default();
1504    /// layout.areas.push((Area::Bottom, Node::Tabs { panels: vec![a.clone(), b.clone()], active: 1 }));
1505    /// assert_eq!(layout.group_of(&a), Some((vec![a, b], 1)));
1506    /// ```
1507    pub fn group_of(&self, panel: &PanelId) -> Option<(Vec<PanelId>, usize)> {
1508        if let Some(a) = self.window_of(panel) {
1509            let shown = a.shown.min(a.tabs.len());
1510            return Some((a.panels().cloned().collect(), shown));
1511        }
1512        fn find(n: &Node, panel: &PanelId) -> Option<(Vec<PanelId>, usize)> {
1513            match n {
1514                Node::Tabs { panels, active } => panels
1515                    .contains(panel)
1516                    .then(|| (panels.clone(), (*active).min(panels.len() - 1))),
1517                Node::Split { a, b, .. } => find(a, panel).or_else(|| find(b, panel)),
1518                Node::Grid { children, .. } => children.iter().find_map(|c| find(c, panel)),
1519            }
1520        }
1521        self.areas.iter().find_map(|(_, n)| find(n, panel))
1522    }
1523
1524    /// Moves the tab group holding `panel` ([`Layout::group_of`]) into
1525    /// the window holding `window`, after its tabs, in order; the group's
1526    /// shown panel is shown there. A group already in that window stays.
1527    pub fn join_window_group(&mut self, panel: &PanelId, window: &PanelId) -> Result<(), String> {
1528        let (panels, shown) = self
1529            .group_of(panel)
1530            .ok_or_else(|| format!("`{panel}` is in no tab group"))?;
1531        for p in &panels {
1532            self.join_window(p, window)?;
1533        }
1534        if let Some(a) = self.auxiliary.iter_mut().find(|a| a.holds(window)) {
1535            a.show(&panels[shown]);
1536        }
1537        Ok(())
1538    }
1539
1540    /// Moves the tab group holding `panel` ([`Layout::group_of`]) into a
1541    /// window of its own at `rect` on `screen`, in order, its shown panel
1542    /// shown. A group that is a window already stays.
1543    pub fn detach_group(
1544        &mut self,
1545        panel: &PanelId,
1546        screen: &str,
1547        rect: [f32; 4],
1548    ) -> Result<(), String> {
1549        if self.window_of(panel).is_some() {
1550            return Ok(());
1551        }
1552        let (panels, shown) = self
1553            .group_of(panel)
1554            .ok_or_else(|| format!("`{panel}` is in no tab group"))?;
1555        for p in &panels {
1556            self.remove(p);
1557            self.hidden.retain(|h| h != p);
1558        }
1559        let mut a = Auxiliary::window(panels[0].clone(), screen, rect);
1560        a.tabs = panels[1..].to_vec();
1561        a.shown = shown;
1562        self.auxiliary.push(a);
1563        Ok(())
1564    }
1565
1566    /// Floats the docked tab group holding `panel` ([`Layout::group_of`])
1567    /// over the interface at `pos`, whole: one floating group of tabs, in
1568    /// order, its shown tab shown. The panels floated.
1569    ///
1570    /// ```
1571    /// use egui_pop_model::ids::PanelId;
1572    /// use egui_pop_model::layout::{Arrangement, Layout, Node};
1573    /// use egui_pop_model::panels::Area;
1574    ///
1575    /// let [a, b] = [PanelId::from_static("app.a"), PanelId::from_static("app.b")];
1576    /// let mut layout = Layout::default();
1577    /// layout.areas.push((Area::Bottom, Node::Tabs { panels: vec![a.clone(), b.clone()], active: 1 }));
1578    /// assert_eq!(layout.float_tabs(&a, [8.0, 8.0]).unwrap(), [a.clone(), b.clone()]);
1579    /// let g = layout.floating_of(&a).unwrap();
1580    /// assert_eq!(g.arrangement, Arrangement::Tabs);
1581    /// assert_eq!(g.shown(), &b);
1582    /// assert_eq!(layout.area_of(&a), None);
1583    /// ```
1584    pub fn float_tabs(&mut self, panel: &PanelId, pos: [f32; 2]) -> Result<Vec<PanelId>, String> {
1585        if self.area_of(panel).is_none() {
1586            return Err(format!("`{panel}` is not docked"));
1587        }
1588        let (panels, shown) = self
1589            .group_of(panel)
1590            .ok_or_else(|| format!("`{panel}` is in no tab group"))?;
1591        for p in &panels {
1592            self.remove(p);
1593            self.hidden.retain(|h| h != p);
1594        }
1595        self.docked_groups
1596            .retain(|g| !panels.iter().any(|p| g.holds(p)));
1597        let mut group = FloatingGroup::lone(panels[0].clone(), pos);
1598        group.members = panels.iter().cloned().map(Member::palette).collect();
1599        if panels.len() > 1 {
1600            group.arrangement = Arrangement::Tabs;
1601        }
1602        group.active = shown;
1603        group.tidy();
1604        self.floating.push(group);
1605        Ok(panels)
1606    }
1607
1608    /// The group a floating panel floats in, if it floats.
1609    pub fn floating_of(&self, panel: &PanelId) -> Option<&FloatingGroup> {
1610        self.floating.iter().find(|g| g.holds(panel))
1611    }
1612
1613    /// The group a floating panel floats in, to change it.
1614    pub fn floating_mut(&mut self, panel: &PanelId) -> Option<&mut FloatingGroup> {
1615        self.floating.iter_mut().find(|g| g.holds(panel))
1616    }
1617
1618    /// Floats a panel over the interface at `pos` (taken out of where it
1619    /// was, opened if it was closed); a panel floating already moves
1620    /// there with its group, keeping its state. A panel docked with the
1621    /// group it was docked in whole ([`Layout::dock_group`]) floats with
1622    /// the members still docked beside it: the group comes back.
1623    pub fn float(&mut self, panel: &PanelId, pos: [f32; 2]) {
1624        if let Some(g) = self.floating_mut(panel) {
1625            g.pos = pos;
1626            return;
1627        }
1628        let area = self.area_of(panel);
1629        let mut group = FloatingGroup::lone(panel.clone(), pos);
1630        if let Some(i) = self.docked_groups.iter().position(|g| g.holds(panel)) {
1631            let mut was = self.docked_groups.remove(i);
1632            was.retain_panels(|p| p == panel || (area.is_some() && self.area_of(p) == area));
1633            if was.panels().count() > 1 {
1634                was.show(panel);
1635                was.pos = pos;
1636                was.anchor = Anchor::default();
1637                group = was;
1638                group.tidy();
1639            }
1640        }
1641        for p in group.panels() {
1642            self.remove(p);
1643            self.hidden.retain(|h| h != p);
1644        }
1645        self.floating.push(group);
1646    }
1647
1648    /// Moves floating panels into the group of another floating panel,
1649    /// `into`, and says where:
1650    ///
1651    /// - [`Join::Above`] or [`Join::Below`] it: the group is then a stack.
1652    ///   Beside a group of tabs, the tabs stay tabs, as one member of the
1653    ///   stack (a nested tab group).
1654    /// - [`Join::Tab`]: as tabs of it, the first of them shown. In a group
1655    ///   of tabs or with a palette alone, the group turns to tabs; on a
1656    ///   member of a stack, that member alone becomes a tab group.
1657    ///
1658    /// A nested tab group whose tabs all move keeps them, unless it joins
1659    /// as tabs; each moved member keeps whether it is rolled up; groups
1660    /// left empty go.
1661    pub fn group(&mut self, panels: &[PanelId], into: &PanelId, at: Join) -> Result<(), String> {
1662        if panels.is_empty() {
1663            return Err("no panel to group".into());
1664        }
1665        if panels.contains(into) {
1666            return Err(format!("`{into}` cannot join its own group"));
1667        }
1668        for p in panels {
1669            if self.floating_of(p).is_none() {
1670                return Err(format!("`{p}` does not float"));
1671            }
1672        }
1673        if self.floating_of(into).is_none() {
1674            return Err(format!("`{into}` does not float"));
1675        }
1676        let mut moving: Vec<Member> = Vec::new();
1677        // A whole group of tabs moving: one tab group, its tabs kept.
1678        while let Some(i) = self.floating.iter().position(|g| {
1679            g.arrangement == Arrangement::Tabs
1680                && !g.holds(into)
1681                && g.panels().all(|p| panels.contains(p))
1682        }) {
1683            let g = self.floating.remove(i);
1684            let rolled = g.members.get(g.active).is_some_and(|m| m.rolled);
1685            let list = g.panels().cloned().collect();
1686            moving.push(Member::from_list(list, g.active, rolled));
1687        }
1688        for p in panels {
1689            if moving.iter().any(|m| m.holds(p)) {
1690                continue;
1691            }
1692            let Some(g) = self.floating_mut(p) else {
1693                continue;
1694            };
1695            let whole = g
1696                .member(p)
1697                .is_some_and(|m| m.is_tabs() && m.panels().all(|q| panels.contains(q)));
1698            let m = if whole { g.take_member(p) } else { g.take(p) };
1699            moving.extend(m);
1700        }
1701        self.floating.retain(|g| !g.members.is_empty());
1702        let g = self.floating_mut(into).expect("checked above");
1703        let mut i = g.members.iter().position(|m| m.holds(into)).unwrap_or(0);
1704        match at {
1705            Join::Above | Join::Below => {
1706                if g.arrangement == Arrangement::Tabs {
1707                    // Beside tabs: they stay tabs, one member of the stack.
1708                    let rolled = g.members.get(g.active).is_some_and(|m| m.rolled);
1709                    let list = g.members.iter().map(|m| m.panel.clone()).collect();
1710                    g.members = vec![Member::from_list(list, g.active, rolled)];
1711                    g.arrangement = Arrangement::Stack;
1712                    g.active = 0;
1713                    i = 0;
1714                }
1715                let first = if at == Join::Above { i } else { i + 1 };
1716                for (k, m) in moving.into_iter().enumerate() {
1717                    g.members.insert(first + k, m);
1718                }
1719            }
1720            Join::Tab if g.arrangement == Arrangement::Stack && g.members.len() > 1 => {
1721                // On a member of a stack: that member holds the tabs.
1722                let m = &mut g.members[i];
1723                let mut list = m.list();
1724                let at = list.iter().position(|p| p == into).unwrap_or(0) + 1;
1725                let new: Vec<PanelId> = moving.iter().flat_map(|m| m.list()).collect();
1726                list.splice(at..at, new);
1727                *m = Member::from_list(list, at, m.rolled);
1728            }
1729            Join::Tab => {
1730                let first = i + 1;
1731                let flat: Vec<Member> = moving.into_iter().flat_map(Member::split).collect();
1732                for (k, m) in flat.into_iter().enumerate() {
1733                    g.members.insert(first + k, m);
1734                }
1735                g.arrangement = Arrangement::Tabs;
1736                g.active = first;
1737            }
1738        }
1739        g.tidy();
1740        Ok(())
1741    }
1742
1743    /// Takes a floating panel out of its group, alone at `pos` (it keeps
1744    /// whether it is rolled up); out of a nested tab group, the group's
1745    /// other tabs stay.
1746    pub fn ungroup(&mut self, panel: &PanelId, pos: [f32; 2]) -> Result<(), String> {
1747        let g = self
1748            .floating_mut(panel)
1749            .ok_or_else(|| format!("`{panel}` does not float"))?;
1750        if g.is_lone() {
1751            return Err(format!("`{panel}` is not in a group"));
1752        }
1753        let m = g.take(panel).expect("held");
1754        let mut lone = FloatingGroup::lone(m.panel, pos);
1755        lone.members[0].rolled = m.rolled;
1756        self.floating.push(lone);
1757        Ok(())
1758    }
1759
1760    /// Takes the tab group a floating panel is a tab of, nested in a
1761    /// stack, out of the stack whole: a group of tabs at `pos`. A palette
1762    /// that is not in a nested tab group comes out alone, as
1763    /// [`Layout::ungroup`] takes it.
1764    pub fn ungroup_tabs(&mut self, panel: &PanelId, pos: [f32; 2]) -> Result<(), String> {
1765        let g = self
1766            .floating_mut(panel)
1767            .ok_or_else(|| format!("`{panel}` does not float"))?;
1768        if !g.member(panel).is_some_and(Member::is_tabs) || g.members.len() < 2 {
1769            return self.ungroup(panel, pos);
1770        }
1771        let m = g.take_member(panel).expect("held");
1772        let mut tabs = FloatingGroup::lone(m.panel.clone(), pos);
1773        tabs.members = vec![m];
1774        tabs.tidy();
1775        self.floating.push(tabs);
1776        Ok(())
1777    }
1778
1779    /// Docks every member of a floating panel's group in an area, as
1780    /// tabs, the group's shown member shown; the group is kept
1781    /// ([`Layout::docked_groups`]) so that floating one of them out
1782    /// again gives it back. The panels docked.
1783    pub fn dock_group(&mut self, panel: &PanelId, area: Area) -> Vec<PanelId> {
1784        let Some(i) = self.floating.iter().position(|g| g.holds(panel)) else {
1785            self.place(panel, area);
1786            return vec![panel.clone()];
1787        };
1788        let group = self.floating.remove(i);
1789        let panels: Vec<PanelId> = group.panels().cloned().collect();
1790        for p in &panels {
1791            self.place(p, area);
1792        }
1793        self.activate(group.shown());
1794        self.docked_groups
1795            .retain(|g| !panels.iter().any(|p| g.holds(p)));
1796        if !group.is_lone() {
1797            self.docked_groups.push(group);
1798        }
1799        panels
1800    }
1801
1802    /// The area a panel is docked in, if it is.
1803    pub fn area_of(&self, panel: &PanelId) -> Option<Area> {
1804        self.areas
1805            .iter()
1806            .find(|(_, n)| n.panels().contains(&panel))
1807            .map(|(a, _)| *a)
1808    }
1809
1810    /// Whether a panel is docked or detached, and not closed.
1811    pub fn shows(&self, panel: &PanelId) -> bool {
1812        !self.hidden.contains(panel) && self.placed().contains(&panel)
1813    }
1814
1815    /// Takes a panel out of its area, its window or its float (out of
1816    /// its group, the others staying together; it stays known: not
1817    /// closed). Whether it was placed.
1818    pub fn remove(&mut self, panel: &PanelId) -> bool {
1819        let before = self.placed().len();
1820        let areas = std::mem::take(&mut self.areas);
1821        self.areas = areas
1822            .into_iter()
1823            .filter_map(|(a, n)| n.retain(&|p: &PanelId| p != panel).map(|n| (a, n)))
1824            .collect();
1825        self.auxiliary.retain_mut(|x| x.take(panel));
1826        for g in &mut self.floating {
1827            g.take(panel);
1828        }
1829        self.floating.retain(|g| !g.members.is_empty());
1830        for w in &mut self.windows {
1831            let areas = std::mem::take(&mut w.areas);
1832            w.areas = areas
1833                .into_iter()
1834                .filter_map(|(a, n)| n.retain(&|p: &PanelId| p != panel).map(|n| (a, n)))
1835                .collect();
1836        }
1837        self.windows.retain(|w| !w.areas.is_empty());
1838        self.placed().len() != before
1839    }
1840
1841    /// Docks a panel in an area (taken out of where it was), as the
1842    /// shown tab of the area's first tabs.
1843    pub fn place(&mut self, panel: &PanelId, area: Area) {
1844        self.remove(panel);
1845        self.hidden.retain(|h| h != panel);
1846        match self.areas.iter_mut().find(|(a, _)| *a == area) {
1847            Some((_, node)) => node.push(panel.clone()),
1848            None => {
1849                self.areas.push((area, Node::tab(panel.clone())));
1850                self.areas.sort_by_key(|(a, _)| *a);
1851            }
1852        }
1853    }
1854
1855    /// Where a docked panel is: its area, the other panels of its tabs
1856    /// and its index among them (a [`DormantPlace::Docked`]); `None` when
1857    /// it is not docked.
1858    ///
1859    /// ```
1860    /// use egui_pop_model::ids::PanelId;
1861    /// use egui_pop_model::layout::{DormantPlace, Layout, Node};
1862    /// use egui_pop_model::panels::Area;
1863    ///
1864    /// let [a, b] = [PanelId::from_static("app.a"), PanelId::from_static("app.b")];
1865    /// let mut layout = Layout::default();
1866    /// layout.areas.push((Area::Bottom, Node::Tabs { panels: vec![a.clone(), b.clone()], active: 0 }));
1867    /// let place = layout.docked_place(&b).unwrap();
1868    /// assert_eq!(place, DormantPlace::Docked { area: Area::Bottom, beside: vec![a.clone()], index: 1 });
1869    /// layout.float(&b, [0.0, 0.0]);
1870    /// layout.dock_at(&b, &place);
1871    /// assert_eq!(layout.group_of(&b), Some((vec![a, b], 1)));
1872    /// ```
1873    pub fn docked_place(&self, panel: &PanelId) -> Option<DormantPlace> {
1874        self.areas.iter().find_map(|(area, n)| {
1875            n.tabs_of(panel)
1876                .map(|(beside, index)| DormantPlace::Docked {
1877                    area: *area,
1878                    beside,
1879                    index,
1880                })
1881        })
1882    }
1883
1884    /// Where a panel docked in an application window other than the main
1885    /// one is (a [`DormantPlace::InWindow`]); `None` when it is not there.
1886    pub fn in_window_place(&self, panel: &PanelId) -> Option<DormantPlace> {
1887        self.windows.iter().find_map(|w| {
1888            w.areas.iter().find_map(|(area, n)| {
1889                n.tabs_of(panel)
1890                    .map(|(beside, index)| DormantPlace::InWindow {
1891                        window: w.window.clone(),
1892                        area: *area,
1893                        beside,
1894                        index,
1895                    })
1896            })
1897        })
1898    }
1899
1900    /// Docks a panel at a place [`Layout::docked_place`] gave (taken out of
1901    /// where it is, opened if closed), shown: at its index in the tabs
1902    /// holding one of the panels it was beside, else in its area's first
1903    /// tabs. A place that is not [`DormantPlace::Docked`] changes nothing;
1904    /// whether it was docked.
1905    pub fn dock_at(&mut self, panel: &PanelId, place: &DormantPlace) -> bool {
1906        if let DormantPlace::InWindow {
1907            window,
1908            area,
1909            beside,
1910            index,
1911        } = place
1912        {
1913            self.remove(panel);
1914            self.hidden.retain(|h| h != panel);
1915            let beside_one = self
1916                .windows
1917                .iter_mut()
1918                .filter(|w| w.window == *window)
1919                .flat_map(|w| w.areas.iter_mut())
1920                .any(|(a, n)| *a == *area && n.insert_beside(panel, beside, *index));
1921            if !beside_one {
1922                self.place_in_window(panel, window, *area);
1923            }
1924            self.activate(panel);
1925            return true;
1926        }
1927        let DormantPlace::Docked {
1928            area,
1929            beside,
1930            index,
1931        } = place
1932        else {
1933            return false;
1934        };
1935        self.remove(panel);
1936        self.hidden.retain(|h| h != panel);
1937        let beside_one = self
1938            .areas
1939            .iter_mut()
1940            .any(|(a, n)| *a == *area && n.insert_beside(panel, beside, *index));
1941        if !beside_one {
1942            self.place(panel, *area);
1943        }
1944        self.activate(panel);
1945        true
1946    }
1947
1948    /// Docks a panel in the tabs holding `into`, after them and shown
1949    /// (taken out of where it is: floating, detached or docked, opened if
1950    /// closed). `into` is docked; a panel already there is only shown.
1951    ///
1952    /// ```
1953    /// use egui_pop_model::ids::PanelId;
1954    /// use egui_pop_model::layout::{Layout, Node};
1955    /// use egui_pop_model::panels::Area;
1956    ///
1957    /// let [a, b] = [PanelId::from_static("app.a"), PanelId::from_static("app.b")];
1958    /// let mut layout = Layout::default();
1959    /// layout.areas.push((Area::Bottom, Node::tab(a.clone())));
1960    /// layout.float(&b, [0.0, 0.0]);
1961    /// layout.join_tabs(&b, &a).unwrap();
1962    /// assert_eq!(layout.group_of(&b), Some((vec![a, b], 1)));
1963    /// ```
1964    pub fn join_tabs(&mut self, panel: &PanelId, into: &PanelId) -> Result<(), String> {
1965        if panel == into {
1966            return Err(format!("`{panel}` cannot join its own tabs"));
1967        }
1968        let Some(area) = self.area_of(into) else {
1969            return Err(format!("`{into}` is not docked"));
1970        };
1971        let same = self
1972            .areas
1973            .iter()
1974            .find_map(|(_, n)| n.tabs_of(into))
1975            .is_some_and(|(others, _)| others.contains(panel));
1976        if !same {
1977            self.remove(panel);
1978            self.hidden.retain(|h| h != panel);
1979            let into = [into.clone()];
1980            let inserted = self
1981                .areas
1982                .iter_mut()
1983                .any(|(a, n)| *a == area && n.insert_beside(panel, &into, usize::MAX));
1984            if !inserted {
1985                self.place(panel, area);
1986            }
1987        }
1988        self.activate(panel);
1989        Ok(())
1990    }
1991
1992    /// Where a panel is: docked (its area, the tabs beside it and its
1993    /// index, [`Layout::docked_place`]), detached (its window's screen and
1994    /// rectangle) or floating (its group's corner); `None` when it is not
1995    /// placed.
1996    ///
1997    /// ```
1998    /// use egui_pop_model::ids::PanelId;
1999    /// use egui_pop_model::layout::{DormantPlace, Layout};
2000    ///
2001    /// let tools = PanelId::from_static("app.tools");
2002    /// let mut layout = Layout::default();
2003    /// layout.float(&tools, [16.0, 24.0]);
2004    /// assert_eq!(layout.place_of(&tools), Some(DormantPlace::Floating { pos: [16.0, 24.0] }));
2005    /// ```
2006    pub fn place_of(&self, panel: &PanelId) -> Option<DormantPlace> {
2007        if let Some(place) = self.docked_place(panel) {
2008            return Some(place);
2009        }
2010        if let Some(place) = self.in_window_place(panel) {
2011            return Some(place);
2012        }
2013        if let Some(a) = self.window_of(panel) {
2014            return Some(DormantPlace::Window {
2015                screen: a.screen.clone(),
2016                rect: a.rect,
2017            });
2018        }
2019        self.floating_of(panel)
2020            .map(|g| DormantPlace::Floating { pos: g.pos })
2021    }
2022
2023    /// The place a closed panel had when it closed ([`Layout::hide`]):
2024    /// `None` when it is open, or closed with no place known.
2025    ///
2026    /// ```
2027    /// use egui_pop_model::ids::PanelId;
2028    /// use egui_pop_model::layout::{DormantPlace, Layout, Node};
2029    /// use egui_pop_model::panels::Area;
2030    ///
2031    /// let [a, b] = [PanelId::from_static("app.a"), PanelId::from_static("app.b")];
2032    /// let mut layout = Layout::default();
2033    /// layout.areas.push((Area::Bottom, Node::Tabs { panels: vec![a.clone(), b.clone()], active: 1 }));
2034    /// layout.hide(&b);
2035    /// let place = layout.last_place(&b).cloned().unwrap();
2036    /// assert_eq!(place, DormantPlace::Docked { area: Area::Bottom, beside: vec![a.clone()], index: 1 });
2037    /// layout.dock_at(&b, &place);
2038    /// assert_eq!(layout.group_of(&b), Some((vec![a, b], 1)));
2039    /// ```
2040    pub fn last_place(&self, panel: &PanelId) -> Option<&DormantPlace> {
2041        self.hidden
2042            .contains(panel)
2043            .then(|| self.closed.get(panel))
2044            .flatten()
2045    }
2046
2047    /// An instance's record ([`Layout::instances`]).
2048    pub fn instance(&self, id: &PanelId) -> Option<&PanelInstance> {
2049        self.instances.iter().find(|i| i.id == *id)
2050    }
2051
2052    /// An instance's record, made (without payload) when it has none.
2053    pub fn instance_mut(&mut self, id: &PanelId) -> &mut PanelInstance {
2054        let at = match self.instances.iter().position(|i| i.id == *id) {
2055            Some(at) => at,
2056            None => {
2057                self.instances.push(PanelInstance::new(id.clone()));
2058                self.instances.len() - 1
2059            }
2060        };
2061        &mut self.instances[at]
2062    }
2063
2064    /// The instances of `kind` this layout knows (open, closed or kept
2065    /// for a panel no longer declared), the panel declared included when
2066    /// placed or closed, in number order.
2067    pub fn instances_of(&self, kind: &PanelId) -> Vec<PanelId> {
2068        let kind = kind.kind();
2069        let mut out: Vec<PanelId> = self
2070            .instances
2071            .iter()
2072            .map(|i| &i.id)
2073            .chain(self.placed())
2074            .chain(self.hidden.iter())
2075            .filter(|p| p.kind() == kind)
2076            .cloned()
2077            .collect();
2078        out.sort_by_key(PanelId::instance_number);
2079        out.dedup();
2080        out
2081    }
2082
2083    /// The id a new instance of `kind` takes: the number after the
2084    /// highest this layout knows, from 2.
2085    pub fn next_instance(&self, kind: &PanelId) -> PanelId {
2086        let n = self
2087            .instances_of(kind)
2088            .iter()
2089            .map(PanelId::instance_number)
2090            .max()
2091            .unwrap_or(1)
2092            .max(1)
2093            + 1;
2094        // A kind's id leaves room for `#<n>`: the shared syntax holds.
2095        kind.instance(n).unwrap_or_else(|_| kind.kind())
2096    }
2097
2098    /// Drops an instance (`<kind>#<n>`): out of where it is, its record
2099    /// and payload gone, not kept closed (closing the panel declared
2100    /// keeps its place, [`Layout::hide`]). Whether it was known.
2101    pub fn drop_instance(&mut self, id: &PanelId) -> bool {
2102        let placed = self.remove(id);
2103        for g in &mut self.docked_groups {
2104            g.take(id);
2105        }
2106        self.docked_groups.retain(|g| g.panels().count() > 1);
2107        let hidden = self.hidden.contains(id);
2108        self.hidden.retain(|h| h != id);
2109        self.closed.remove(id);
2110        self.flyouts.remove(id);
2111        let before = self.instances.len();
2112        self.instances.retain(|i| i.id != *id);
2113        placed || hidden || before != self.instances.len()
2114    }
2115
2116    /// Closes a panel: out of its area or window, and kept closed, its
2117    /// place kept for when it opens again ([`Layout::last_place`]).
2118    pub fn hide(&mut self, panel: &PanelId) {
2119        if let Some(place) = self.place_of(panel) {
2120            self.closed.insert(panel.clone(), place);
2121        }
2122        self.remove(panel);
2123        for g in &mut self.docked_groups {
2124            g.take(panel);
2125        }
2126        self.docked_groups.retain(|g| g.panels().count() > 1);
2127        if !self.hidden.contains(panel) {
2128            self.hidden.push(panel.clone());
2129        }
2130    }
2131
2132    /// Makes a docked panel the shown tab of its tabs; whether it is
2133    /// docked.
2134    pub fn activate(&mut self, panel: &PanelId) -> bool {
2135        self.areas.iter_mut().any(|(_, n)| n.activate(panel))
2136            || self.auxiliary.iter_mut().any(|a| a.show(panel))
2137            || self
2138                .windows
2139                .iter_mut()
2140                .flat_map(|w| w.areas.iter_mut())
2141                .any(|(_, n)| n.activate(panel))
2142    }
2143
2144    /// The shown panels of an area, in order (the shown tab of each
2145    /// tabs node).
2146    pub fn active_in(&self, area: Area) -> Vec<&PanelId> {
2147        fn walk<'a>(n: &'a Node, out: &mut Vec<&'a PanelId>) {
2148            match n {
2149                Node::Tabs { panels, active } => {
2150                    if let Some(p) = panels.get(*active) {
2151                        out.push(p);
2152                    }
2153                }
2154                Node::Split { a, b, .. } => {
2155                    walk(a, out);
2156                    walk(b, out);
2157                }
2158                Node::Grid { children, .. } => {
2159                    for c in children {
2160                        walk(c, out);
2161                    }
2162                }
2163            }
2164        }
2165        let mut out = Vec::new();
2166        for (a, n) in &self.areas {
2167            if *a == area {
2168                walk(n, &mut out);
2169            }
2170        }
2171        out
2172    }
2173
2174    /// Brings a saved layout in line with today's panels and screens:
2175    /// panels no longer declared leave it, new ones go to their default
2176    /// area, so do panels in an area they may no longer be in, a window on
2177    /// a screen that is gone comes back docked. Says what it changed.
2178    /// [`Layout::repair_dormant`] also keeps the places of the panels
2179    /// that leave.
2180    pub fn repair(self, panels: &Panels, screens: &[&str]) -> (Layout, Vec<String>) {
2181        let (layout, notes) = self.repair_with(None, panels, screens);
2182        (layout.layout, notes)
2183    }
2184
2185    /// [`Layout::repair`], keeping the places of panels no longer declared
2186    /// (ADR 0028): `dormant`, the places kept so far, comes back with
2187    /// those of the panels leaving now; a panel declared again goes back
2188    /// to its place (docked at its index beside the same tabs, detached,
2189    /// floating, or closed) instead of to its default area.
2190    pub fn repair_dormant(
2191        self,
2192        dormant: Vec<Dormant>,
2193        panels: &Panels,
2194        screens: &[&str],
2195    ) -> (SavedLayout, Vec<String>) {
2196        self.repair_with(Some(dormant), panels, screens)
2197    }
2198
2199    /// The repair, keeping places when given the places kept so far.
2200    fn repair_with(
2201        self,
2202        kept: Option<Vec<Dormant>>,
2203        panels: &Panels,
2204        screens: &[&str],
2205    ) -> (SavedLayout, Vec<String>) {
2206        let mut notes = Vec::new();
2207        let known = |id: &PanelId| panels.get(id.as_str()).is_some();
2208        let keeping = kept.is_some();
2209        // Places kept: those of panels declared again come back below.
2210        let (mut back, mut dormant): (Vec<Dormant>, Vec<Dormant>) = kept
2211            .unwrap_or_default()
2212            .into_iter()
2213            .partition(|d| known(&d.panel));
2214        let keep_dormant = |dormant: &mut Vec<Dormant>,
2215                            notes: &mut Vec<String>,
2216                            panel: &PanelId,
2217                            place: DormantPlace| {
2218            if keeping {
2219                keep_place(dormant, notes, panel, place);
2220            } else {
2221                notes.push(format!("panel `{panel}` no longer exists"));
2222            }
2223        };
2224        let mut auxiliary = Vec::new();
2225        let mut redock = Vec::new();
2226        for mut a in self.auxiliary {
2227            let place = DormantPlace::Window {
2228                screen: a.screen.clone(),
2229                rect: a.rect,
2230            };
2231            for p in a.panels().filter(|p| !known(p)) {
2232                keep_dormant(&mut dormant, &mut notes, p, place.clone());
2233            }
2234            let gone: Vec<PanelId> = a.panels().filter(|p| !known(p)).cloned().collect();
2235            if gone.len() == a.panels().count() {
2236                continue;
2237            }
2238            for p in &gone {
2239                a.take(p);
2240            }
2241            if !screens.contains(&a.screen.as_str()) {
2242                for p in a.panels() {
2243                    notes.push(format!("screen `{}` is gone: `{p}` docked back", a.screen));
2244                }
2245                redock.extend(a.panels().cloned());
2246            } else {
2247                auxiliary.push(a);
2248            }
2249        }
2250        let mut floating = Vec::new();
2251        for mut g in self.floating {
2252            let mut keep = Vec::new();
2253            for p in g.panels() {
2254                match panels.get(p.as_str()) {
2255                    None => keep_dormant(
2256                        &mut dormant,
2257                        &mut notes,
2258                        p,
2259                        DormantPlace::Floating { pos: g.pos },
2260                    ),
2261                    Some(spec) if !spec.floatable => {
2262                        notes.push(format!(
2263                            "`{p}` no longer floats: docked in its default area"
2264                        ));
2265                        redock.push(p.clone());
2266                    }
2267                    Some(_) => keep.push(p.clone()),
2268                }
2269            }
2270            g.retain_panels(|p| keep.contains(p));
2271            if !g.members.is_empty() {
2272                floating.push(g);
2273            }
2274        }
2275        let docked_groups: Vec<FloatingGroup> = self
2276            .docked_groups
2277            .into_iter()
2278            .filter_map(|mut g| {
2279                g.retain_panels(|p| known(p));
2280                (g.panels().count() > 1).then_some(g)
2281            })
2282            .collect();
2283        let mut areas: Vec<(Area, Node)> = Vec::new();
2284        for (area, node) in self.areas {
2285            for p in node.panels() {
2286                match panels.get(p.as_str()) {
2287                    None => {
2288                        let (beside, index) = node.tabs_of(p).unwrap_or_default();
2289                        keep_dormant(
2290                            &mut dormant,
2291                            &mut notes,
2292                            p,
2293                            DormantPlace::Docked {
2294                                area,
2295                                beside,
2296                                index,
2297                            },
2298                        );
2299                    }
2300                    Some(spec) if !spec.allows(area) => {
2301                        notes.push(format!(
2302                            "`{p}` cannot be in {}: moved to its default area",
2303                            area.name()
2304                        ));
2305                        redock.push(p.clone());
2306                    }
2307                    Some(_) => {}
2308                }
2309            }
2310            let allowed = |id: &PanelId| panels.get(id.as_str()).is_some_and(|s| s.allows(area));
2311            if let Some(n) = node.retain(&allowed) {
2312                areas.push((area, n));
2313            }
2314        }
2315        // Each application window's areas, as the main window's: panels
2316        // no longer declared leave them (their place kept), panels their
2317        // rules keep out of an area go to their default one.
2318        let mut windows = Vec::new();
2319        for w in self.windows {
2320            let mut kept_areas = Vec::new();
2321            for (area, node) in w.areas {
2322                for p in node.panels() {
2323                    match panels.get(p.as_str()) {
2324                        None => {
2325                            let (beside, index) = node.tabs_of(p).unwrap_or_default();
2326                            keep_dormant(
2327                                &mut dormant,
2328                                &mut notes,
2329                                p,
2330                                DormantPlace::InWindow {
2331                                    window: w.window.clone(),
2332                                    area,
2333                                    beside,
2334                                    index,
2335                                },
2336                            );
2337                        }
2338                        Some(spec) if !spec.allows(area) => {
2339                            notes.push(format!(
2340                                "`{p}` cannot be in {} of window `{}`: moved to its default area",
2341                                area.name(),
2342                                w.window
2343                            ));
2344                            redock.push(p.clone());
2345                        }
2346                        Some(_) => {}
2347                    }
2348                }
2349                let allowed =
2350                    |id: &PanelId| panels.get(id.as_str()).is_some_and(|s| s.allows(area));
2351                if let Some(n) = node.retain(&allowed) {
2352                    kept_areas.push((area, n));
2353                }
2354            }
2355            if !kept_areas.is_empty() {
2356                windows.push(WindowAreas {
2357                    window: w.window,
2358                    areas: kept_areas,
2359                    folded: w.folded,
2360                });
2361            }
2362        }
2363        for h in self.hidden.iter().filter(|h| !known(h)) {
2364            keep_dormant(&mut dormant, &mut notes, h, DormantPlace::Hidden);
2365        }
2366        let hidden: Vec<PanelId> = self.hidden.into_iter().filter(|h| known(h)).collect();
2367        let mut layout = Layout {
2368            areas,
2369            auxiliary,
2370            hidden: hidden.clone(),
2371            // The centre never folds.
2372            folded: self
2373                .folded
2374                .into_iter()
2375                .filter(|a| *a != Area::Center)
2376                .collect(),
2377            flyouts: self
2378                .flyouts
2379                .into_iter()
2380                .filter(|(p, w)| known(p) && w.is_finite() && *w > 0.0)
2381                .collect(),
2382            over: self
2383                .over
2384                .into_iter()
2385                .filter(|a| matches!(a, Area::StartSide | Area::EndSide))
2386                .collect(),
2387            floating,
2388            docked_groups,
2389            // The places of panels still closed and declared.
2390            closed: self
2391                .closed
2392                .into_iter()
2393                .filter(|(p, _)| hidden.contains(p))
2394                .collect(),
2395            // An instance stays while it is declared, and while its kind
2396            // is not (its place kept with the dormant ones); a kind
2397            // declared again with one instance drops the others.
2398            instances: self
2399                .instances
2400                .into_iter()
2401                .filter(|i| known(&i.id) || !known(&i.id.kind()))
2402                .collect(),
2403            windows,
2404        };
2405        let placed: Vec<PanelId> = layout.placed().into_iter().cloned().collect();
2406        for p in panels.all() {
2407            if placed.contains(&p.id) || hidden.contains(&p.id) {
2408                continue;
2409            }
2410            // Declared again: back in the place it had.
2411            let mut area = p.area;
2412            if let Some(i) = back.iter().position(|d| d.panel == p.id) {
2413                let came_back = || format!("panel `{}` is back in its place", p.id);
2414                match back.remove(i).place {
2415                    DormantPlace::Hidden => {
2416                        notes.push(came_back());
2417                        layout.hidden.push(p.id.clone());
2418                        continue;
2419                    }
2420                    DormantPlace::InWindow {
2421                        window,
2422                        area: was,
2423                        beside,
2424                        index,
2425                    } if p.allows(was) => {
2426                        notes.push(came_back());
2427                        layout.dock_at(
2428                            &p.id,
2429                            &DormantPlace::InWindow {
2430                                window,
2431                                area: was,
2432                                beside,
2433                                index,
2434                            },
2435                        );
2436                        continue;
2437                    }
2438                    DormantPlace::Floating { pos } if p.floatable => {
2439                        notes.push(came_back());
2440                        layout.float(&p.id, pos);
2441                        continue;
2442                    }
2443                    DormantPlace::Window { screen, rect } if screens.contains(&screen.as_str()) => {
2444                        notes.push(came_back());
2445                        layout
2446                            .auxiliary
2447                            .push(Auxiliary::window(p.id.clone(), &screen, rect));
2448                        continue;
2449                    }
2450                    DormantPlace::Docked {
2451                        area: was,
2452                        beside,
2453                        index,
2454                    } if p.allows(was) => {
2455                        notes.push(came_back());
2456                        let beside_one = layout
2457                            .areas
2458                            .iter_mut()
2459                            .any(|(a, n)| *a == was && n.insert_beside(&p.id, &beside, index));
2460                        if beside_one {
2461                            continue;
2462                        }
2463                        area = was;
2464                    }
2465                    _ => notes.push(format!(
2466                        "panel `{}` cannot go back to its place: placed in its default area",
2467                        p.id
2468                    )),
2469                }
2470                // Not new: docked, open, as it was.
2471                redock.push(p.id.clone());
2472            }
2473            if !p.open && !redock.contains(&p.id) {
2474                layout.hidden.push(p.id.clone());
2475                continue;
2476            }
2477            if !redock.contains(&p.id) {
2478                if p.palette {
2479                    notes.push(format!("new palette `{}` floats", p.id));
2480                    let pos = FloatingGroup::cascade(layout.floating.len());
2481                    layout.float(&p.id, pos);
2482                    continue;
2483                }
2484                notes.push(format!("new panel `{}` placed in its default area", p.id));
2485            }
2486            match layout.areas.iter_mut().find(|(a, _)| *a == area) {
2487                Some((_, Node::Tabs { panels, .. })) => panels.push(p.id.clone()),
2488                Some((_, node)) => {
2489                    let old = std::mem::replace(node, Node::tab(p.id.clone()));
2490                    *node = Node::Split {
2491                        vertical: false,
2492                        ratio: 0.7,
2493                        a: Box::new(old),
2494                        b: Box::new(Node::tab(p.id.clone())),
2495                    };
2496                }
2497                None => layout.areas.push((area, Node::tab(p.id.clone()))),
2498            }
2499        }
2500        layout.areas.sort_by_key(|(a, _)| *a);
2501        (SavedLayout { layout, dormant }, notes)
2502    }
2503
2504    /// The document's text.
2505    pub fn to_json(&self) -> String {
2506        schema().save(self).expect("layouts serialize")
2507    }
2508
2509    /// Reads a layout document of any known version.
2510    pub fn from_json(text: &str) -> Result<Layout, String> {
2511        schema()
2512            .load(text)
2513            .map(|l| l.value)
2514            .map_err(|e| format!("layout: {e}"))
2515    }
2516}