Skip to main content

egui_pop_api/
workbench.rs

1//! The workbench: panels in areas (the centre, the start and end side
2//! bars, the bottom panel), as tabs and splits drawn by `egui_stack`. The
3//! versioned layout document (`egui_pop_model::layout::Layout`) is the
4//! saved form; the areas are the named docks of one `egui_stack::DockSpace`,
5//! which is how they are drawn and rearranged by hand, and which is read
6//! back into the layout as needed.
7//!
8//! <div class="warning">Experimental: may change in any release
9//! (docs/stability.md).</div>
10//!
11//! The workbench lays the areas out (a side area's width, its fold and
12//! flyout, the bottom panel's alignment) and draws each area's dock where
13//! it put the area; the docks share one drag, so a tab dragged from one
14//! area to another gets the same drop zones as inside one (the middle of a
15//! group joins its tabs, its edges split it, a tab bar takes it between two
16//! tabs), with the same preview.
17//!
18//! **Placement rules** come from each panel's declaration
19//! (`PanelSpec`): the areas it may be in (`only_in`), its smallest size
20//! across its area (`min_size`) and the size it asks for
21//! (`default_size`). A tab dragged onto an area its rules keep it out of
22//! is refused there: the drop zone shows it disabled, with the reason. A
23//! tab dropped in another area is moved through the `workbench.move` step,
24//! which a plugin may veto (the tab goes back where it was) or redirect
25//! (ADR 0003).
26//!
27//! The shell's zones are placed in areas as panels: `app.side-bar`
28//! (the `SIDE_BAR` zone, start side), `app.main` (`MAIN`, centre) and
29//! `app.inspector` (`INSPECTOR`, end side); a zone panel with no blocks
30//! is not drawn, and one alone in its area is drawn without a tab bar.
31//!
32//! The layout changes only through named steps (ADR 0011), each with
33//! its default, a plugin may veto, redirect or replace them:
34//!
35//! | Step | Arguments |
36//! |---|---|
37//! | `workbench.move` | `{ "panel", "area" }` (`center`, `start_side`, `end_side`, `bottom`), `window` for an application window's area; also run once a tab is dropped in another area, of any window |
38//! | `workbench.show` | `{ "panel" }`: docks it back (its default area) and shows its tab |
39//! | `workbench.hide` | `{ "panel" }`: closes it (kept closed by the layout) |
40//! | `workbench.focus` | `{ "panel" }`: shows it and gives it the keyboard: see [the focused panel](#the-focused-panel) |
41//! | `workbench.fold` | `{ "area", "folded" }`: an area folded to its strip, or unfolded |
42//! | `workbench.place` | `{ "area", "placement" }`: a side area lies `beside` the centre or `over` it |
43//! | `workbench.flyout` | `{ "panel", "open" }`: a folded side area's panel opens alone over the centre, or closes |
44//! | `workbench.flyout_size` | `{ "panel", "width" }`: the width of a panel's flyout, saved with the layout |
45//! | `workbench.detach` | `{ "panel" }`: into a window of its own (its own scale) |
46//! | `workbench.attach` | `{ "panel" }`: a detached panel docked back |
47//! | `workbench.close_window` | `{ "panel" }`: a detached panel's window closes; the default docks it back, a veto keeps the window |
48//! | `workbench.join_group` | `{ "panel", "group" }`: docks it in the tab group holding `group`, after its tabs, shown |
49//! | `workbench.dock_back` | `{ "panel" }`: a floating or detached panel docked back where it floated from, else in its own area |
50//! | `workbench.zen` | `{ "zen" }`: zen mode on or off (see below) |
51//!
52//! A panel's context menu is the same wherever it is, docked, floating
53//! or detached: [`panel_menu`].
54//!
55//! # The focused panel
56//!
57//! [`AppHandle::focused_panel`], the context key `focusedPanel`, is the panel
58//! the keys obey. It follows the widget focus, however that arrived:
59//!
60//! - **Tab or any widget taking the focus:** its panel, the one it was drawn
61//!   in, is the focused panel.
62//! - **`workbench.focus` and `<panel>.focus`:** the panel is focused at once
63//!   and takes the widget focus in the next pass: the widget named by
64//!   `focus::prefer` in it (a canvas under a toolbar, a search field), else
65//!   the panel itself, a stop of its own, named after it and there only while
66//!   it holds the focus, from which Tab enters its widgets. Never its first
67//!   focusable widget unasked: a slider focused that way would take the wheel
68//!   meant to scroll the panel. It stays where it is if the focus already is
69//!   in the panel. Behind a modal,
70//!   or when an agent's command finds someone typing, only the logical focus
71//!   moves.
72//! - **A press** in a panel, whether or not a widget takes the focus.
73//! - **The focus leaving for something no panel holds** (the menu, the status
74//!   bar, a tab of a dock, nothing): the last panel stays focused until another
75//!   takes it, so a menu's command acts on the panel it was opened from.
76//! - **A floating palette or a flyout only borrows it:** a press in it moves
77//!   nothing, a widget of it taking the focus does, and when that lets go
78//!   (Escape, a click elsewhere, the palette closing) the keys go back to the
79//!   panel of the layout that had them. So a click on a palette's background
80//!   leaves the keys on the image, as in an image editor.
81//! - **A detached window** counts when its widget takes the focus or the
82//!   pointer presses in it, and the main window when it gets the system's focus
83//!   back. Each window keeps its own widget focus (egui does).
84//!
85//! Following is a plain write, not a step, so it cannot loop back into
86//! `workbench.focus`; each change is published once as `workbench.focused`.
87//!
88//! # Moving between regions
89//!
90//! `workbench.next_region` (F6) and `workbench.previous_region` (Shift+F6) move
91//! the keyboard through the window's regions: the activity bar, the start side
92//! area, the end side area, the bottom area, the centre, each palette drawn, an
93//! open flyout, the status bar. Each landing follows
94//! [`egui_pop_core::regions`]: an area without anything to focus in its panel
95//! takes it as `workbench.focus` does, on the panel's own stop. A menu or a
96//! popover open (not a flyout) keeps the focus, for Escape first, and so does a
97//! modal; so does someone typing when an agent asks.
98//!
99//! Each declared panel gets the commands `<panel>.focus` and
100//! `<panel>.toggle`.
101//!
102//! A side area lies **beside** the centre (an egui side panel, taking the
103//! centre's room) or **over** it ([`Placement::Over`]): its folded strip
104//! keeps the room in the layout, so the centre keeps its width, and the
105//! area, unfolded, lies above the centre next to its strip with the kit's
106//! `side-area` shadow (egui_stack's `ZoneState::over`). It is a lasting
107//! placement: a click away or Escape leaves it, only a click on the strip
108//! folds or unfolds it; its edge on the centre's side resizes it.
109//! The centre never folds.
110//!
111//! **Strip icons.** A side area's strip shows one icon per panel, in tab
112//! order: its [`PanelSpec::icon`] (a vector icon tinted by the kit's
113//! `activity-bar-item`, crisp at any scale), else its title's first
114//! letter; the tooltip gives the title and the panel's key, if it has
115//! one. On a folded area a click opens that panel alone as a
116//! **flyout** over the centre, next to the strip, without moving the
117//! layout (egui_stack's `LayoutArea::flyout`, `workbench.flyout`);
118//! Escape or a click away closes it (it is an overlay of the stack,
119//! `egui_pop_core::overlay::hold`: Escape closes the top overlay first,
120//! and a combo box or a context menu opened in it is part of it). A double
121//! click on the icon, or the flyout's pin button, unfolds the area with
122//! the panel shown. The flyout's free edge resizes it; its width is
123//! kept per panel in the layout (`flyouts`, `workbench.flyout_size`).
124//! On an area lying over the centre, open, a click shows the panel.
125//! A panel's indicator ([`crate::strips::Indicator::panel`]) shows on
126//! its icon while the panel is not shown; [`strip`] lists the icons
127//! with their marks for agents, as the `workbench` collector does.
128//!
129//! **Zen mode** (the `workbench.zen` command, a toggle on `Shift+F11`
130//! that an application may rebind) leaves one panel alone, full size, in
131//! the window holding it: the one named (`panel`, the panel menu's "Zen
132//! this panel"), else the focused view or mixed panel, else the
133//! application's choice (`pop.zen.panel`), else the centre's active tab
134//! (with none, the centre whole). The title bar, the menu and status
135//! bars, the activity bar, every other panel and the floating panels are
136//! hidden, and Escape (`workbench.leave_zen`) brings them back: zen mode
137//! changes only what is drawn, never the layout. The way out stays in sight: a strip at the top
138//! centre says how to leave, with a "Leave zen mode" button, for a few
139//! seconds on entering, and again whenever the pointer reaches the top
140//! edge. It is a state of the session, not of the layout: never saved,
141//! so the next start shows the whole workbench.
142//!
143//! A panel may also float over the interface: a palette
144//! (`PanelSpec::palette`) does when it opens, any floatable panel when
145//! asked (its tab menu's Float). Floating panels are drawn by
146//! [`crate::palettes`], with steps of their own (`palette.open`,
147//! `palette.float`, `palette.dock`, `palette.move`, `palette.roll`,
148//! `palette.pin`, `palette.group`, `palette.ungroup`,
149//! `palette.close_group`).
150
151use std::collections::{BTreeMap, BTreeSet, HashMap};
152use std::sync::{Arc, Mutex};
153
154use egui::{Color32, Id, Pos2, Rect, Role, Ui, ViewportId, WidgetInfo};
155use egui_pop_core::focus;
156use egui_pop_core::kit::{Kit, KitCx, Part, Side, State};
157use egui_pop_core::state::Slot;
158use egui_pop_core::strings;
159use egui_pop_model::ids::{PanelId, StepId, ZoneId};
160use egui_pop_model::layout::{Auxiliary, FloatingGroup, Join, Layout, Node, Placement};
161use egui_pop_model::panels::{Area, Instances, PanelSpec, Panels, Place};
162use egui_stack::layout::{
163    Content, Dir, Dismiss, Drops, Flyout, FlyoutPaint, Fold, Layout as ZoneLayout, LayoutArea,
164    LayoutEvent, LayoutPainter, LayoutStyle, SashPaint, Shown, Size, SnapGuidePaint, StripPaint,
165    Zone, ZoneName, ZoneViewer,
166};
167use egui_stack::{
168    DockArea, DockRules, DockSpace, DockState, DropZone, NodeIndex, PartState, Split, TabViewer,
169};
170use serde_json::{Value as Json, json};
171
172use crate::app::AppHandle;
173use crate::bus::OpenPlace;
174use crate::steps::Outcome;
175use crate::strings as txt;
176use crate::window::WindowState;
177
178mod drag_session;
179pub mod instances;
180pub mod panel_menu;
181pub mod window_areas;
182mod window_host;
183use crate::bus::drag::{self, End};
184use drag_session::Dragged;
185
186/// The shell's zones as panels.
187pub const PANEL_SIDE_BAR: PanelId = PanelId::from_static("app.side-bar");
188pub const PANEL_MAIN: PanelId = PanelId::from_static("app.main");
189pub const PANEL_INSPECTOR: PanelId = PanelId::from_static("app.inspector");
190
191pub const STEP_MOVE: StepId = StepId::from_static("workbench.move");
192pub const STEP_SHOW: StepId = StepId::from_static("workbench.show");
193pub const STEP_HIDE: StepId = StepId::from_static("workbench.hide");
194pub const STEP_FOCUS: StepId = StepId::from_static("workbench.focus");
195pub const STEP_FOLD: StepId = StepId::from_static("workbench.fold");
196pub const STEP_PLACE: StepId = StepId::from_static("workbench.place");
197pub const STEP_DETACH: StepId = StepId::from_static("workbench.detach");
198pub const STEP_ATTACH: StepId = StepId::from_static("workbench.attach");
199pub const STEP_CLOSE_WINDOW: StepId = StepId::from_static("workbench.close_window");
200pub const STEP_JOIN_WINDOW: StepId = StepId::from_static("workbench.join_window");
201pub const STEP_ZEN: StepId = StepId::from_static("workbench.zen");
202pub const STEP_FLYOUT: StepId = StepId::from_static("workbench.flyout");
203pub const STEP_FLYOUT_SIZE: StepId = StepId::from_static("workbench.flyout_size");
204pub const STEP_ARRANGE: StepId = StepId::from_static("workbench.arrange");
205pub const STEP_JOIN_GROUP: StepId = StepId::from_static("workbench.join_group");
206pub const STEP_DOCK_BACK: StepId = StepId::from_static("workbench.dock_back");
207
208/// Toggles zen mode: one panel alone, full size, in its window (`panel`,
209/// else the panel that matters now: see
210/// [`AppHandle::zen_target`](crate::AppHandle::zen_target)); the centre
211/// whole when there is none.
212pub const CMD_ZEN: egui_pop_model::ids::CommandId =
213    egui_pop_model::ids::CommandId::from_static("workbench.zen");
214/// Leaves zen mode (Escape while in it).
215/// The keyboard to the next region of the window (F6): see
216/// [Moving between regions](self#moving-between-regions).
217/// The keyboard to the next tab of the focused panel's tab group
218/// (Ctrl+Page Down).
219pub const CMD_NEXT_TAB: egui_pop_model::ids::CommandId =
220    egui_pop_model::ids::CommandId::from_static("workbench.tab.next");
221/// The keyboard to the previous tab of the focused panel's tab group
222/// (Ctrl+Page Up).
223pub const CMD_PREVIOUS_TAB: egui_pop_model::ids::CommandId =
224    egui_pop_model::ids::CommandId::from_static("workbench.tab.previous");
225pub const CMD_NEXT_REGION: egui_pop_model::ids::CommandId =
226    egui_pop_model::ids::CommandId::from_static("workbench.next_region");
227
228/// The keyboard to the previous region of the window (Shift+F6).
229pub const CMD_PREVIOUS_REGION: egui_pop_model::ids::CommandId =
230    egui_pop_model::ids::CommandId::from_static("workbench.previous_region");
231
232pub const CMD_LEAVE_ZEN: egui_pop_model::ids::CommandId =
233    egui_pop_model::ids::CommandId::from_static("workbench.leave_zen");
234
235/// Lays out the focused panel's group and its neighbours (the row,
236/// column or grid holding it) as a grid.
237/// Moves a panel into a detached window, as a tab (`panel`: the focused
238/// one by default; `window`: a panel of that window).
239pub const CMD_MOVE_TO_WINDOW: egui_pop_model::ids::CommandId =
240    egui_pop_model::ids::CommandId::from_static("workbench.move_to_window");
241pub const CMD_ARRANGE_GRID: egui_pop_model::ids::CommandId =
242    egui_pop_model::ids::CommandId::from_static("workbench.arrange.grid");
243/// Lays out the focused panel's group and its neighbours in a row.
244pub const CMD_ARRANGE_ROW: egui_pop_model::ids::CommandId =
245    egui_pop_model::ids::CommandId::from_static("workbench.arrange.row");
246/// Lays out the focused panel's group and its neighbours in a column.
247pub const CMD_ARRANGE_COLUMN: egui_pop_model::ids::CommandId =
248    egui_pop_model::ids::CommandId::from_static("workbench.arrange.column");
249
250/// The setting: how the bottom panel lines up with the side bars, as
251/// VS Code's panel alignment (see [`PanelAlignment`]).
252pub const SETTING_PANEL_ALIGNMENT: egui_pop_model::ids::SettingId =
253    egui_pop_model::ids::SettingId::from_static("workbench.panel_alignment");
254
255/// A size across an area set by the application
256/// ([`AppBuilder::shell_panel_min_size`](crate::AppBuilder::shell_panel_min_size),
257/// `shell_panel_max_size`, `centre_min_size`): points, or a share of the
258/// window's content (0.6: 60 % of its width). A plain number is points.
259#[derive(Clone, Copy, Debug, PartialEq)]
260pub enum ShellSize {
261    Points(f32),
262    Share(f32),
263}
264
265impl ShellSize {
266    /// In points, in a window whose content is `across` points across.
267    pub fn resolve(self, across: f32) -> f32 {
268        let points = match self {
269            ShellSize::Points(p) => p,
270            ShellSize::Share(s) => s * across,
271        };
272        if points.is_finite() {
273            points.max(0.0)
274        } else {
275            0.0
276        }
277    }
278}
279
280impl From<f32> for ShellSize {
281    fn from(points: f32) -> Self {
282        ShellSize::Points(points)
283    }
284}
285
286/// The least and largest sizes the application set for a shell panel.
287#[derive(Clone, Copy, Debug, Default, PartialEq)]
288pub(crate) struct ShellBounds {
289    pub(crate) min: Option<ShellSize>,
290    pub(crate) max: Option<ShellSize>,
291}
292
293/// How the bottom panel lines up with the side bars.
294#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
295pub enum PanelAlignment {
296    /// The window's whole width, under both side bars.
297    Justify,
298    /// Between the side bars, which go down to the bottom: under the
299    /// editors (the default, as VS Code's).
300    #[default]
301    Center,
302    /// From the start edge, under the start side bar, to the end side bar.
303    Start,
304    /// From the start side bar to the end edge, under the end side bar.
305    End,
306}
307
308impl PanelAlignment {
309    /// The setting's choices, in order.
310    pub const CHOICES: [&'static str; 4] = ["justify", "center", "start", "end"];
311
312    pub fn as_str(self) -> &'static str {
313        match self {
314            PanelAlignment::Justify => "justify",
315            PanelAlignment::Center => "center",
316            PanelAlignment::Start => "start",
317            PanelAlignment::End => "end",
318        }
319    }
320
321    pub fn parse(s: &str) -> Option<PanelAlignment> {
322        [
323            PanelAlignment::Justify,
324            PanelAlignment::Center,
325            PanelAlignment::Start,
326            PanelAlignment::End,
327        ]
328        .into_iter()
329        .find(|a| a.as_str() == s)
330    }
331
332    /// The order the side and bottom areas are drawn in: an area drawn
333    /// earlier spans the whole height (a side bar) or width (the bottom).
334    fn order(self) -> [Area; 3] {
335        match self {
336            PanelAlignment::Justify => [Area::Bottom, Area::StartSide, Area::EndSide],
337            PanelAlignment::Center => [Area::StartSide, Area::EndSide, Area::Bottom],
338            PanelAlignment::Start => [Area::EndSide, Area::Bottom, Area::StartSide],
339            PanelAlignment::End => [Area::StartSide, Area::Bottom, Area::EndSide],
340        }
341    }
342}
343
344/// The bottom panel's alignment, as the setting says now.
345pub fn panel_alignment(app: &AppHandle) -> PanelAlignment {
346    egui_pop_core::lock(&app.store())
347        .get(&format!("settings/{SETTING_PANEL_ALIGNMENT}"))
348        .and_then(|e| e.value.as_choice().and_then(PanelAlignment::parse))
349        .unwrap_or_default()
350}
351
352pub use egui_stack::{FloatMove, GroupHandles, MoveFrom};
353
354/// The controls the workbench's docks show beyond the tabs, as the
355/// application sets them ([`AppBuilder::dock_controls`](crate::AppBuilder::dock_controls)).
356/// Each follows egui_stack's default: what is off there is off here.
357///
358/// ```
359/// use egui_pop_api::workbench::{DockControls, MoveFrom};
360///
361/// let controls = DockControls::default()
362///     .eject_group(true)
363///     .float_move_from(MoveFrom::BAR | MoveFrom::EMPTY_SPACE);
364/// assert!(controls.eject_group);
365/// assert!(controls.group_menus);
366/// ```
367///
368/// Need (layout): a tab bar button that moves a whole tab group into a window of its own.
369///
370/// <div class="warning">Experimental: may change in any release
371/// (docs/stability.md).</div>
372#[derive(Clone, Copy, Debug, PartialEq, Eq)]
373#[non_exhaustive]
374pub struct DockControls {
375    /// An "Eject group" button on each docked tab bar: clicked, the
376    /// whole group, its tabs in order, moves into a window of its own
377    /// (the `workbench.detach` step with `group`). Off by default.
378    pub eject_group: bool,
379    /// A right click on the empty part of a tab bar opens the group's
380    /// menu (egui_stack's group context menu: "Move group", and the
381    /// items its bar's buttons offer). On by default.
382    pub group_menus: bool,
383    /// Where else than its move handle a drag moves a floating window
384    /// (egui_stack's `FloatsArea::move_from`): [`MoveFrom::BAR`] by
385    /// default.
386    pub float_move_from: MoveFrom,
387    /// A "+" at the end of each tab bar, docked or floating: it lists the
388    /// closed panels that may open in that group and opens the one chosen
389    /// there (`pop.panel.open` with `here`). Off by default.
390    pub add_buttons: bool,
391}
392
393impl Default for DockControls {
394    fn default() -> Self {
395        Self {
396            eject_group: false,
397            group_menus: true,
398            float_move_from: MoveFrom::BAR,
399            add_buttons: false,
400        }
401    }
402}
403
404impl DockControls {
405    /// Shows the "Eject group" button on docked tab bars, or not.
406    pub fn eject_group(mut self, on: bool) -> Self {
407        self.eject_group = on;
408        self
409    }
410
411    /// Opens a group's menu on a right click of its bar's empty part, or
412    /// not.
413    pub fn group_menus(mut self, on: bool) -> Self {
414        self.group_menus = on;
415        self
416    }
417
418    /// Shows a "+" at the end of each tab bar, opening a closed panel
419    /// there, or not.
420    pub fn add_buttons(mut self, on: bool) -> Self {
421        self.add_buttons = on;
422        self
423    }
424
425    /// Where else than its move handle a drag moves a floating window.
426    pub fn float_move_from(mut self, from: MoveFrom) -> Self {
427        self.float_move_from = from;
428        self
429    }
430}
431
432/// The dock controls in force ([`DockControls`]): the application's,
433/// or the last [`set_dock_controls`].
434pub fn dock_controls(app: &AppHandle) -> DockControls {
435    app.0.dock_controls.get()
436}
437
438/// Changes the dock controls while running, from the next pass: a
439/// settings page or a demonstration turning the "Eject group" buttons on.
440pub fn set_dock_controls(app: &AppHandle, controls: DockControls) {
441    app.0.dock_controls.set(controls);
442    app.egui().request_repaint();
443}
444
445/// The setting: the key held while dragging a tab to carry its whole
446/// group (Shift, Ctrl or Alt; see [`GroupModifier`]).
447pub const SETTING_GROUP_DRAG_MODIFIER: egui_pop_model::ids::SettingId =
448    egui_pop_model::ids::SettingId::from_static("workbench.group_drag_modifier");
449/// The setting: whether the empty part of a tab bar drags its group.
450pub const SETTING_GROUP_EMPTY_SPACE: egui_pop_model::ids::SettingId =
451    egui_pop_model::ids::SettingId::from_static("workbench.group_handle.empty_space");
452/// The setting: whether a grip at the end of each tab bar drags its group.
453pub const SETTING_GROUP_GRIP: egui_pop_model::ids::SettingId =
454    egui_pop_model::ids::SettingId::from_static("workbench.group_handle.grip");
455/// The setting: whether a tab dragged with the group modifier
456/// ([`SETTING_GROUP_DRAG_MODIFIER`]) carries its group.
457pub const SETTING_GROUP_MODIFIER_DRAG: egui_pop_model::ids::SettingId =
458    egui_pop_model::ids::SettingId::from_static("workbench.group_handle.modifier_drag");
459/// The setting: whether the tab menu offers "Move group".
460pub const SETTING_GROUP_MENU: egui_pop_model::ids::SettingId =
461    egui_pop_model::ids::SettingId::from_static("workbench.group_handle.menu");
462/// The setting: whether a floating window shows a move handle.
463pub const SETTING_GROUP_MOVE_WINDOW: egui_pop_model::ids::SettingId =
464    egui_pop_model::ids::SettingId::from_static("workbench.group_handle.move_window");
465/// The setting: what moving a floating window does (see
466/// [`float_move`]).
467pub const SETTING_FLOAT_MOVE: egui_pop_model::ids::SettingId =
468    egui_pop_model::ids::SettingId::from_static("workbench.float_move");
469/// The setting: which panels may float over the interface (see
470/// [`FloatScope`]); it only narrows what each panel's spec allows.
471pub const SETTING_FLOAT_PANELS: egui_pop_model::ids::SettingId =
472    egui_pop_model::ids::SettingId::from_static("workbench.float_panels");
473
474/// Which panels may float ([`SETTING_FLOAT_PANELS`]): it narrows what
475/// each panel declares ([`PanelSpec::floatable`]), never widens it.
476#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
477pub enum FloatScope {
478    /// Every panel its spec lets float (the default).
479    #[default]
480    Any,
481    /// Only the palettes (panels that open floating, [`PanelSpec::palette`]).
482    Palettes,
483}
484
485impl FloatScope {
486    /// The setting's choices, in order.
487    pub const CHOICES: [&'static str; 2] = ["any", "palettes"];
488
489    pub fn as_str(self) -> &'static str {
490        match self {
491            FloatScope::Any => "any",
492            FloatScope::Palettes => "palettes",
493        }
494    }
495
496    pub fn parse(s: &str) -> Option<FloatScope> {
497        [FloatScope::Any, FloatScope::Palettes]
498            .into_iter()
499            .find(|m| m.as_str() == s)
500    }
501
502    /// Whether it lets a panel float, its spec allowing it.
503    pub fn allows(self, spec: &PanelSpec) -> bool {
504        self == FloatScope::Any || spec.palette
505    }
506}
507
508/// Which panels may float, as the setting says now.
509pub fn float_scope(app: &AppHandle) -> FloatScope {
510    setting_value(app, &SETTING_FLOAT_PANELS, |v| {
511        v.as_choice().and_then(FloatScope::parse)
512    })
513    .unwrap_or_default()
514}
515
516/// The group handles an application allows unless it says otherwise
517/// ([`AppBuilder::group_handles`](crate::AppBuilder::group_handles)):
518/// every handle, the tab menu's "Move group" included, whose list names
519/// the areas by their translated titles and the panels they hold.
520pub const DEFAULT_GROUP_HANDLES: GroupHandles = GroupHandles::ALL;
521
522/// Each group handle, its setting and its label and description.
523const HANDLE_SETTINGS: [(GroupHandles, egui_pop_model::ids::SettingId, &str, &str); 5] = [
524    (
525        GroupHandles::EMPTY_SPACE,
526        SETTING_GROUP_EMPTY_SPACE,
527        "Drag a group by its tab bar",
528        "Whether dragging the empty part of a tab bar moves its whole group of tabs.",
529    ),
530    (
531        GroupHandles::GRIP,
532        SETTING_GROUP_GRIP,
533        "Group grip",
534        "Whether each tab bar ends with a grip that moves its whole group of tabs, even when the bar is full.",
535    ),
536    (
537        GroupHandles::MODIFIER_DRAG,
538        SETTING_GROUP_MODIFIER_DRAG,
539        "Drag a group with a key held",
540        "Whether a tab dragged with the group key held (Group drag key) carries its whole group.",
541    ),
542    (
543        GroupHandles::MENU,
544        SETTING_GROUP_MENU,
545        "Move group in the tab menu",
546        "Whether a tab's menu offers to move its whole group to another area or a new window.",
547    ),
548    (
549        GroupHandles::MOVE_WINDOW,
550        SETTING_GROUP_MOVE_WINDOW,
551        "Window move handle",
552        "Whether a floating window shows a handle at the end of its tab bar that moves the window.",
553    ),
554];
555
556/// The key held while dragging a tab to carry its whole group
557/// ([`SETTING_GROUP_DRAG_MODIFIER`]).
558///
559/// It never clashes with the workbench's other keys: Ctrl docks a
560/// floating palette (`gesture.workbench.dock`), a palette's own drag,
561/// never a tab's; Shift on a tab bar's buttons is a click, not a drag.
562#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
563pub enum GroupModifier {
564    /// Shift (the default).
565    #[default]
566    Shift,
567    /// Ctrl (Cmd on macOS).
568    Ctrl,
569    /// Alt (Option on macOS).
570    Alt,
571}
572
573impl GroupModifier {
574    /// The setting's choices, in order.
575    pub const CHOICES: [&'static str; 3] = ["shift", "ctrl", "alt"];
576
577    pub fn as_str(self) -> &'static str {
578        match self {
579            GroupModifier::Shift => "shift",
580            GroupModifier::Ctrl => "ctrl",
581            GroupModifier::Alt => "alt",
582        }
583    }
584
585    pub fn parse(s: &str) -> Option<GroupModifier> {
586        [
587            GroupModifier::Shift,
588            GroupModifier::Ctrl,
589            GroupModifier::Alt,
590        ]
591        .into_iter()
592        .find(|m| m.as_str() == s)
593    }
594
595    /// egui's modifiers for it (Ctrl is the command key).
596    pub fn modifiers(self) -> egui::Modifiers {
597        match self {
598            GroupModifier::Shift => egui::Modifiers::SHIFT,
599            GroupModifier::Ctrl => egui::Modifiers::COMMAND,
600            GroupModifier::Alt => egui::Modifiers::ALT,
601        }
602    }
603}
604
605/// The float move setting's choices: [`FloatMove::Move`], [`FloatMove::Dock`].
606const FLOAT_MOVE_CHOICES: [&str; 2] = ["move", "dock"];
607
608/// Declares the group handles' settings (those of the handles the
609/// application allows, `allowed`), the group drag key and the float move.
610pub(crate) fn register_group_settings(
611    ctx: &mut crate::ctx::Ctx<'_>,
612    allowed: GroupHandles,
613) -> Result<(), crate::ctx::CtxError> {
614    use egui_pop_model::values::Descriptor;
615    if allowed.contains(GroupHandles::MODIFIER_DRAG) {
616        ctx.setting(
617            SETTING_GROUP_DRAG_MODIFIER,
618            Descriptor::choice(
619                "Group drag key",
620                &GroupModifier::CHOICES,
621                GroupModifier::default().as_str(),
622            )
623            .description(
624                "The key held while dragging a tab to move its whole group of tabs: shift, ctrl (cmd on macOS) or alt.",
625            ),
626        )?;
627    }
628    for (flag, id, label, description) in HANDLE_SETTINGS {
629        if allowed.contains(flag) {
630            ctx.setting(id, Descriptor::bool(label, true).description(description))?;
631        }
632    }
633    if allowed.contains(GroupHandles::MOVE_WINDOW) {
634        ctx.setting(
635            SETTING_FLOAT_MOVE,
636            Descriptor::choice("Moving a window", &FLOAT_MOVE_CHOICES, "move").description(
637                "What moving a floating window by its title bar or move handle does: only move it (move), or dock it into the area it is let go over, highlighted while it moves (dock; where the system hides window positions it only moves).",
638            ),
639        )?;
640    }
641    ctx.setting(
642        SETTING_FLOAT_PANELS,
643        Descriptor::choice(
644            "Floating panels",
645            &FloatScope::CHOICES,
646            FloatScope::default().as_str(),
647        )
648        .description(
649            "Which panels may float over the interface: any panel that allows it (any), or only the palettes, the panels that open floating (palettes).",
650        ),
651    )?;
652    Ok(())
653}
654
655/// A setting's value from the store, read by `read`.
656fn setting_value<T>(
657    app: &AppHandle,
658    id: &egui_pop_model::ids::SettingId,
659    read: impl FnOnce(&egui_pop_model::values::Value) -> Option<T>,
660) -> Option<T> {
661    egui_pop_core::lock(&app.store())
662        .get(&format!("settings/{id}"))
663        .and_then(|e| read(&e.value))
664}
665
666/// The handles that move a whole tab group: those the application
667/// allows ([`AppBuilder::group_handles`](crate::AppBuilder::group_handles))
668/// that the user left on in the settings.
669pub fn group_handles(app: &AppHandle) -> GroupHandles {
670    let allowed = app.0.group_handles.get();
671    let mut user = GroupHandles::ALL;
672    for (flag, id, _, _) in HANDLE_SETTINGS {
673        let on = setting_value(app, &id, egui_pop_model::values::Value::as_bool).unwrap_or(true);
674        user = user.with(flag, on);
675    }
676    allowed.intersection(user)
677}
678
679/// The key held while dragging a tab to carry its group, as the setting
680/// says now.
681pub fn group_drag_modifier(app: &AppHandle) -> GroupModifier {
682    setting_value(app, &SETTING_GROUP_DRAG_MODIFIER, |v| {
683        v.as_choice().and_then(GroupModifier::parse)
684    })
685    .unwrap_or_default()
686}
687
688/// What moving a floating window does, as the setting says now:
689/// [`FloatMove::Move`] (only moves it) unless the user chose `dock`.
690pub fn float_move(app: &AppHandle) -> FloatMove {
691    match setting_value(app, &SETTING_FLOAT_MOVE, |v| {
692        v.as_choice().map(str::to_owned)
693    }) {
694        Some(choice) if choice == "dock" => FloatMove::Dock,
695        _ => FloatMove::Move,
696    }
697}
698
699/// The workbench's listener of `stack.dock.drop`: the panels' rules
700/// refuse a tab dragged into an area it stays out of, with the reason.
701pub const STACK_DROP: &str = "pop.workbench.dock_drop";
702/// The workbench's listener of `stack.layout.changed`: the shell follows
703/// the zones the user resized, folded and unfolded, and the flyouts.
704pub const STACK_LAYOUT: &str = "pop.workbench.stack_layout";
705
706/// A panel as egui_stack's points name it: its id.
707fn stack_key(panel: &PanelId) -> String {
708    panel.as_str().to_owned()
709}
710
711/// Gives the space the application's bus (egui_stack's `stack.*` points,
712/// declared on it) and registers the workbench's listeners, local to the
713/// interface's thread: the drop veto ([`STACK_DROP`]) and the shell's
714/// changes ([`STACK_LAYOUT`]).
715pub(crate) fn listen_stack(app: &AppHandle) {
716    use bus_contract::{HookError, ListenOpts};
717    use egui_stack::bus::{DockDrop, LayoutChanged, POINTS};
718    let bus = app.bus();
719    // A second space on the bus finds them declared.
720    let _ = bus_contract::declare_all(&*bus, POINTS);
721    {
722        let mut wb = app.workbench_mut();
723        wb.bus = Some(bus.clone());
724        if let Some(space) = wb.space.as_mut() {
725            space.set_bus(bus.clone(), stack_key);
726        }
727    }
728    let mine = || ListenOpts::new().owner(crate::bus::OWNER);
729    let weak = app.downgrade();
730    let drop = bus.listen_local::<DockDrop>(STACK_DROP, mine(), move |ask, ()| {
731        let Ok(app) = weak.get() else { return Ok(()) };
732        match drop_refusal(&app, ask) {
733            Some(why) => Err(HookError::refuse(why)),
734            None => Ok(()),
735        }
736    });
737    let weak = app.downgrade();
738    let layout = bus.listen_local::<LayoutChanged>(STACK_LAYOUT, mine(), move |change, ()| {
739        if let Ok(app) = weak.get() {
740            app.0.stack_changes.borrow_mut().push(change.clone());
741        }
742        Ok(())
743    });
744    for listened in [drop, layout] {
745        if let Err(e) = listened {
746            log::error!(target: "egui_pop", "the workbench's stack listeners: {e}");
747        }
748    }
749}
750
751/// The panels' rules for a drop egui_stack asks about (`stack.dock.drop`):
752/// the reason a tab may not go there (empty when there is none to say),
753/// `None` when it may. Moving inside its own area, or among a detached
754/// window's tabs, is always allowed; an application window's area keeps
755/// a panel out as the main window's area of that name does; a detached window takes the panels
756/// that may live in a window of their own. For a group, the first of its
757/// tabs refused. A drop into or out of a detached window allowed here
758/// still runs its step, which may veto it (`settle_drop`).
759fn drop_refusal(app: &AppHandle, ask: &egui_stack::bus::DropAsk) -> Option<String> {
760    if ask.from.is_none() && ask.to.is_none() {
761        return None;
762    }
763    let ctx = app.egui();
764    let panels = || {
765        let wb = app.workbench_mut();
766        let specs: Vec<PanelSpec> = (ask.tabs.iter())
767            .filter_map(|key| PanelId::new(key.as_str()).ok())
768            .filter_map(|p| wb.spec(&p).cloned())
769            .collect();
770        specs
771    };
772    if ask.to.as_deref().is_some_and(|d| d.starts_with("window:")) {
773        if ask.from.as_deref() == ask.to.as_deref() {
774            return None;
775        }
776        return panels().iter().find_map(|spec| {
777            spec.refuses(&crate::mounts::panel_host(Place::Window))
778                .map(|_| stays_docked(&ctx, spec))
779        });
780    }
781    // An area of the main window, or of an application window: the
782    // window (`None` for the main one) and the area.
783    let place = |dock: &str| {
784        dock_area(dock)
785            .map(|(a, _)| (None, a))
786            .or_else(|| window_areas::dock_place(dock).map(|(w, a)| (Some(w.to_owned()), a)))
787    };
788    let Some((window, area)) = ask.to.as_deref().and_then(place) else {
789        return Some(String::new());
790    };
791    let from = ask.from.as_deref().and_then(place);
792    if from == Some((window, area)) {
793        return None;
794    }
795    panels().iter().find_map(|spec| {
796        let title = strings::panel_title(&ctx, spec.id.as_str(), &spec.title);
797        refusal(&ctx, spec, &title, area)
798            .or_else(|| spec.refuses(&crate::mounts::panel_host(Place::Area(area))))
799    })
800}
801
802/// Why a panel stays out of the detached windows, as the drop zone says it.
803fn stays_docked(ctx: &egui::Context, spec: &PanelSpec) -> String {
804    let title = strings::panel_title(ctx, spec.id.as_str(), &spec.title);
805    strings::tr_args(ctx, &txt::WORKBENCH_STAYS_DOCKED, &[("panel", &title)])
806}
807
808/// Where a panel detached without a known place opens, and its size.
809pub const DETACHED: [f32; 4] = [80.0, 80.0, 480.0, 360.0];
810
811/// The workbench's steps, as the framework declares them.
812pub(crate) fn steps() -> Vec<crate::steps::StepSpec> {
813    use crate::steps::StepSpec;
814    vec![
815        StepSpec::new(
816            STEP_MOVE,
817            "A panel moves to an area (`panel`, `area`; `window` for an application window's area); a tab dropped in another area, of any window, runs it after the drop, and a veto puts it back.",
818        )
819            .args(json!({ "panel": "app.inspector", "area": "start_side" })),
820        StepSpec::new(
821            STEP_SHOW,
822            "A panel is shown (`panel`; `instance`: `new` opens a new instance of a panel declared with several). Closed, it goes back where it was (`place`: `last`, the default); that place gone, into the focused panel's tab group when its areas allow it, else its declared area. `place`: `here` opens it in the tab group holding `group` (else the focused panel's), an area's name docks it there.",
823        )
824        .args(json!({ "panel": "app.inspector", "place": "last" })),
825        StepSpec::new(STEP_HIDE, "A panel is closed (`panel`).")
826            .args(json!({ "panel": "app.inspector" })),
827        StepSpec::new(
828            STEP_FOCUS,
829            "A panel is shown and gets the keyboard (`panel`).",
830        )
831        .args(json!({ "panel": "app.inspector" })),
832        StepSpec::new(
833            STEP_FOLD,
834            "An area folds to its strip, or unfolds (`area`, `folded`).",
835        )
836        .args(json!({ "area": "start_side", "folded": true })),
837        StepSpec::new(
838            STEP_PLACE,
839            "A side area lies beside the centre or over it (`area`, `placement`: `beside` or `over`).",
840        )
841        .args(json!({ "area": "start_side", "placement": "over" })),
842        StepSpec::new(
843            STEP_FLYOUT,
844            "A folded side area's panel opens alone over the centre (`panel`, `open`), or closes (`open`: false).",
845        )
846        .args(json!({ "panel": "app.side-bar", "open": true })),
847        StepSpec::new(
848            STEP_FLYOUT_SIZE,
849            "A panel's flyout is given a width in points (`panel`, `width`), saved with the layout.",
850        )
851        .args(json!({ "panel": "app.side-bar", "width": 280.0 })),
852        StepSpec::new(
853            STEP_ARRANGE,
854            "The groups beside a panel's (the row, column or grid holding it) are laid out again (`panel`, `as`: `grid`, `row` or `column`; `columns` for a grid, none for as many as fit a square).",
855        )
856        .args(json!({ "panel": "app.inspector", "as": "grid" })),
857        StepSpec::new(
858            STEP_DETACH,
859            "A panel moves to a window of its own (`panel`); with `group`, the tab group holding it, all its tabs in order, its shown tab kept.",
860        )
861        .args(json!({ "panel": "app.inspector" })),
862        StepSpec::new(
863            STEP_ATTACH,
864            "A detached panel docks back in its area (`panel`).",
865        )
866        .args(json!({ "panel": "app.inspector" })),
867        StepSpec::new(
868            STEP_CLOSE_WINDOW,
869            "A detached panel's window closes; by default its panels dock back (`panel`).",
870        )
871        .args(json!({ "panel": "app.inspector" })),
872        StepSpec::new(
873            STEP_JOIN_WINDOW,
874            "A panel moves into a detached window as a tab (`panel`; `window`: a panel of that window); with `group`, the tab group holding it, all its tabs in order, its shown tab kept.",
875        )
876        .args(json!({ "panel": "app.outline", "window": "app.inspector" })),
877        StepSpec::new(
878            STEP_JOIN_GROUP,
879            "A panel docks in the tab group holding another one, after its tabs and shown (`panel`; `group`: a docked panel of that group), out of where it was: floating, detached or docked.",
880        )
881        .args(json!({ "panel": "app.outline", "group": "app.inspector" })),
882        StepSpec::new(
883            STEP_DOCK_BACK,
884            "A floating or detached panel docks back (`panel`): where it floated from (its area, among the same tabs), else its own area.",
885        )
886        .args(json!({ "panel": "app.outline" })),
887        StepSpec::new(
888            STEP_ZEN,
889            "Zen mode starts (`zen`: true: `panel` alone, full size, in the window holding it; without `panel`, the centre whole) or ends (false). The layout is left as it is.",
890        )
891        .args(json!({ "zen": true, "panel": "app.viewer" })),
892    ]
893}
894
895/// How close to the areas' edges a dragged tab or palette is offered a
896/// closed side or bottom area.
897const EDGE: f32 = 48.0;
898
899/// The id the areas' docks share: one drag between them.
900pub(crate) fn space_id() -> Id {
901    Id::unique("egui_pop.workbench.space")
902}
903
904/// The name of the space's drop target over an area drawn bare (a zone
905/// alone, without a tab bar): a tab dropped there joins the area's tabs.
906fn bare_target(area: Area) -> &'static str {
907    match area {
908        Area::Center => "center.bare",
909        Area::StartSide => "start_side.bare",
910        Area::EndSide => "end_side.bare",
911        Area::Bottom => "bottom.bare",
912    }
913}
914
915/// The area a dock of the space stands for (its own, or its bare target),
916/// and whether it is the bare target.
917fn dock_area(name: &str) -> Option<(Area, bool)> {
918    match name.strip_suffix(".bare") {
919        Some(area) => area_from(area).map(|a| (a, true)),
920        None => area_from(name).map(|a| (a, false)),
921    }
922}
923
924/// An area's dock rules: any split, as inside one area; no floating
925/// window (a panel leaves the main window through `workbench.detach`);
926/// kept when empty, a target for a tab dragged to a closed area.
927fn area_rules() -> DockRules {
928    DockRules::default().windows(false).keep_when_empty(true)
929}
930
931/// A detached window's dock's rules: tabs only (no split), no float of
932/// egui_stack's own (a panel leaves through `workbench.detach`), kept when
933/// a drag empties it (its step decides: `settle_drop`).
934fn window_rules() -> DockRules {
935    area_rules().splits(egui_stack::AllowedSplits::None)
936}
937
938/// A bare target's rules: the tab joins the area's tabs, so no split.
939fn bare_rules() -> DockRules {
940    area_rules().splits(egui_stack::AllowedSplits::None)
941}
942
943/// An area's name in documents and arguments.
944pub fn area_name(area: Area) -> &'static str {
945    match area {
946        Area::Center => "center",
947        Area::StartSide => "start_side",
948        Area::EndSide => "end_side",
949        Area::Bottom => "bottom",
950    }
951}
952
953/// Whether a side area lies on the window's left: the start one, unless
954/// the primary side bar is on the right (`flipped`). `false` for the
955/// centre and the bottom area.
956pub(crate) fn on_left(area: Area, flipped: bool) -> bool {
957    match area {
958        Area::StartSide => !flipped,
959        Area::EndSide => flipped,
960        _ => false,
961    }
962}
963
964/// An area from its name.
965pub fn area_from(name: &str) -> Option<Area> {
966    Area::ALL.into_iter().find(|a| area_name(*a) == name)
967}
968
969/// The drop hint shown while a tab is dragged (in its area or over
970/// another), or a palette over an area it docks in: what
971/// [`AppHandle::drop_hint`], `overlay_rects` (`drop:<panel>:<area>`) and
972/// the `workbench` collector report.
973#[derive(Clone, Debug, PartialEq)]
974#[non_exhaustive]
975pub struct DropHint {
976    pub panel: PanelId,
977    /// The area the panel would go to (`area_name`).
978    pub area: &'static str,
979    /// Where the hint is drawn, in points: the region the panel would
980    /// take (a group of tabs, the half of it a split gives, a place in a
981    /// tab bar, a closed area along the edge).
982    pub rect: Rect,
983    /// Why the panel may not go there, as the hint says it; `None` when
984    /// it may.
985    pub refusal: Option<String>,
986    /// How it would go there: [`DropZone::Center`] joins a group's tabs,
987    /// an edge splits the group on that side.
988    pub zone: DropZone,
989    /// Its index among the tabs it would join; `None` for a split.
990    pub index: Option<usize>,
991    /// A palette's: the ghost of its tab where it would land; `None` when
992    /// the drop is refused or not armed, and for a tab (the drop zone
993    /// shows it).
994    pub preview: Option<TabPreview>,
995    /// Whether a drop now docks: always for a tab; for a palette, as its
996    /// drag mode and the dock keys held say (`input.dock_drag`,
997    /// `gesture.workbench.dock`). Not armed, nothing is drawn and a drop
998    /// only moves the palette.
999    pub armed: bool,
1000}
1001
1002/// Where a drop hint draws a dragged palette's tab (the kit's
1003/// `tab-preview`): in the target area's tab bar, after its tabs, where a
1004/// drop on the area puts it.
1005#[derive(Clone, Debug, PartialEq)]
1006pub struct TabPreview {
1007    /// The area (`area_name`).
1008    pub area: &'static str,
1009    /// The tab's index among the tabs it joins (their count: a drop on
1010    /// an area appends to its first tabs).
1011    pub index: usize,
1012    /// Where the ghost is drawn, in points.
1013    pub rect: Rect,
1014}
1015
1016/// An area's first tab bar as drawn last frame, where a drop on the area
1017/// adds its tab: the bar, the right edge of its last tab, its tab count.
1018#[derive(Clone, Copy, Debug, PartialEq)]
1019pub struct TabBar {
1020    pub rect: Rect,
1021    pub end: f32,
1022    pub tabs: usize,
1023}
1024
1025/// A tab dragged over a detached panel's window: a drop there moves
1026/// it into that window, as a tab (`workbench.join_window`).
1027#[derive(Clone, Debug, PartialEq)]
1028pub struct WindowDrop {
1029    /// The dragged panel.
1030    pub panel: PanelId,
1031    /// The window, by its first panel.
1032    pub window: PanelId,
1033    /// Where it would go: the window's body, the zone drawn there.
1034    pub zone: egui_stack::DropZone,
1035    /// Why it may not go there, as the zone's label says.
1036    pub refusal: Option<String>,
1037}
1038
1039impl DropHint {
1040    /// Its name among the overlays: `drop:<panel>:<area>`.
1041    pub fn name(&self) -> String {
1042        format!("drop:{}:{}", self.panel, self.area)
1043    }
1044}
1045
1046/// A change of the workbench, as a step runs it.
1047///
1048/// New kinds of change come with new features: a `match` on it keeps a
1049/// `_` arm.
1050#[derive(Clone, Debug, PartialEq)]
1051#[non_exhaustive]
1052pub enum Change {
1053    Move(PanelId, Area),
1054    /// A panel moves to an area of an application window other than the
1055    /// main one: the panel, the window's id, the area (`workbench.move`
1056    /// with `window`). A tab dropped there runs it after the drop.
1057    MoveInWindow(PanelId, String, Area),
1058    /// A panel is shown: closed, back where it was (`pop.panel.open`'s
1059    /// `last`).
1060    Show(PanelId),
1061    /// A panel opens here (in the tab group holding the panel given, else
1062    /// the focused panel's) or in an area, moved there when open
1063    /// elsewhere (`pop.panel.open`); [`OpenPlace::Last`] is [`Change::Show`].
1064    Open(PanelId, OpenPlace, Option<PanelId>),
1065    /// A new instance of a panel declared with several opens (its kind,
1066    /// then where, as [`Change::Open`]): `pop.panel.open` with
1067    /// `instance: "new"`.
1068    NewInstance(PanelId, OpenPlace, Option<PanelId>),
1069    /// A panel is closed: an instance (`<kind>#<n>`) is dropped with its
1070    /// payload, any other keeps its place for when it opens again.
1071    Hide(PanelId),
1072    Focus(PanelId),
1073    /// An area folded to its strip (`true`) or unfolded.
1074    Fold(Area, bool),
1075    /// An application window's area folded to its strip (`true`) or
1076    /// unfolded: the window's id, then as [`Change::Fold`]
1077    /// (`workbench.fold` with `window`).
1078    FoldWindow(String, Area, bool),
1079    /// A side area lies beside the centre or over it.
1080    Place(Area, Placement),
1081    /// A panel moved to a window of its own.
1082    Detach(PanelId),
1083    /// A detached panel docked back in its area.
1084    Attach(PanelId),
1085    /// A detached panel's window closed (by default: docked back, with
1086    /// the panels that joined it as tabs).
1087    CloseWindow(PanelId),
1088    /// A panel joins a detached window as a tab: the window holding the
1089    /// second panel.
1090    JoinWindow(PanelId, PanelId),
1091    /// The tab group holding a panel (all its tabs, in order, its shown
1092    /// tab kept) moves to a window of its own (`workbench.detach` with
1093    /// `group`).
1094    DetachGroup(PanelId),
1095    /// The tab group holding a panel joins a detached window, after its
1096    /// tabs: the window holding the second panel (`workbench.join_window`
1097    /// with `group`).
1098    JoinWindowGroup(PanelId, PanelId),
1099    /// A panel docks in the tab group holding the second one (docked),
1100    /// after its tabs, shown: out of where it was, floating, detached or
1101    /// docked.
1102    JoinGroup(PanelId, PanelId),
1103    /// A floating or detached panel docks back: where it floated from
1104    /// (its area, among the same tabs), else in its own area.
1105    DockBack(PanelId),
1106    /// A palette opens: floating (where it was, or cascaded), or docked
1107    /// when it may not float.
1108    OpenPalette(PanelId),
1109    /// A panel floats over the interface, its top-left at a place (in
1110    /// points from the workbench's top-left).
1111    Float(PanelId, [f32; 2]),
1112    /// The docked tab group holding a panel floats whole, its top-left at
1113    /// a place: one floating group of tabs, in order; Dock back puts it
1114    /// back as it was (`palette.float` with `group`).
1115    FloatGroup(PanelId, [f32; 2]),
1116    /// A floating panel docks in an area (taken out of its group).
1117    Dock(PanelId, Area),
1118    /// Every member of a floating panel's group docks in an area, as
1119    /// tabs.
1120    DockGroup(PanelId, Area),
1121    /// Floating panels join the group of another one: above it, below
1122    /// it, or as tabs.
1123    Group(Vec<PanelId>, PanelId, Join),
1124    /// A floating panel comes out of its group, alone at a place.
1125    Ungroup(PanelId, [f32; 2]),
1126    /// The tab group a floating panel is a tab of, nested in a stack,
1127    /// comes out of the stack whole, at a place.
1128    UngroupTabs(PanelId, [f32; 2]),
1129    /// Every member of a floating panel's group closes.
1130    CloseGroup(PanelId),
1131    /// A floating panel moves.
1132    MovePalette(PanelId, [f32; 2]),
1133    /// A floating panel's group is resized (its frame, in points), or
1134    /// sized by its content again (`None`).
1135    ResizePalette(PanelId, Option<[f32; 2]>),
1136    /// A floating panel's group is resized and moved at once (its size,
1137    /// then its place): a left or top edge dragged.
1138    ResizePaletteAt(PanelId, [f32; 2], [f32; 2]),
1139    /// A floating panel rolls up to its header band (`true`) or down.
1140    Roll(PanelId, bool),
1141    /// A floating panel is pinned (`true`) or unpinned.
1142    Pin(PanelId, bool),
1143    /// A folded side area's panel opens alone over the centre (`true`),
1144    /// or closes.
1145    Flyout(PanelId, bool),
1146    /// The width of a panel's flyout, in points.
1147    FlyoutSize(PanelId, f32),
1148    /// Zen mode on (`true`: only the centre is shown) or off.
1149    Zen(bool),
1150    /// The row, column or grid holding a panel's group is laid out again.
1151    Arrange(PanelId, Arrangement),
1152}
1153
1154/// How [`Change::Arrange`] lays out the groups beside a panel's.
1155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1156#[non_exhaustive]
1157pub enum Arrangement {
1158    /// In rows and columns, row by row: `columns` of them, or as many as
1159    /// the square root of their number, rounded up (`None`).
1160    Grid(Option<usize>),
1161    /// Side by side.
1162    Row,
1163    /// One above the other.
1164    Column,
1165}
1166
1167impl Arrangement {
1168    /// Its name in a step's arguments.
1169    pub fn as_str(self) -> &'static str {
1170        match self {
1171            Arrangement::Grid(_) => "grid",
1172            Arrangement::Row => "row",
1173            Arrangement::Column => "column",
1174        }
1175    }
1176
1177    fn from_args(args: &Json) -> Result<Arrangement, String> {
1178        let name = args.get("as").and_then(Json::as_str).unwrap_or("grid");
1179        match name {
1180            "grid" => {
1181                let columns = match args.get("columns").filter(|c| !c.is_null()) {
1182                    None => None,
1183                    Some(c) => Some(
1184                        c.as_u64()
1185                            .filter(|n| *n > 0)
1186                            .ok_or("`columns` is a positive whole number")?
1187                            as usize,
1188                    ),
1189                };
1190                Ok(Arrangement::Grid(columns))
1191            }
1192            "row" => Ok(Arrangement::Row),
1193            "column" => Ok(Arrangement::Column),
1194            _ => Err(format!(
1195                "no arrangement `{name}` (`grid`, `row` or `column`)"
1196            )),
1197        }
1198    }
1199}
1200
1201/// `[x, y]` as a place.
1202fn pos_of(args: &Json) -> Result<[f32; 2], String> {
1203    let a = args
1204        .get("pos")
1205        .and_then(Json::as_array)
1206        .ok_or("`pos` is missing")?;
1207    match a.as_slice() {
1208        [x, y] => Ok([
1209            x.as_f64().ok_or("`pos` holds numbers")? as f32,
1210            y.as_f64().ok_or("`pos` holds numbers")? as f32,
1211        ]),
1212        _ => Err("`pos` is `[x, y]`".into()),
1213    }
1214}
1215
1216/// `[width, height]` as a size, or `null` (sized by the content).
1217fn size_of(args: &Json) -> Result<Option<[f32; 2]>, String> {
1218    let Some(a) = args.get("size").filter(|s| !s.is_null()) else {
1219        return Ok(None);
1220    };
1221    match a.as_array().map(Vec::as_slice) {
1222        Some([w, h]) => {
1223            let w = w.as_f64().ok_or("`size` holds numbers")? as f32;
1224            let h = h.as_f64().ok_or("`size` holds numbers")? as f32;
1225            if w > 0.0 && h > 0.0 {
1226                Ok(Some([w, h]))
1227            } else {
1228                Err("`size` is positive".into())
1229            }
1230        }
1231        _ => Err("`size` is `[width, height]` or `null`".into()),
1232    }
1233}
1234
1235impl Change {
1236    pub(crate) fn step(&self) -> (StepId, Json) {
1237        match self {
1238            Change::Move(p, a) => (STEP_MOVE, json!({ "panel": p, "area": area_name(*a) })),
1239            Change::MoveInWindow(p, w, a) => (
1240                STEP_MOVE,
1241                json!({ "panel": p, "window": w, "area": area_name(*a) }),
1242            ),
1243            Change::Show(p) => (STEP_SHOW, json!({ "panel": p })),
1244            Change::Open(p, place, group) => {
1245                let mut args = json!({ "panel": p, "place": place.as_str() });
1246                if let Some(g) = group {
1247                    args["group"] = json!(g);
1248                }
1249                (STEP_SHOW, args)
1250            }
1251            Change::NewInstance(p, place, group) => {
1252                let mut args = json!({ "panel": p, "instance": "new", "place": place.as_str() });
1253                if let Some(g) = group {
1254                    args["group"] = json!(g);
1255                }
1256                (STEP_SHOW, args)
1257            }
1258            Change::Hide(p) => (STEP_HIDE, json!({ "panel": p })),
1259            Change::Focus(p) => (STEP_FOCUS, json!({ "panel": p })),
1260            Change::Fold(a, f) => (STEP_FOLD, json!({ "area": area_name(*a), "folded": f })),
1261            Change::FoldWindow(w, a, f) => (
1262                STEP_FOLD,
1263                json!({ "window": w, "area": area_name(*a), "folded": f }),
1264            ),
1265            Change::Place(a, p) => (
1266                STEP_PLACE,
1267                json!({ "area": area_name(*a), "placement": p.as_str() }),
1268            ),
1269            Change::Detach(p) => (STEP_DETACH, json!({ "panel": p })),
1270            Change::Attach(p) => (STEP_ATTACH, json!({ "panel": p })),
1271            Change::CloseWindow(p) => (STEP_CLOSE_WINDOW, json!({ "panel": p })),
1272            Change::JoinWindow(p, w) => (STEP_JOIN_WINDOW, json!({ "panel": p, "window": w })),
1273            Change::DetachGroup(p) => (STEP_DETACH, json!({ "panel": p, "group": true })),
1274            Change::JoinWindowGroup(p, w) => (
1275                STEP_JOIN_WINDOW,
1276                json!({ "panel": p, "window": w, "group": true }),
1277            ),
1278            Change::JoinGroup(p, g) => (STEP_JOIN_GROUP, json!({ "panel": p, "group": g })),
1279            Change::DockBack(p) => (STEP_DOCK_BACK, json!({ "panel": p })),
1280            Change::OpenPalette(p) => (crate::palettes::STEP_OPEN, json!({ "panel": p })),
1281            Change::Float(p, pos) => (
1282                crate::palettes::STEP_FLOAT,
1283                json!({ "panel": p, "pos": pos }),
1284            ),
1285            Change::FloatGroup(p, pos) => (
1286                crate::palettes::STEP_FLOAT,
1287                json!({ "panel": p, "pos": pos, "group": true }),
1288            ),
1289            Change::Dock(p, a) => (
1290                crate::palettes::STEP_DOCK,
1291                json!({ "panel": p, "area": area_name(*a) }),
1292            ),
1293            Change::DockGroup(p, a) => (
1294                crate::palettes::STEP_DOCK,
1295                json!({ "panel": p, "area": area_name(*a), "group": true }),
1296            ),
1297            Change::Group(panels, into, at) => (
1298                crate::palettes::STEP_GROUP,
1299                json!({ "panels": panels, "into": into, "at": at.as_str() }),
1300            ),
1301            Change::Ungroup(p, pos) => (
1302                crate::palettes::STEP_UNGROUP,
1303                json!({ "panel": p, "pos": pos }),
1304            ),
1305            Change::UngroupTabs(p, pos) => (
1306                crate::palettes::STEP_UNGROUP,
1307                json!({ "panel": p, "pos": pos, "tabs": true }),
1308            ),
1309            Change::CloseGroup(p) => (crate::palettes::STEP_CLOSE_GROUP, json!({ "panel": p })),
1310            Change::MovePalette(p, pos) => (
1311                crate::palettes::STEP_MOVE,
1312                json!({ "panel": p, "pos": pos }),
1313            ),
1314            Change::ResizePalette(p, size) => (
1315                crate::palettes::STEP_RESIZE,
1316                json!({ "panel": p, "size": size }),
1317            ),
1318            Change::ResizePaletteAt(p, size, pos) => (
1319                crate::palettes::STEP_RESIZE,
1320                json!({ "panel": p, "size": size, "pos": pos }),
1321            ),
1322            Change::Roll(p, on) => (
1323                crate::palettes::STEP_ROLL,
1324                json!({ "panel": p, "rolled": on }),
1325            ),
1326            Change::Pin(p, on) => (
1327                crate::palettes::STEP_PIN,
1328                json!({ "panel": p, "pinned": on }),
1329            ),
1330            Change::Zen(on) => (STEP_ZEN, json!({ "zen": on })),
1331            Change::Arrange(p, how) => {
1332                let mut args = json!({ "panel": p, "as": how.as_str() });
1333                if let Arrangement::Grid(Some(n)) = how {
1334                    args["columns"] = json!(n);
1335                }
1336                (STEP_ARRANGE, args)
1337            }
1338            Change::Flyout(p, open) => (STEP_FLYOUT, json!({ "panel": p, "open": open })),
1339            Change::FlyoutSize(p, width) => {
1340                (STEP_FLYOUT_SIZE, json!({ "panel": p, "width": width }))
1341            }
1342        }
1343    }
1344
1345    /// The event a palette's change publishes once done.
1346    pub(crate) fn event(&self) -> Option<&'static str> {
1347        Some(match self {
1348            Change::OpenPalette(_) => "palette.opened",
1349            Change::Float(..) | Change::FloatGroup(..) => "palette.floated",
1350            Change::Dock(..) | Change::DockGroup(..) => "palette.docked",
1351            Change::Group(..) => "palette.grouped",
1352            Change::Ungroup(..) | Change::UngroupTabs(..) => "palette.ungrouped",
1353            Change::CloseGroup(..) => "palette.group_closed",
1354            Change::MovePalette(..) => "palette.moved",
1355            Change::ResizePalette(..) | Change::ResizePaletteAt(..) => "palette.resized",
1356            Change::Roll(..) => "palette.rolled",
1357            Change::Pin(..) => "palette.pinned",
1358            _ => return None,
1359        })
1360    }
1361
1362    /// The change a step's (possibly redirected) arguments ask for.
1363    pub(crate) fn from_args(step: &StepId, args: &Json) -> Result<Change, String> {
1364        if *step == STEP_ZEN {
1365            return Ok(Change::Zen(
1366                args.get("zen").and_then(Json::as_bool).unwrap_or(true),
1367            ));
1368        }
1369        if *step == STEP_FOLD {
1370            let name = args
1371                .get("area")
1372                .and_then(Json::as_str)
1373                .ok_or("`area` is missing")?;
1374            let area = area_from(name).ok_or_else(|| format!("no area `{name}`"))?;
1375            let folded = args.get("folded").and_then(Json::as_bool).unwrap_or(true);
1376            let window = args.get("window").and_then(Json::as_str);
1377            if let Some(window) = window.filter(|w| *w != crate::windows::WindowId::MAIN) {
1378                return Ok(Change::FoldWindow(window.to_string(), area, folded));
1379            }
1380            return Ok(Change::Fold(area, folded));
1381        }
1382        if *step == STEP_PLACE {
1383            let name = args
1384                .get("area")
1385                .and_then(Json::as_str)
1386                .ok_or("`area` is missing")?;
1387            let area = area_from(name).ok_or_else(|| format!("no area `{name}`"))?;
1388            let name = args
1389                .get("placement")
1390                .and_then(Json::as_str)
1391                .ok_or("`placement` is missing")?;
1392            let placement = Placement::parse(name)
1393                .ok_or_else(|| format!("no placement `{name}` (`beside` or `over`)"))?;
1394            return Ok(Change::Place(area, placement));
1395        }
1396        if *step == crate::palettes::STEP_GROUP {
1397            let panels = args
1398                .get("panels")
1399                .and_then(Json::as_array)
1400                .ok_or("`panels` is missing")?
1401                .iter()
1402                .map(|p| {
1403                    let p = p.as_str().ok_or("`panels` holds panel ids")?;
1404                    PanelId::new(p).map_err(|e| e.to_string())
1405                })
1406                .collect::<Result<Vec<_>, String>>()?;
1407            let into = args
1408                .get("into")
1409                .and_then(Json::as_str)
1410                .ok_or("`into` is missing")?;
1411            let into = PanelId::new(into).map_err(|e| e.to_string())?;
1412            let name = args.get("at").and_then(Json::as_str).unwrap_or("below");
1413            let at = Join::parse(name)
1414                .ok_or_else(|| format!("no place `{name}` (`above`, `below` or `tab`)"))?;
1415            return Ok(Change::Group(panels, into, at));
1416        }
1417        let panel = args
1418            .get("panel")
1419            .and_then(Json::as_str)
1420            .ok_or("`panel` is missing")?;
1421        let panel = PanelId::new(panel).map_err(|e| e.to_string())?;
1422        let flag = |key: &str| args.get(key).and_then(Json::as_bool).unwrap_or(true);
1423        // A flag that is off unless it is given.
1424        let flag_off = |key: &str| args.get(key).and_then(Json::as_bool).unwrap_or(false);
1425        Ok(match step.as_str() {
1426            "palette.open" => Change::OpenPalette(panel),
1427            "palette.float" if flag_off("group") => Change::FloatGroup(panel, pos_of(args)?),
1428            "palette.float" => Change::Float(panel, pos_of(args)?),
1429            "palette.move" => Change::MovePalette(panel, pos_of(args)?),
1430            "palette.resize" => match (size_of(args)?, args.get("pos")) {
1431                (Some(size), Some(_)) => Change::ResizePaletteAt(panel, size, pos_of(args)?),
1432                (size, _) => Change::ResizePalette(panel, size),
1433            },
1434            "palette.ungroup" if flag_off("tabs") => Change::UngroupTabs(panel, pos_of(args)?),
1435            "palette.ungroup" => Change::Ungroup(panel, pos_of(args)?),
1436            "palette.close_group" => Change::CloseGroup(panel),
1437            "palette.roll" => Change::Roll(panel, flag("rolled")),
1438            "palette.pin" => Change::Pin(panel, flag("pinned")),
1439            "workbench.flyout" => Change::Flyout(panel, flag("open")),
1440            "workbench.flyout_size" => {
1441                let width = args
1442                    .get("width")
1443                    .and_then(Json::as_f64)
1444                    .ok_or("`width` is missing")? as f32;
1445                if !(width.is_finite() && width > 0.0) {
1446                    return Err("`width` is positive".into());
1447                }
1448                Change::FlyoutSize(panel, width)
1449            }
1450            "workbench.move" | "palette.dock" => {
1451                let name = args
1452                    .get("area")
1453                    .and_then(Json::as_str)
1454                    .ok_or("`area` is missing")?;
1455                let area = area_from(name).ok_or_else(|| format!("no area `{name}`"))?;
1456                if step.as_str() == "palette.dock" {
1457                    if args.get("group").and_then(Json::as_bool) == Some(true) {
1458                        Change::DockGroup(panel, area)
1459                    } else {
1460                        Change::Dock(panel, area)
1461                    }
1462                } else {
1463                    match args.get("window").and_then(Json::as_str) {
1464                        Some(w) if w != crate::windows::WindowId::MAIN => {
1465                            Change::MoveInWindow(panel, w.to_string(), area)
1466                        }
1467                        _ => Change::Move(panel, area),
1468                    }
1469                }
1470            }
1471            "workbench.show" => {
1472                let place = match args.get("place").and_then(Json::as_str) {
1473                    Some(name) => OpenPlace::parse(name).ok_or_else(|| {
1474                        format!("no place `{name}` (`last`, `here` or an area's name)")
1475                    })?,
1476                    None => OpenPlace::Last,
1477                };
1478                let group = match args.get("group").and_then(Json::as_str) {
1479                    Some(g) => Some(PanelId::new(g).map_err(|e| e.to_string())?),
1480                    None => None,
1481                };
1482                match (args.get("instance").and_then(Json::as_str), place) {
1483                    (Some("new"), place) => Change::NewInstance(panel, place, group),
1484                    (_, OpenPlace::Last) => Change::Show(panel),
1485                    (_, place) => Change::Open(panel, place, group),
1486                }
1487            }
1488            "workbench.detach" if flag_off("group") => Change::DetachGroup(panel),
1489            "workbench.detach" => Change::Detach(panel),
1490            "workbench.attach" => Change::Attach(panel),
1491            "workbench.close_window" => Change::CloseWindow(panel),
1492            "workbench.join_window" => {
1493                let w = args
1494                    .get("window")
1495                    .and_then(Json::as_str)
1496                    .ok_or("`window` is missing")?;
1497                let window = PanelId::new(w).map_err(|e| e.to_string())?;
1498                if flag_off("group") {
1499                    Change::JoinWindowGroup(panel, window)
1500                } else {
1501                    Change::JoinWindow(panel, window)
1502                }
1503            }
1504            "workbench.hide" => Change::Hide(panel),
1505            "workbench.join_group" => {
1506                let g = args
1507                    .get("group")
1508                    .and_then(Json::as_str)
1509                    .ok_or("`group` is missing")?;
1510                Change::JoinGroup(panel, PanelId::new(g).map_err(|e| e.to_string())?)
1511            }
1512            "workbench.dock_back" => Change::DockBack(panel),
1513            "workbench.arrange" => Change::Arrange(panel, Arrangement::from_args(args)?),
1514            _ => Change::Focus(panel),
1515        })
1516    }
1517}
1518
1519/// Where the dragged tab would land, as the space asked the veto this
1520/// frame.
1521#[derive(Clone, Debug)]
1522struct Seen {
1523    panel: PanelId,
1524    /// The area (a drop on its bare target counts as on the area).
1525    area: Area,
1526    landing: Landing,
1527    refusal: Option<String>,
1528}
1529
1530/// How a dragged tab lands in a dock.
1531#[derive(Clone, Copy, Debug)]
1532enum Landing {
1533    /// Among a group's tabs, at this index.
1534    At(usize),
1535    /// After a group's tabs.
1536    End(egui_stack::NodePath),
1537    /// Beside a group: the zone of the edge.
1538    Split(DropZone),
1539    /// In an empty dock (a closed area), or on an area drawn bare (after
1540    /// its first tabs).
1541    Whole { bare: bool },
1542}
1543
1544impl Landing {
1545    fn of(destination: &egui_stack::TabDestination, bare: bool) -> Option<Landing> {
1546        use egui_stack::{TabDestination, TabInsert};
1547        Some(match destination {
1548            TabDestination::Node(_, TabInsert::Insert(index)) => Landing::At(index.0),
1549            TabDestination::Node(path, TabInsert::Append) => Landing::End(*path),
1550            TabDestination::Node(_, TabInsert::Split(split)) => Landing::Split(match split {
1551                Split::Left => DropZone::Left,
1552                Split::Right => DropZone::Right,
1553                Split::Above => DropZone::Top,
1554                Split::Below => DropZone::Bottom,
1555            }),
1556            TabDestination::EmptySurface(_) => Landing::Whole { bare },
1557            TabDestination::Window(_) => return None,
1558        })
1559    }
1560}
1561
1562/// A detached window's place as the layout keeps it: its rectangle,
1563/// maximized, full screen.
1564type WindowPlace = ([f32; 4], bool, bool);
1565
1566/// Who owns a detached window's place (#5241). The system sizes a window
1567/// once it is open: the window opens with a place (its builder, which
1568/// egui_stack makes once and gives again unchanged while the window
1569/// lives, so the backend asks nothing more of it), and a place the system
1570/// tells is followed into the layout, never asked back. Only a place the
1571/// application changes on purpose (a layout applied) is asked, once, by
1572/// explicit commands.
1573#[derive(Clone, Copy, Debug)]
1574struct WindowAsk {
1575    /// The place last asked of the system (or opened with).
1576    asked: WindowPlace,
1577    /// The place the system last told, followed into the layout.
1578    told: Option<WindowPlace>,
1579}
1580
1581/// Where a panel is in the space: an area's dock (or its bare target),
1582/// a detached window's dock, or an application window's area (the
1583/// window's id, the area).
1584#[derive(Clone, Debug, PartialEq)]
1585enum Home {
1586    Area(Area),
1587    Window(PanelId),
1588    InWindow(String, Area),
1589}
1590
1591/// The space's drag in progress, as the workbench follows it.
1592#[derive(Clone, Debug)]
1593struct Cross {
1594    /// What is dragged.
1595    dragged: Dragged,
1596    /// The viewport it began in.
1597    source: ViewportId,
1598    /// The areas and the detached windows before the drag.
1599    areas: Vec<(Area, Node)>,
1600    windows: Vec<Auxiliary>,
1601    /// The application windows' areas before the drag.
1602    in_windows: Vec<egui_pop_model::layout::WindowAreas>,
1603    /// Where each dragged panel was.
1604    homes: Vec<Home>,
1605}
1606
1607/// The workbench's state, held by the application.
1608pub(crate) struct Workbench {
1609    /// The declared panels, in declaration order (refreshed at rebuild),
1610    /// then the instances of those declared with several
1611    /// (`PanelSpec::instances`), one spec each (`Layout::instances`).
1612    pub specs: Vec<PanelSpec>,
1613    /// The declared panels alone (`specs` without the instances).
1614    declared: Vec<PanelSpec>,
1615    /// Panels showing a zone.
1616    pub zone_of: BTreeMap<PanelId, ZoneId>,
1617    pub layout: Layout,
1618    /// The places of panels no longer declared, kept for their return
1619    /// (ADR 0028), saved with the layout.
1620    pub dormant: Vec<egui_pop_model::layout::Dormant>,
1621    /// The areas as drawn, each a dock of the space (and each its bare
1622    /// target); taken out while a dock is drawn.
1623    space: Option<DockSpace<PanelId>>,
1624    /// Where each area was drawn last frame.
1625    pub rects: BTreeMap<Area, Rect>,
1626    /// Each area's first tab bar as drawn last frame (none for an area
1627    /// drawn bare).
1628    pub bars: BTreeMap<Area, TabBar>,
1629    /// The areas drawn bare this frame.
1630    bare: BTreeSet<Area>,
1631    /// The areas' rectangle.
1632    pub content: Rect,
1633    /// A tab or a tab group being dragged: what, its area, the pointer.
1634    pub(crate) dragging: Option<(Dragged, Area, Pos2)>,
1635    /// Where the dragged tab would land this frame, as the dock asked the
1636    /// veto, and where its preview was painted.
1637    landing: Option<Seen>,
1638    landing_rect: Option<Rect>,
1639    /// The drop hint drawn last frame.
1640    pub hint: Option<DropHint>,
1641    /// The detached window under a dragged tab this pass, where a drop
1642    /// moves it (the space's drop zone painted over one of its docks).
1643    pub window_drop: Option<WindowDrop>,
1644    /// The detached windows outlined this pass, where a tab dragged out of
1645    /// another window may go but no window can tell the pointer is over
1646    /// it (the space's `DockPainter::window_outline`).
1647    window_outlines: Vec<PanelId>,
1648    /// The detached windows as egui_stack's native floats, each showing
1649    /// its dock of the space (`window:<panel>`): their places, kept beside
1650    /// the shell's layout, which is built again each pass. The layout
1651    /// document (`layout.auxiliary`) stays the saved form.
1652    floats: ZoneLayout,
1653    /// The space replaced while it was taken out (the layout changed):
1654    /// the floats' state (their windows' builders, the drag in progress)
1655    /// goes on in the space projected next (`DockSpace::carry_floats_from`).
1656    retired: Option<DockSpace<PanelId>>,
1657    /// The space's drag in progress, as the last pass saw it, and the
1658    /// layout before it: a drop into or out of a detached window is the
1659    /// workbench's step, never egui_stack's move (`settle_drop`).
1660    cross: Option<Cross>,
1661    /// The last drop zone the space painted during a drag: its dock, its
1662    /// refusal, the pass.
1663    cross_landing: Option<(String, Option<String>, u64)>,
1664    /// The place of each panel's detached window when it closed: the
1665    /// panel detached again opens its window there, as it was.
1666    closed_windows: BTreeMap<PanelId, Auxiliary>,
1667    /// Who set each detached window's place: what its window opened
1668    /// with, what the application asked since and what the system told.
1669    window_asks: BTreeMap<PanelId, WindowAsk>,
1670    /// Where each floating panel was docked when it floated (its area,
1671    /// among which tabs): where Dock back puts it (`workbench.dock_back`).
1672    floated_from: BTreeMap<PanelId, egui_pop_model::layout::DormantPlace>,
1673    /// Which panels may float, as the user's setting says
1674    /// ([`SETTING_FLOAT_PANELS`]); read before each change.
1675    pub(crate) float_scope: FloatScope,
1676    /// The panel the keys obey: see [`Workbench::follow_focus`].
1677    pub focused: Option<PanelId>,
1678    /// The last panel to be `focused` that lives in the layout proper: where
1679    /// the keys go back to when a palette or a flyout lets go.
1680    settled: Option<PanelId>,
1681    /// A panel to give the widget focus to, and for how many passes it has
1682    /// waited.
1683    focus_request: Option<(PanelId, u8)>,
1684    /// The layout changed outside the space: project it again.
1685    stale: bool,
1686    /// The space taken out to draw a dock: the layout is not read back
1687    /// then.
1688    taken: usize,
1689    /// The application's named layouts (`Ctx::arrangement`): owner,
1690    /// name, layout.
1691    pub templates: Vec<(egui_pop_model::ids::OwnerId, String, Layout)>,
1692    /// A palette's band being dragged.
1693    pub palette_drag: Option<crate::palettes::PaletteDrag>,
1694    /// A palette's edge being dragged.
1695    pub palette_resize: Option<crate::palettes::PaletteResize>,
1696    /// Where each floating panel's group was drawn last frame.
1697    pub palette_rects: BTreeMap<PanelId, Rect>,
1698    /// Where each floating panel was drawn last frame, itself (in a
1699    /// group, its band and content).
1700    pub member_rects: BTreeMap<PanelId, Rect>,
1701    /// Where the dragged palettes would join a group, while dragged over
1702    /// another palette.
1703    pub group_hint: Option<crate::palettes::GroupHint>,
1704    /// Zen mode: only the centre is drawn, or only [`Self::zen_panel`].
1705    /// Not part of the layout, so never saved.
1706    pub zen: bool,
1707    /// The panel zen mode draws alone, full size, in the window holding
1708    /// it (none: the centre whole). A draw override: the layout is left
1709    /// as it is, so leaving zen mode draws it unchanged.
1710    pub zen_panel: Option<PanelId>,
1711    /// The panel shown as a flyout out of its folded side area's strip:
1712    /// the session's state, never saved.
1713    pub flyout: Option<PanelId>,
1714    /// Where the flyout was drawn last frame.
1715    pub flyout_rect: Option<Rect>,
1716    /// The panel whose flyout was held in the overlay stack last frame.
1717    flyout_held: Option<PanelId>,
1718    /// The shell's zones that hold no dock this frame (the title, top and
1719    /// status bars, the activity bar): a tab released there goes back
1720    /// where it was, with no drop preview.
1721    pub no_drop: Vec<Rect>,
1722    /// The primary (start) side bar lies on the right, the secondary on
1723    /// the left (`workbench.side_bar_position`), as of the last pass.
1724    pub flipped: bool,
1725    /// The sizes the user gave the side and bottom areas, by zone name
1726    /// (`shell_sizes`); `None` until loaded.
1727    shell_sizes: Option<BTreeMap<String, f32>>,
1728    /// Layout changes noted and not said yet (`pop.layout.changed`).
1729    pub(crate) unsaid: Option<crate::bus::layout::Unsaid>,
1730    /// The layout as said, loaded or saved last; `None` before the
1731    /// first pass.
1732    pub(crate) said: Option<egui_pop_model::layout::SavedLayout>,
1733    /// The application's bus, which the space asks its drop veto on
1734    /// (`stack.dock.drop`) and tells its changes to
1735    /// (`stack.layout.changed`).
1736    bus: Option<Arc<dyn bus_contract::Bus>>,
1737    /// Where the change being applied was asked from: its window, and the
1738    /// window the application sends the panel to (`pop.panel.home`).
1739    pub(crate) open_from: Option<window_areas::OpenFrom>,
1740    /// The application windows shown as of the change being applied, by
1741    /// id (`main` while the main window shows the shell): a panel never
1742    /// opens in another.
1743    pub(crate) open_windows: Vec<String>,
1744    /// Tabs the space moved into, out of or between the application
1745    /// windows' areas, waiting for their `workbench.move` steps
1746    /// (`settle_area_moves`).
1747    area_moves: Option<AreaMoves>,
1748}
1749
1750/// Where a docked panel is: the application window (`None` for the main
1751/// one) and the area.
1752type DockedAt = (Option<String>, Area);
1753
1754/// Tabs a drag moved into, out of or between the application windows'
1755/// areas, read back from the space and not yet through their steps; the
1756/// areas as they were before, put back when a step refuses or vetoes.
1757#[derive(Clone, Debug)]
1758struct AreaMoves {
1759    /// The main window's areas before the moves.
1760    areas: Vec<(Area, Node)>,
1761    /// The application windows' areas before the moves.
1762    windows: Vec<egui_pop_model::layout::WindowAreas>,
1763    /// Each panel moved, and where to.
1764    moved: Vec<(PanelId, DockedAt)>,
1765}
1766
1767/// Where each docked panel is, in the main window's areas and the
1768/// application windows'.
1769fn docked_places(layout: &Layout) -> HashMap<PanelId, DockedAt> {
1770    let mut out = HashMap::new();
1771    for (area, node) in &layout.areas {
1772        for p in node.panels() {
1773            out.insert(p.clone(), (None, *area));
1774        }
1775    }
1776    for w in &layout.windows {
1777        for (area, node) in &w.areas {
1778            for p in node.panels() {
1779                out.insert(p.clone(), (Some(w.window.clone()), *area));
1780            }
1781        }
1782    }
1783    out
1784}
1785
1786impl Default for Workbench {
1787    fn default() -> Self {
1788        Self {
1789            specs: Vec::new(),
1790            declared: Vec::new(),
1791            zone_of: BTreeMap::new(),
1792            layout: Layout::default(),
1793            dormant: Vec::new(),
1794            space: None,
1795            rects: BTreeMap::new(),
1796            bars: BTreeMap::new(),
1797            bare: BTreeSet::new(),
1798            content: Rect::NOTHING,
1799            dragging: None,
1800            landing: None,
1801            landing_rect: None,
1802            window_drop: None,
1803            window_outlines: Vec::new(),
1804            floats: ZoneLayout::new(Zone::leaf("windows", Content::Empty)),
1805            retired: None,
1806            cross: None,
1807            cross_landing: None,
1808            closed_windows: BTreeMap::new(),
1809            window_asks: BTreeMap::new(),
1810            floated_from: BTreeMap::new(),
1811            float_scope: FloatScope::Any,
1812            hint: None,
1813            focused: None,
1814            settled: None,
1815            focus_request: None,
1816            stale: true,
1817            taken: 0,
1818            templates: Vec::new(),
1819            palette_drag: None,
1820            palette_resize: None,
1821            palette_rects: BTreeMap::new(),
1822            member_rects: BTreeMap::new(),
1823            group_hint: None,
1824            zen: false,
1825            zen_panel: None,
1826            flyout: None,
1827            flyout_rect: None,
1828            flyout_held: None,
1829            no_drop: Vec::new(),
1830            flipped: false,
1831            shell_sizes: None,
1832            unsaid: None,
1833            said: None,
1834            bus: None,
1835            open_from: None,
1836            open_windows: Vec::new(),
1837            area_moves: None,
1838        }
1839    }
1840}
1841
1842/// A detached window's place as a window state, brought back onto the
1843/// screens (`screens`) when it is off them all.
1844pub(crate) fn repaired_place(
1845    (r, maximized, fullscreen): WindowPlace,
1846    screens: &[Rect],
1847) -> WindowState {
1848    let [x, y, w, h] = r;
1849    WindowState {
1850        position: Some(egui::pos2(x, y)),
1851        size: egui::vec2(w, h),
1852        maximized,
1853        fullscreen,
1854    }
1855    .repair(screens)
1856}
1857
1858impl Workbench {
1859    /// A detached window's place for this pass (#5241): the place the
1860    /// application changed on purpose (from, to), to ask of the system
1861    /// once. A place the system told is never asked back. Its first place
1862    /// is the one its builder opens it with (`window_host`).
1863    fn window_place(
1864        &mut self,
1865        panel: &PanelId,
1866        now: WindowPlace,
1867        screens: &[Rect],
1868    ) -> Option<(WindowState, WindowState)> {
1869        let Some(ask) = self.window_asks.get_mut(panel) else {
1870            log::debug!(
1871                target: "egui_pop::window_size",
1872                "`{panel}` opens its window at {:?} (maximized {}, full screen {}): its builder's place",
1873                now.0,
1874                now.1,
1875                now.2,
1876            );
1877            self.window_asks.insert(
1878                panel.clone(),
1879                WindowAsk {
1880                    asked: now,
1881                    told: None,
1882                },
1883            );
1884            return None;
1885        };
1886        if ask.asked == now || ask.told == Some(now) {
1887            return None;
1888        }
1889        // The application changed the place: asked, from where the
1890        // window is (as told), once.
1891        let was = ask.told.unwrap_or(ask.asked);
1892        ask.asked = now;
1893        ask.told = None;
1894        Some((repaired_place(was, screens), repaired_place(now, screens)))
1895    }
1896
1897    /// A detached window's place as the system told it, followed into the
1898    /// layout: never asked back.
1899    fn window_told(&mut self, panel: &PanelId, place: WindowPlace) {
1900        if let Some(ask) = self.window_asks.get_mut(panel) {
1901            ask.told = Some(place);
1902        }
1903    }
1904
1905    /// A detached window's place the application asked by its own
1906    /// command (a window brought back onto a screen): asked already.
1907    pub(crate) fn window_place_asked(&mut self, panel: &PanelId) {
1908        let Some(a) = self.layout.auxiliary.iter().find(|a| a.panel == *panel) else {
1909            return;
1910        };
1911        let now = (a.rect, a.maximized, a.fullscreen);
1912        if let Some(ask) = self.window_asks.get_mut(panel) {
1913            ask.asked = now;
1914            ask.told = None;
1915        }
1916    }
1917    /// A template by name (the last offered wins).
1918    pub fn template(&self, name: &str) -> Option<Layout> {
1919        self.templates
1920            .iter()
1921            .rev()
1922            .find(|t| t.1 == name)
1923            .map(|t| t.2.clone())
1924    }
1925
1926    pub fn spec(&self, id: &PanelId) -> Option<&PanelSpec> {
1927        self.specs.iter().find(|s| s.id == *id)
1928    }
1929
1930    /// An area's least, asked-for and largest size across (`0.0` and
1931    /// infinity when none is set), from the panels it holds: the largest
1932    /// least size of its panels, a least size the application set
1933    /// (`bounds`, `AppBuilder::shell_panel_min_size`) replacing the
1934    /// panel's own `PanelSpec::min_size`; the smallest largest size the
1935    /// application set; the largest `PanelSpec::default_size`. `across`
1936    /// is the window's content width, for sizes given as a share of it.
1937    /// The main window's areas and every application window's take their
1938    /// sizes from it.
1939    pub(crate) fn area_sizes(
1940        &self,
1941        panels: &[PanelId],
1942        bounds: &[(PanelId, ShellBounds)],
1943        across: f32,
1944    ) -> (f32, f32, f32) {
1945        let set = |p: &PanelId| bounds.iter().find(|(id, _)| id == p).map(|(_, b)| *b);
1946        let mut min = 0.0_f32;
1947        let mut default = 0.0_f32;
1948        for p in panels {
1949            let spec = self.spec(p);
1950            let own = spec.map_or(0.0, |s| s.min_size);
1951            min = min.max(
1952                set(p)
1953                    .and_then(|b| b.min)
1954                    .map_or(own, |m| m.resolve(across)),
1955            );
1956            default = default.max(spec.and_then(|s| s.default_size).unwrap_or(0.0));
1957        }
1958        let max = panels
1959            .iter()
1960            .filter_map(|p| set(p).and_then(|b| b.max))
1961            .map(|m| m.resolve(across))
1962            .fold(f32::INFINITY, f32::min);
1963        (min, default, max)
1964    }
1965
1966    fn panels(&self) -> Panels {
1967        let mut p = Panels::new();
1968        for s in &self.specs {
1969            let _ = p.declare(&egui_pop_model::ids::OwnerId::FRAMEWORK, s.clone());
1970        }
1971        p
1972    }
1973
1974    /// The declared panels, then a spec for each instance `layout` holds
1975    /// of a panel declared with several.
1976    fn with_instances(declared: &[PanelSpec], layout: &Layout) -> Vec<PanelSpec> {
1977        let mut specs = declared.to_vec();
1978        for i in layout.instances.iter().filter(|i| i.id.is_instance()) {
1979            let kind = i.id.kind();
1980            if let Some(spec) = declared
1981                .iter()
1982                .find(|s| s.id == kind && s.instances == Instances::Multiple)
1983            {
1984                specs.push(spec.instance_spec(&i.id, i.title.as_deref()));
1985            }
1986        }
1987        specs
1988    }
1989
1990    /// The specs again, after the layout's instances changed.
1991    fn follow_instances(&mut self) {
1992        self.specs = Self::with_instances(&self.declared, &self.layout);
1993    }
1994
1995    /// The declared panels changed (or a layout was loaded): the layout
1996    /// is repaired against them; says what it changed.
1997    pub fn refresh(&mut self, specs: Vec<PanelSpec>, screens: &[&str]) -> Vec<String> {
1998        self.read_back();
1999        self.declared = specs;
2000        self.follow_instances();
2001        let panels = self.panels();
2002        let dormant = std::mem::take(&mut self.dormant);
2003        let (saved, notes) =
2004            std::mem::take(&mut self.layout).repair_dormant(dormant, &panels, screens);
2005        self.layout = saved.layout;
2006        self.dormant = saved.dormant;
2007        self.follow_instances();
2008        self.stale = true;
2009        notes
2010    }
2011
2012    /// Puts in a layout (loaded, or an arrangement), repaired; the
2013    /// instances it holds come with it.
2014    pub fn set_layout(&mut self, layout: Layout, screens: &[&str]) -> Vec<String> {
2015        let dormant = std::mem::take(&mut self.dormant);
2016        self.specs = Self::with_instances(&self.declared, &layout);
2017        let (saved, notes) = layout.repair_dormant(dormant, &self.panels(), screens);
2018        self.layout = saved.layout;
2019        self.dormant = saved.dormant;
2020        self.follow_instances();
2021        self.stale = true;
2022        notes
2023    }
2024
2025    /// Makes a new instance of `kind` (declared with several) and opens
2026    /// it at `place`; its id.
2027    fn new_instance(
2028        &mut self,
2029        kind: &PanelId,
2030        place: OpenPlace,
2031        group: Option<&PanelId>,
2032    ) -> Result<Json, String> {
2033        let spec = self
2034            .declared
2035            .iter()
2036            .find(|s| s.id == *kind)
2037            .ok_or_else(|| format!("no panel `{kind}`"))?;
2038        if spec.instances != Instances::Multiple {
2039            return Err(format!("`{kind}` opens once: it has no new instance"));
2040        }
2041        let id = self.layout.next_instance(kind);
2042        if !id.is_instance() {
2043            return Err(format!("`{kind}` leaves no room for an instance number"));
2044        }
2045        self.layout
2046            .instances
2047            .push(egui_pop_model::layout::PanelInstance::new(id.clone()));
2048        self.follow_instances();
2049        let spec = self.spec(&id).cloned().ok_or("the instance has no spec")?;
2050        let opened = match place {
2051            // A new one has no place yet: its area (a palette floats).
2052            OpenPlace::Last => {
2053                self.reopen(&spec);
2054                self.layout.activate(&id);
2055                Ok(json!({ "panel": id, "shown": true, "place": "last" }))
2056            }
2057            place => self.open_at(&spec, place, group),
2058        };
2059        match opened {
2060            Ok(mut out) => {
2061                out["kind"] = json!(kind);
2062                out["instance"] = json!(id);
2063                self.stale = true;
2064                Ok(out)
2065            }
2066            Err(e) => {
2067                self.layout.drop_instance(&id);
2068                self.follow_instances();
2069                Err(e)
2070            }
2071        }
2072    }
2073
2074    /// Closes a panel: an instance (`<kind>#<n>`) is dropped, its payload
2075    /// with it; any other panel is hidden, its place kept.
2076    fn close(&mut self, p: &PanelId) {
2077        if p.is_instance() {
2078            self.layout.drop_instance(p);
2079            self.follow_instances();
2080        } else {
2081            self.layout.hide(p);
2082        }
2083        self.forget_focus(p);
2084    }
2085
2086    /// Keeps the place of the detached window `panel` leaves, for when
2087    /// it is detached again.
2088    fn keep_closed_window(&mut self, panel: &PanelId) {
2089        if let Some(a) = self.layout.window_of(panel) {
2090            let kept = a.clone();
2091            self.closed_windows.insert(panel.clone(), kept);
2092        }
2093    }
2094
2095    /// The layout as it stands (the space read back).
2096    pub fn layout(&mut self) -> Layout {
2097        self.read_back();
2098        self.layout.clone()
2099    }
2100
2101    /// Reads the docks' tabs and splits back into the layout: the areas'
2102    /// trees, and the order of each detached window's tabs and the one it
2103    /// shows. Not while a tab moved into or out of a detached window waits
2104    /// for its step (`settle_drop`).
2105    fn read_back(&mut self) {
2106        if self.stale || self.taken > 0 {
2107            return;
2108        }
2109        let Some(space) = &self.space else {
2110            return;
2111        };
2112        if unsettled(space, &self.layout.auxiliary) {
2113            return;
2114        }
2115        let was = docked_places(&self.layout);
2116        let (areas, windows) = (self.layout.areas.clone(), self.layout.windows.clone());
2117        self.layout.areas = from_space(space);
2118        for (window, areas) in window_areas::read_docks(space) {
2119            let now = self.layout.window_areas(&window).map(|w| &w.areas);
2120            if now.map_or(!areas.is_empty(), |now| *now != areas) {
2121                self.layout.set_window_areas(&window, areas);
2122            }
2123        }
2124        // A tab the space moved into, out of or between the application
2125        // windows' areas: its step runs once the pass is done
2126        // (`settle_area_moves`). Between the main window's areas, the
2127        // areas' own drag follows it (`track_drag`).
2128        let mut now: Vec<(PanelId, DockedAt)> = docked_places(&self.layout)
2129            .into_iter()
2130            .filter(|(p, to)| {
2131                was.get(p)
2132                    .is_some_and(|from| from != to && (from.0.is_some() || to.0.is_some()))
2133            })
2134            .collect();
2135        if !now.is_empty() {
2136            now.sort_by(|a, b| a.0.cmp(&b.0));
2137            let moves = self.area_moves.get_or_insert(AreaMoves {
2138                areas,
2139                windows,
2140                moved: Vec::new(),
2141            });
2142            for (panel, to) in now {
2143                moves.moved.retain(|(p, _)| *p != panel);
2144                moves.moved.push((panel, to));
2145            }
2146        }
2147        for a in &mut self.layout.auxiliary {
2148            if let Some((panels, active)) = window_tabs_in(space, &a.panel) {
2149                a.reorder(&panels);
2150                if let Some(p) = panels.get(active) {
2151                    a.show(p);
2152                }
2153            }
2154        }
2155    }
2156
2157    /// Makes the space show the layout, when it changed outside it. The
2158    /// floats' state of the space it replaces goes on in the new one (their
2159    /// windows, the drag in progress): the space keeps its id.
2160    pub fn project(&mut self) {
2161        if !self.stale {
2162            return;
2163        }
2164        let mut space = to_space(&self.layout);
2165        if let Some(bus) = &self.bus {
2166            space.set_bus(bus.clone(), stack_key);
2167        }
2168        if let Some(mut old) = self.space.take().or_else(|| self.retired.take()) {
2169            space.carry_floats_from(&mut old);
2170        }
2171        self.retired = None;
2172        self.space = Some(space);
2173        self.stale = false;
2174    }
2175
2176    /// Whether a panel shows (docked or detached, not closed).
2177    pub fn shows(&mut self, panel: &PanelId) -> bool {
2178        self.read_back();
2179        self.layout.shows(panel)
2180    }
2181
2182    /// Puts a closed panel back where it was when it closed
2183    /// ([`Layout::last_place`]). That place gone, it joins the current
2184    /// group (the focused panel's tabs) when its areas allow it; else, or
2185    /// with no place known, a palette floats (cascaded), any other panel
2186    /// docks in its area.
2187    fn reopen(&mut self, spec: &PanelSpec) {
2188        let last = self.layout.closed.remove(&spec.id);
2189        let had_place = last.is_some() && self.layout.hidden.contains(&spec.id);
2190        // Rule A: its last place while that window is shown, else the
2191        // window it was asked from, in its own area; never a window closed
2192        // or hidden. The application may send it elsewhere first
2193        // (`pop.panel.home`).
2194        let from = self.open_from.clone().unwrap_or_default();
2195        let main = crate::windows::WindowId::MAIN;
2196        let open = self.open_windows.clone();
2197        let shown = |w: &str| open.is_empty() || open.iter().any(|o| o == w);
2198        let last_window = last
2199            .as_ref()
2200            .map(|p| p.window().unwrap_or(main).to_string());
2201        // The area the application chose (`pop.panel.home_area`), else
2202        // its declared one.
2203        let area = from.area.unwrap_or(spec.area);
2204        if let Some(home) = from.home.as_deref().filter(|h| shown(h)) {
2205            if had_place
2206                && last_window.as_deref() == Some(home)
2207                && last.as_ref().is_some_and(|place| self.restore(spec, place))
2208            {
2209                return;
2210            }
2211            if self.place_in(spec, home, area) {
2212                return;
2213            }
2214        }
2215        if had_place
2216            && last_window.as_deref().is_some_and(shown)
2217            && last.as_ref().is_some_and(|place| self.restore(spec, place))
2218        {
2219            return;
2220        }
2221        // The window it was asked from; none named or not shown, the main
2222        // window when it shows, else the first window shown.
2223        let target = from
2224            .origin
2225            .clone()
2226            .filter(|o| shown(o))
2227            .or_else(|| shown(main).then(|| main.to_string()))
2228            .or_else(|| open.first().cloned())
2229            .unwrap_or_else(|| main.to_string());
2230        if target != main && self.place_in(spec, &target, area) {
2231            return;
2232        }
2233        // An area the application chose, in the main window.
2234        if from.area.is_some() && !spec.palette && self.place_in(spec, main, area) {
2235            return;
2236        }
2237        // Its place gone, the current group; a panel that never had one
2238        // (closed when declared) goes to its area. A palette floats
2239        // rather than join a docked group.
2240        if had_place
2241            && !spec.palette
2242            && let Some(group) = self.current_group(spec)
2243            && self.layout.join_tabs(&spec.id, &group).is_ok()
2244        {
2245            return;
2246        }
2247        if spec.palette {
2248            let n = self.layout.floating.len();
2249            self.layout.float(&spec.id, FloatingGroup::cascade(n));
2250        } else {
2251            self.layout.place(&spec.id, spec.area);
2252        }
2253    }
2254
2255    /// Docks a panel in an area of a window (`main`: the main window's
2256    /// areas), its own area when its rules keep it out of that one;
2257    /// `false` when they keep it out of both.
2258    fn place_in(&mut self, spec: &PanelSpec, window: &str, area: Area) -> bool {
2259        let host = |a: Area| crate::mounts::panel_host(Place::Area(a));
2260        let area = if spec.refuses(&host(area)).is_none() {
2261            area
2262        } else if spec.refuses(&host(spec.area)).is_none() {
2263            spec.area
2264        } else {
2265            return false;
2266        };
2267        if window == crate::windows::WindowId::MAIN {
2268            self.layout.place(&spec.id, area);
2269        } else {
2270            self.layout.place_in_window(&spec.id, window, area);
2271        }
2272        true
2273    }
2274
2275    /// Puts a closed panel at the place it had; `false` when that place is
2276    /// gone (the tabs it sat with left its area, its window's screen is
2277    /// unplugged) or its rules keep it out of it now.
2278    fn restore(&mut self, spec: &PanelSpec, place: &egui_pop_model::layout::DormantPlace) -> bool {
2279        use egui_pop_model::layout::DormantPlace;
2280        let host = |p: Place| crate::mounts::panel_host(p);
2281        match place {
2282            DormantPlace::Docked { area, beside, .. } => {
2283                if spec.refuses(&host(Place::Area(*area))).is_some() {
2284                    return false;
2285                }
2286                // Alone in its area, the area is its place; else one of the
2287                // tabs it sat with must still be there.
2288                let there = beside.is_empty()
2289                    || beside.iter().any(|b| self.layout.area_of(b) == Some(*area));
2290                there && self.layout.dock_at(&spec.id, place)
2291            }
2292            DormantPlace::Floating { pos } => {
2293                if spec.refuses(&host(Place::Floating)).is_some() {
2294                    return false;
2295                }
2296                self.layout.float(&spec.id, *pos);
2297                true
2298            }
2299            DormantPlace::Window { screen, rect } => {
2300                // Unnamed, or no screen told: kept on the screen there is.
2301                let screens = crate::window::screen_list();
2302                let plugged = screen == crate::window::UNNAMED_SCREEN
2303                    || screens.is_empty()
2304                    || screens
2305                        .iter()
2306                        .any(|s| s.name.as_deref() == Some(screen.as_str()));
2307                if !plugged || spec.refuses(&host(Place::Window)).is_some() {
2308                    return false;
2309                }
2310                self.layout.remove(&spec.id);
2311                self.layout.hidden.retain(|h| *h != spec.id);
2312                self.layout
2313                    .auxiliary
2314                    .push(egui_pop_model::layout::Auxiliary::window(
2315                        spec.id.clone(),
2316                        screen,
2317                        *rect,
2318                    ));
2319                true
2320            }
2321            DormantPlace::InWindow { area, .. } => {
2322                if spec.refuses(&host(Place::Area(*area))).is_some() {
2323                    return false;
2324                }
2325                self.layout.dock_at(&spec.id, place)
2326            }
2327            DormantPlace::Hidden => false,
2328        }
2329    }
2330
2331    /// The current group a panel may open into: the focused panel, when
2332    /// it is docked in an area the panel's rules allow (and is not the
2333    /// panel itself).
2334    fn current_group(&self, spec: &PanelSpec) -> Option<PanelId> {
2335        let focused = self.focused.clone().filter(|f| *f != spec.id)?;
2336        let area = self.layout.area_of(&focused)?;
2337        spec.refuses(&crate::mounts::panel_host(Place::Area(area)))
2338            .is_none()
2339            .then_some(focused)
2340    }
2341
2342    /// Opens a panel here (the tab group holding `group`, else the
2343    /// focused panel's: docked, floating or detached) or in an area,
2344    /// taken out of where it is when open elsewhere.
2345    fn open_at(
2346        &mut self,
2347        spec: &PanelSpec,
2348        place: OpenPlace,
2349        group: Option<&PanelId>,
2350    ) -> Result<Json, String> {
2351        let p = &spec.id;
2352        let host = |pl: Place| crate::mounts::panel_host(pl);
2353        let area = match place {
2354            OpenPlace::Last => {
2355                if !self.layout.shows(p) {
2356                    self.reopen(spec);
2357                }
2358                self.layout.activate(p);
2359                return Ok(json!({ "panel": p, "shown": true, "place": "last" }));
2360            }
2361            OpenPlace::Area(area) => area,
2362            OpenPlace::Here => {
2363                let group = group
2364                    .cloned()
2365                    .or_else(|| self.focused.clone())
2366                    .ok_or("no tab group to open it in: name one (`group`)")?;
2367                if group == *p {
2368                    self.layout.activate(p);
2369                    return Ok(json!({ "panel": p, "shown": true, "place": "here" }));
2370                }
2371                if let Some(area) = self.layout.area_of(&group) {
2372                    if let Some(why) = spec.refuses(&host(Place::Area(area))) {
2373                        return Err(why);
2374                    }
2375                    if self.layout.window_of(p).is_some() {
2376                        self.keep_closed_window(p);
2377                    }
2378                    self.layout.join_tabs(p, &group)?;
2379                } else if self.layout.window_of(&group).is_some() {
2380                    if let Some(why) = spec.refuses(&host(Place::Window)) {
2381                        return Err(why);
2382                    }
2383                    self.layout.join_window(p, &group)?;
2384                } else if let Some(g) = self.layout.floating_of(&group) {
2385                    if let Some(why) = spec.refuses(&host(Place::Floating)) {
2386                        return Err(why);
2387                    }
2388                    let pos = g.pos;
2389                    if self.layout.floating_of(p).is_none() {
2390                        self.layout.float(p, pos);
2391                    }
2392                    self.layout
2393                        .group(std::slice::from_ref(p), &group, Join::Tab)?;
2394                    if let Some(g) = self.layout.floating_mut(p) {
2395                        g.show(p);
2396                    }
2397                } else if let Some((window, area)) = self
2398                    .layout
2399                    .window_place(&group)
2400                    .map(|(w, a)| (w.to_string(), a))
2401                {
2402                    // In an application window's area: its tabs there.
2403                    if let Some(why) = spec.refuses(&host(Place::Area(area))) {
2404                        return Err(why);
2405                    }
2406                    let beside = [group.clone()];
2407                    let place = egui_pop_model::layout::DormantPlace::InWindow {
2408                        window,
2409                        area,
2410                        beside: beside.to_vec(),
2411                        index: usize::MAX,
2412                    };
2413                    self.layout.dock_at(p, &place);
2414                } else {
2415                    return Err(format!("`{group}` is not open"));
2416                }
2417                return Ok(json!({ "panel": p, "shown": true, "place": "here", "group": group }));
2418            }
2419        };
2420        if let Some(why) = spec.refuses(&host(Place::Area(area))) {
2421            return Err(why);
2422        }
2423        // Asked from an application window shown: that window's area.
2424        let main = crate::windows::WindowId::MAIN;
2425        let window = (self.open_from.as_ref())
2426            .and_then(|f| f.origin.clone())
2427            .filter(|o| o != main && self.open_windows.iter().any(|w| w == o));
2428        if let Some(window) = window {
2429            if self.layout.window_place(p) != Some((window.as_str(), area)) {
2430                self.layout.place_in_window(p, &window, area);
2431            }
2432            self.layout.activate(p);
2433            return Ok(
2434                json!({ "panel": p, "shown": true, "area": area_name(area), "window": window }),
2435            );
2436        }
2437        if self.layout.area_of(p) != Some(area) {
2438            if self.layout.window_of(p).is_some() {
2439                self.keep_closed_window(p);
2440            }
2441            self.layout.place(p, area);
2442        }
2443        self.layout.activate(p);
2444        Ok(json!({ "panel": p, "shown": true, "area": area_name(area) }))
2445    }
2446
2447    /// Why a panel may not float, if it may not: its spec refuses it
2448    /// ([`PanelSpec::floatable`], its content), or the user's setting
2449    /// lets only palettes float ([`SETTING_FLOAT_PANELS`]).
2450    pub fn float_refusal(&self, spec: &PanelSpec) -> Option<String> {
2451        spec.refuses(&crate::mounts::panel_host(Place::Floating))
2452            .or_else(|| {
2453                (!self.float_scope.allows(spec))
2454                    .then(|| format!("{} cannot float: only palettes float", spec.title))
2455            })
2456    }
2457
2458    /// Docks back a floating group of tabs that floated whole from one
2459    /// area ([`Change::FloatGroup`]): every tab where it was, in order,
2460    /// its shown tab shown. `None`: the panel does not float in such a
2461    /// group (it docks back alone).
2462    fn dock_back_tabs(&mut self, p: &PanelId) -> Option<Json> {
2463        use egui_pop_model::layout::{Arrangement as Tabs, DormantPlace};
2464        let g = self.layout.floating_of(p)?;
2465        if g.arrangement != Tabs::Tabs || g.is_lone() {
2466            return None;
2467        }
2468        let panels: Vec<PanelId> = g.panels().cloned().collect();
2469        let shown = g.shown().clone();
2470        let area = match self.floated_from.get(&panels[0]) {
2471            Some(DormantPlace::Docked { area, .. }) => *area,
2472            _ => return None,
2473        };
2474        let same = panels.iter().all(|q| {
2475            matches!(self.floated_from.get(q), Some(DormantPlace::Docked { area: a, .. }) if *a == area)
2476                && self.spec(q).is_some_and(|s| {
2477                    s.refuses(&crate::mounts::panel_host(Place::Area(area)))
2478                        .is_none()
2479                })
2480        });
2481        if !same {
2482            return None;
2483        }
2484        let first = self.floated_from.remove(&panels[0])?;
2485        self.layout.dock_at(&panels[0], &first);
2486        for q in &panels[1..] {
2487            self.floated_from.remove(q);
2488            if self.layout.join_tabs(q, &panels[0]).is_err() {
2489                self.layout.place(q, area);
2490            }
2491        }
2492        self.layout.activate(&shown);
2493        Some(json!({ "panel": p, "area": area_name(area), "panels": panels }))
2494    }
2495
2496    /// Applies a change; refused when the panel's rules do not allow it.
2497    /// Anchors a floating panel to the workbench edges its new place lies
2498    /// on (`palettes::anchor_of`), or to none: dropped against an edge,
2499    /// it sticks to it; dropped away, it no longer does.
2500    /// `alone`: it just came out of its group, its size is its own. A
2501    /// group resized (`size`) is anchored with its new size.
2502    fn anchor_palette(&mut self, p: &PanelId, alone: bool) {
2503        let rects = if alone {
2504            &self.member_rects
2505        } else {
2506            &self.palette_rects
2507        };
2508        let resized = (!alone)
2509            .then(|| self.layout.floating_of(p).and_then(|g| g.size))
2510            .flatten();
2511        let size = resized
2512            .map(egui::Vec2::from)
2513            .unwrap_or_else(|| rects.get(p).map_or(egui::Vec2::ZERO, |r| r.size()));
2514        let content = self.content;
2515        if let Some(f) = self.layout.floating_mut(p) {
2516            f.anchor = if content.is_positive() {
2517                let rect = Rect::from_min_size(content.min + egui::Vec2::from(f.pos), size);
2518                crate::palettes::anchor_of(rect, content)
2519            } else {
2520                Default::default()
2521            };
2522        }
2523    }
2524
2525    /// Whether a panel only borrows the keys: it floats above the layout, or
2526    /// opens over the centre from a folded area. A press in it leaves them
2527    /// where they are, and they go back when it lets go.
2528    fn borrows_keys(&self, panel: &PanelId) -> bool {
2529        self.layout.floating_of(panel).is_some()
2530            || self
2531                .layout
2532                .area_of(panel)
2533                .is_some_and(|a| self.layout.folded.contains(&a))
2534    }
2535
2536    fn set_focused(&mut self, panel: &PanelId) {
2537        if !self.borrows_keys(panel) {
2538            self.settled = Some(panel.clone());
2539        }
2540        self.focused = Some(panel.clone());
2541    }
2542
2543    /// A panel goes away: a panel only borrowing the keys gives them back.
2544    fn forget_focus(&mut self, panel: &PanelId) {
2545        if self.settled.as_ref() == Some(panel) {
2546            self.settled = None;
2547        }
2548        if self.focused.as_ref() == Some(panel) {
2549            self.focused = self.settled.clone();
2550        }
2551        if self.focus_request.as_ref().is_some_and(|(p, _)| p == panel) {
2552            self.focus_request = None;
2553        }
2554    }
2555
2556    /// The panel drawn in these scopes (the innermost, should one be drawn
2557    /// inside another).
2558    pub(crate) fn panel_of(&self, chain: &[focus::ScopeRecord]) -> Option<PanelId> {
2559        chain.iter().rev().find_map(|r| {
2560            let spec = self
2561                .specs
2562                .iter()
2563                .find(|s| crate::app::scope_name(s.id.as_str()) == r.name)?;
2564            Some(spec.id.clone())
2565        })
2566    }
2567
2568    /// Follows the widget focus and the pointer: see
2569    /// [the focused panel](self#the-focused-panel). Whether `focused` changed.
2570    pub(crate) fn follow_focus(&mut self, moved: focus::Moved) -> bool {
2571        let before = self.focused.clone();
2572        match moved {
2573            focus::Moved::Pressed(chain) => {
2574                if let Some(p) = self.panel_of(&chain).filter(|p| !self.borrows_keys(p)) {
2575                    self.set_focused(&p);
2576                }
2577            }
2578            focus::Moved::Focused(chain) => {
2579                if let Some(p) = self.panel_of(&chain) {
2580                    self.set_focused(&p);
2581                }
2582            }
2583            focus::Moved::Left => {
2584                if self.focused.as_ref().is_some_and(|p| self.borrows_keys(p)) {
2585                    self.focused = self.settled.clone();
2586                }
2587            }
2588        }
2589        // A flyout closed without the focus going anywhere.
2590        if let Some(p) = &self.focused
2591            && self.borrows_keys(p)
2592            && self.layout.floating_of(p).is_none()
2593            && self.flyout.as_ref() != Some(p)
2594        {
2595            self.focused = self.settled.clone();
2596        }
2597        before != self.focused
2598    }
2599
2600    /// One more pass for a panel to take the widget focus. A panel that was
2601    /// not drawn in this time (a hidden zone, a rolled palette) is left with
2602    /// the logical focus: nothing steals the keyboard long after the command.
2603    pub(crate) fn age_focus_request(&mut self) {
2604        const PASSES: u8 = 4;
2605        if let Some((_, age)) = &mut self.focus_request {
2606            *age += 1;
2607            if *age > PASSES {
2608                self.focus_request = None;
2609            }
2610        }
2611    }
2612
2613    /// The panel asked for keeps the logical focus only.
2614    pub(crate) fn cancel_focus_request(&mut self) {
2615        self.focus_request = None;
2616    }
2617
2618    /// Takes the request to give a panel the widget focus, if it is this
2619    /// panel's and a pass old: the input of the pass that asked (the key
2620    /// bound to the command, an Enter on a button) is not read by the widget
2621    /// that gets the focus.
2622    pub(crate) fn take_focus_request(&mut self, panel: &PanelId) -> bool {
2623        let ripe = matches!(&self.focus_request, Some((p, age)) if p == panel && *age > 0);
2624        if ripe {
2625            self.focus_request = None;
2626        }
2627        ripe
2628    }
2629
2630    /// Zen mode on, `panel` alone (none: the centre whole), or off: the
2631    /// session's state, the layout left as it is. The result names the
2632    /// panel and the window drawing it (`main`, or `panel:<window>` for a
2633    /// detached one).
2634    pub(crate) fn apply_zen(&mut self, on: bool, panel: Option<PanelId>) -> Result<Json, String> {
2635        if let Some(p) = panel.as_ref().filter(|_| on) {
2636            if self.spec(p).is_none() && !p.is_instance() {
2637                return Err(format!("no panel `{p}`"));
2638            }
2639            if !self.layout.shows(p) {
2640                return Err(format!("`{p}` is not open: zen mode shows an open panel"));
2641            }
2642        }
2643        self.zen = on;
2644        self.zen_panel = if on { panel } else { None };
2645        let window = self.zen_panel.as_ref().map(|p| self.zen_window(p));
2646        Ok(json!({ "zen": on, "panel": self.zen_panel, "window": window }))
2647    }
2648
2649    /// The window drawing a panel zen mode shows: `main`, or
2650    /// `panel:<window>` for a detached window (as the bus names it).
2651    fn zen_window(&self, panel: &PanelId) -> String {
2652        if let Some((window, _)) = self.layout.window_place(panel) {
2653            return window.to_owned();
2654        }
2655        match self.layout.window_of(panel) {
2656            Some(aux) => format!("panel:{}", aux.panel),
2657            None => "main".to_owned(),
2658        }
2659    }
2660
2661    /// The panel zen mode draws alone in the application window `window`
2662    /// (by its id), if any: one of its areas' panels, open.
2663    pub(crate) fn zen_in_app_window(&self, window: &str) -> Option<PanelId> {
2664        let panel = self.zen_panel.as_ref().filter(|_| self.zen)?;
2665        let (w, _) = self.layout.window_place(panel)?;
2666        (w == window).then(|| panel.clone())
2667    }
2668
2669    /// Whether zen mode changes what the main window draws: on, for the
2670    /// centre or a panel of the main window (a detached window's panel
2671    /// leaves the main window as it is).
2672    pub(crate) fn main_zen(&self) -> bool {
2673        self.zen
2674            && self.zen_panel.as_ref().is_none_or(|p| {
2675                self.layout.window_of(p).is_none() && self.layout.window_place(p).is_none()
2676            })
2677    }
2678
2679    /// The panel zen mode draws alone in the detached window `window`
2680    /// (by its panel), if any.
2681    pub(crate) fn zen_in_window(&self, window: &PanelId) -> Option<PanelId> {
2682        let panel = self.zen_panel.as_ref().filter(|_| self.zen)?;
2683        let aux = self.layout.window_of(panel)?;
2684        (aux.panel == *window && self.layout.shows(panel)).then(|| panel.clone())
2685    }
2686
2687    /// The panel zen mode draws alone in the main window, if any (open,
2688    /// and not in a detached window).
2689    pub(crate) fn zen_in_main(&self) -> Option<PanelId> {
2690        let panel = self.zen_panel.as_ref().filter(|_| self.main_zen())?;
2691        self.layout.shows(panel).then(|| panel.clone())
2692    }
2693
2694    pub fn apply(&mut self, change: &Change) -> Result<Json, String> {
2695        self.read_back();
2696        let spec_of = |p: &PanelId| {
2697            self.spec(p)
2698                .cloned()
2699                .ok_or_else(|| format!("no panel `{p}`"))
2700        };
2701        let out = match change {
2702            Change::Move(p, area) | Change::Dock(p, area) => {
2703                let spec = spec_of(p)?;
2704                if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Area(*area))) {
2705                    return Err(why);
2706                }
2707                // Already there (a tab a drag dropped there): kept where
2708                // it was dropped.
2709                if self.layout.area_of(p) != Some(*area) {
2710                    // Out of a detached window: its place kept, for when
2711                    // it is detached again.
2712                    if self.layout.window_of(p).is_some() {
2713                        self.keep_closed_window(p);
2714                    }
2715                    self.layout.place(p, *area);
2716                }
2717                json!({ "panel": p, "area": area_name(*area) })
2718            }
2719            Change::MoveInWindow(p, window, area) => {
2720                let spec = spec_of(p)?;
2721                if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Area(*area))) {
2722                    return Err(why);
2723                }
2724                // Already there (a tab a drag dropped there): kept where
2725                // it was dropped.
2726                if self.layout.window_place(p) != Some((window.as_str(), *area)) {
2727                    if self.layout.window_of(p).is_some() {
2728                        self.keep_closed_window(p);
2729                    }
2730                    self.layout.place_in_window(p, window, *area);
2731                }
2732                json!({ "panel": p, "window": window, "area": area_name(*area) })
2733            }
2734            Change::Show(p) => {
2735                let spec = spec_of(p)?;
2736                if !self.layout.shows(p) {
2737                    self.reopen(&spec);
2738                }
2739                self.layout.activate(p);
2740                json!({ "panel": p, "shown": true })
2741            }
2742            Change::Open(p, place, group) => {
2743                let spec = spec_of(p)?;
2744                self.open_at(&spec, *place, group.as_ref())?
2745            }
2746            Change::NewInstance(kind, place, group) => {
2747                self.new_instance(kind, *place, group.as_ref())?
2748            }
2749            Change::Hide(p) => {
2750                spec_of(p)?;
2751                self.close(p);
2752                json!({ "panel": p, "shown": false })
2753            }
2754            Change::Focus(p) => {
2755                let spec = spec_of(p)?;
2756                if !self.layout.shows(p) {
2757                    self.reopen(&spec);
2758                }
2759                self.layout.activate(p);
2760                let area = self.layout.area_of(p);
2761                self.layout.folded.retain(|a| Some(*a) != area);
2762                self.set_focused(p);
2763                self.focus_request = Some((p.clone(), 0));
2764                json!({ "panel": p, "focused": true })
2765            }
2766            Change::Detach(p) => {
2767                let spec = spec_of(p)?;
2768                if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Window)) {
2769                    return Err(why);
2770                }
2771                let window = self.layout.window_of(p);
2772                if window.is_some_and(|a| a.tabs.is_empty()) {
2773                    return Ok(json!({ "panel": p, "detached": true }));
2774                }
2775                // A tab of a window gets a window of its own beside it.
2776                let beside = window.map(|a| {
2777                    let [x, y, w, h] = a.rect;
2778                    [x + 40.0, y + 40.0, w, h]
2779                });
2780                // Where it was drawn, in the window's coordinates.
2781                let rect = beside.unwrap_or_else(|| {
2782                    self.layout
2783                        .area_of(p)
2784                        .and_then(|a| self.rects.get(&a))
2785                        .map_or(DETACHED, |r| {
2786                            [
2787                                r.min.x + 40.0,
2788                                r.min.y + 40.0,
2789                                r.width().max(320.0),
2790                                r.height().max(240.0),
2791                            ]
2792                        })
2793                });
2794                self.layout.remove(p);
2795                self.layout.hidden.retain(|h| h != p);
2796                // Its window closed earlier: where and as it was.
2797                let mut window = egui_pop_model::layout::Auxiliary::window(
2798                    p.clone(),
2799                    crate::window::UNNAMED_SCREEN,
2800                    rect,
2801                );
2802                if beside.is_none()
2803                    && let Some(closed) = self.closed_windows.get(p)
2804                {
2805                    window.screen.clone_from(&closed.screen);
2806                    window.rect = closed.rect;
2807                    window.maximized = closed.maximized;
2808                    window.fullscreen = closed.fullscreen;
2809                }
2810                self.layout.auxiliary.push(window);
2811                json!({ "panel": p, "detached": true })
2812            }
2813            Change::Attach(p) => {
2814                let spec = spec_of(p)?;
2815                self.keep_closed_window(p);
2816                self.layout.place(p, spec.area);
2817                json!({ "panel": p, "detached": false })
2818            }
2819            Change::CloseWindow(p) => {
2820                // Every panel of the window docks back.
2821                let panels: Vec<PanelId> = self
2822                    .layout
2823                    .window_of(p)
2824                    .map_or_else(|| vec![p.clone()], |a| a.panels().cloned().collect());
2825                spec_of(p)?;
2826                let homes: Vec<(PanelId, Area)> = (panels.iter())
2827                    .filter_map(|q| spec_of(q).ok().map(|s| (q.clone(), s.area)))
2828                    .collect();
2829                for q in &panels {
2830                    self.keep_closed_window(q);
2831                }
2832                for (q, area) in &homes {
2833                    self.layout.place(q, *area);
2834                }
2835                json!({ "panel": p, "detached": false, "docked": panels })
2836            }
2837            Change::JoinWindow(p, window) => {
2838                let spec = spec_of(p)?;
2839                if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Window)) {
2840                    return Err(why);
2841                }
2842                self.layout.join_window(p, window)?;
2843                let named = self.layout.window_of(p).map(|a| a.panel.clone());
2844                json!({ "panel": p, "window": named, "detached": true })
2845            }
2846            Change::DetachGroup(p) | Change::JoinWindowGroup(p, _) => {
2847                let (panels, _) = self
2848                    .layout
2849                    .group_of(p)
2850                    .ok_or_else(|| format!("`{p}` is in no tab group"))?;
2851                // The group moves whole, or not at all.
2852                for q in &panels {
2853                    let spec = spec_of(q)?;
2854                    if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Window)) {
2855                        return Err(why);
2856                    }
2857                }
2858                if let Change::JoinWindowGroup(_, window) = change {
2859                    self.layout.join_window_group(p, window)?;
2860                } else {
2861                    // Where the group was drawn, a little in.
2862                    let rect = self
2863                        .layout
2864                        .area_of(p)
2865                        .and_then(|a| self.rects.get(&a))
2866                        .map_or(DETACHED, |r| {
2867                            [
2868                                r.min.x + 40.0,
2869                                r.min.y + 40.0,
2870                                r.width().max(320.0),
2871                                r.height().max(240.0),
2872                            ]
2873                        });
2874                    self.layout
2875                        .detach_group(p, crate::window::UNNAMED_SCREEN, rect)?;
2876                }
2877                let named = self.layout.window_of(p).map(|a| a.panel.clone());
2878                json!({ "panel": p, "panels": panels, "window": named, "detached": true })
2879            }
2880            Change::OpenPalette(p) => {
2881                let spec = spec_of(p)?;
2882                if !self.layout.shows(p) {
2883                    if self.layout.last_place(p).is_some() {
2884                        // Back where it was, floating or not.
2885                        self.reopen(&spec);
2886                    } else if self.float_refusal(&spec).is_none() {
2887                        let n = self.layout.floating.len();
2888                        self.layout.float(p, FloatingGroup::cascade(n));
2889                    } else {
2890                        self.reopen(&spec);
2891                    }
2892                }
2893                self.layout.activate(p);
2894                let floating = self.layout.floating_of(p).is_some();
2895                json!({ "panel": p, "shown": true, "floating": floating })
2896            }
2897            Change::Float(p, pos) => {
2898                let spec = spec_of(p)?;
2899                if let Some(why) = self.float_refusal(&spec) {
2900                    return Err(why);
2901                }
2902                // Docked until now: where Dock back puts it.
2903                match self.layout.docked_place(p) {
2904                    Some(place) => {
2905                        self.floated_from.insert(p.clone(), place);
2906                    }
2907                    None if self.layout.floating_of(p).is_none() => {
2908                        self.floated_from.remove(p);
2909                    }
2910                    None => {}
2911                }
2912                self.layout.float(p, *pos);
2913                self.anchor_palette(p, false);
2914                json!({ "panel": p, "pos": pos })
2915            }
2916            Change::FloatGroup(p, pos) => {
2917                let (panels, _) = self
2918                    .layout
2919                    .group_of(p)
2920                    .filter(|_| self.layout.area_of(p).is_some())
2921                    .ok_or_else(|| format!("`{p}` is not docked in a tab group"))?;
2922                // The group floats whole, or not at all.
2923                for q in &panels {
2924                    if let Some(why) = self.float_refusal(&spec_of(q)?) {
2925                        return Err(why);
2926                    }
2927                }
2928                // Where Dock back puts each one.
2929                for q in &panels {
2930                    match self.layout.docked_place(q) {
2931                        Some(place) => self.floated_from.insert(q.clone(), place),
2932                        None => self.floated_from.remove(q),
2933                    };
2934                }
2935                let floated = self.layout.float_tabs(p, *pos)?;
2936                self.anchor_palette(p, false);
2937                json!({ "panel": p, "pos": pos, "group": true, "panels": floated })
2938            }
2939            Change::JoinGroup(p, into) => {
2940                let spec = spec_of(p)?;
2941                let area = self
2942                    .layout
2943                    .area_of(into)
2944                    .ok_or_else(|| format!("`{into}` is not docked"))?;
2945                if let Some(why) = spec.refuses(&crate::mounts::panel_host(Place::Area(area))) {
2946                    return Err(why);
2947                }
2948                if self.layout.window_of(p).is_some() {
2949                    self.keep_closed_window(p);
2950                }
2951                self.layout.join_tabs(p, into)?;
2952                json!({ "panel": p, "group": into, "area": area_name(area) })
2953            }
2954            Change::DockBack(p) => {
2955                let spec = spec_of(p)?;
2956                if self.layout.floating_of(p).is_none() && self.layout.window_of(p).is_none() {
2957                    return Err(format!("{} is docked", spec.title));
2958                }
2959                if self.layout.window_of(p).is_some() {
2960                    self.keep_closed_window(p);
2961                }
2962                // A group of tabs floated whole goes back whole.
2963                match self.dock_back_tabs(p) {
2964                    Some(out) => out,
2965                    None => {
2966                        let place = self.floated_from.remove(p).filter(|place| match place {
2967                            egui_pop_model::layout::DormantPlace::Docked { area, .. } => spec
2968                                .refuses(&crate::mounts::panel_host(Place::Area(*area)))
2969                                .is_none(),
2970                            _ => false,
2971                        });
2972                        let area = match &place {
2973                            Some(place) => {
2974                                self.layout.dock_at(p, place);
2975                                self.layout.area_of(p).unwrap_or(spec.area)
2976                            }
2977                            None => {
2978                                self.layout.place(p, spec.area);
2979                                spec.area
2980                            }
2981                        };
2982                        json!({ "panel": p, "area": area_name(area) })
2983                    }
2984                }
2985            }
2986            Change::DockGroup(p, area) => {
2987                let panels: Vec<PanelId> = match self.layout.floating_of(p) {
2988                    Some(g) => g.panels().cloned().collect(),
2989                    None => vec![p.clone()],
2990                };
2991                let host = crate::mounts::panel_host(Place::Area(*area));
2992                for q in &panels {
2993                    if let Some(why) = spec_of(q)?.refuses(&host) {
2994                        return Err(why);
2995                    }
2996                }
2997                let docked = self.layout.dock_group(p, *area);
2998                json!({ "panel": p, "area": area_name(*area), "panels": docked })
2999            }
3000            Change::Group(panels, into, at) => {
3001                self.layout.group(panels, into, *at)?;
3002                json!({ "panels": panels, "into": into, "at": at.as_str() })
3003            }
3004            Change::Ungroup(p, pos) => {
3005                self.layout.ungroup(p, *pos)?;
3006                self.anchor_palette(p, true);
3007                json!({ "panel": p, "pos": pos })
3008            }
3009            Change::UngroupTabs(p, pos) => {
3010                self.layout.ungroup_tabs(p, *pos)?;
3011                self.anchor_palette(p, true);
3012                json!({ "panel": p, "pos": pos, "tabs": true })
3013            }
3014            Change::CloseGroup(p) => {
3015                let panels: Vec<PanelId> = self
3016                    .layout
3017                    .floating_of(p)
3018                    .ok_or_else(|| format!("`{p}` does not float"))?
3019                    .panels()
3020                    .cloned()
3021                    .collect();
3022                for q in &panels {
3023                    self.close(q);
3024                }
3025                json!({ "panel": p, "panels": panels })
3026            }
3027            Change::MovePalette(p, pos) => {
3028                let f = self
3029                    .layout
3030                    .floating_mut(p)
3031                    .ok_or_else(|| format!("`{p}` does not float"))?;
3032                f.pos = *pos;
3033                self.anchor_palette(p, false);
3034                json!({ "panel": p, "pos": pos })
3035            }
3036            Change::ResizePalette(p, size) => {
3037                let f = self
3038                    .layout
3039                    .floating_mut(p)
3040                    .ok_or_else(|| format!("`{p}` does not float"))?;
3041                f.size = *size;
3042                self.anchor_palette(p, false);
3043                json!({ "panel": p, "size": size })
3044            }
3045            Change::ResizePaletteAt(p, size, pos) => {
3046                let f = self
3047                    .layout
3048                    .floating_mut(p)
3049                    .ok_or_else(|| format!("`{p}` does not float"))?;
3050                f.size = Some(*size);
3051                f.pos = *pos;
3052                self.anchor_palette(p, false);
3053                json!({ "panel": p, "size": size, "pos": pos })
3054            }
3055            Change::Roll(p, on) => {
3056                let m = self
3057                    .layout
3058                    .floating_mut(p)
3059                    .and_then(|g| g.member_mut(p))
3060                    .ok_or_else(|| format!("`{p}` does not float"))?;
3061                m.rolled = *on;
3062                json!({ "panel": p, "rolled": on })
3063            }
3064            Change::Pin(p, on) => {
3065                let f = self
3066                    .layout
3067                    .floating_mut(p)
3068                    .ok_or_else(|| format!("`{p}` does not float"))?;
3069                f.pinned = *on;
3070                json!({ "panel": p, "pinned": on })
3071            }
3072            Change::Arrange(p, how) => {
3073                let spec = spec_of(p)?;
3074                let (area, node) = self
3075                    .layout
3076                    .areas
3077                    .iter_mut()
3078                    .find(|(_, n)| n.panels().contains(&p))
3079                    .ok_or_else(|| format!("{} is not in an area", spec.title))?;
3080                *node = arrange(node, p, *how)
3081                    .ok_or_else(|| format!("{} is alone in its area", spec.title))?;
3082                let mut out = json!({ "panel": p, "area": area_name(*area), "as": how.as_str() });
3083                if let Arrangement::Grid(columns) = how {
3084                    out["columns"] = json!(columns);
3085                }
3086                out
3087            }
3088            Change::Fold(area, folded) => {
3089                if *area == Area::Center && *folded {
3090                    return Err("the centre never folds".into());
3091                }
3092                if !folded
3093                    && self
3094                        .flyout
3095                        .as_ref()
3096                        .is_some_and(|p| self.layout.area_of(p) == Some(*area))
3097                {
3098                    self.flyout = None;
3099                }
3100                self.layout.folded.retain(|a| a != area);
3101                if *folded {
3102                    self.layout.folded.push(*area);
3103                }
3104                json!({ "area": area_name(*area), "folded": folded })
3105            }
3106            Change::FoldWindow(window, area, folded) => {
3107                if *area == Area::Center && *folded {
3108                    return Err("the centre never folds".into());
3109                }
3110                if self.layout.window_areas(window).is_none() {
3111                    return Err(format!("window `{window}` has no areas"));
3112                }
3113                if !folded
3114                    && self
3115                        .flyout
3116                        .as_ref()
3117                        .is_some_and(|p| self.layout.window_place(p) == Some((window, *area)))
3118                {
3119                    self.flyout = None;
3120                }
3121                self.layout.fold_in_window(window, *area, *folded);
3122                json!({ "window": window, "area": area_name(*area), "folded": folded })
3123            }
3124            Change::Flyout(p, open) => {
3125                let spec = spec_of(p)?;
3126                if !*open {
3127                    if self.flyout.as_ref() == Some(p) {
3128                        self.flyout = None;
3129                    }
3130                    return Ok(json!({ "panel": p, "open": false }));
3131                }
3132                // In the main window's areas, or in another window's.
3133                let (area, folded) = match self.layout.window_place(p) {
3134                    Some((window, area)) => (area, self.layout.window_folded(window, area)),
3135                    None => {
3136                        let area = self
3137                            .layout
3138                            .area_of(p)
3139                            .ok_or_else(|| format!("{} is not in an area", spec.title))?;
3140                        (area, self.layout.folded.contains(&area))
3141                    }
3142                };
3143                if !matches!(area, Area::StartSide | Area::EndSide) || !folded {
3144                    return Err(format!(
3145                        "{} is not in a folded side area: only those open as a flyout",
3146                        spec.title
3147                    ));
3148                }
3149                // The session's state: the layout is left as it is.
3150                self.flyout = Some(p.clone());
3151                return Ok(json!({ "panel": p, "open": true }));
3152            }
3153            Change::FlyoutSize(p, width) => {
3154                spec_of(p)?;
3155                self.layout.flyouts.insert(p.clone(), *width);
3156                return Ok(json!({ "panel": p, "width": width }));
3157            }
3158            Change::Zen(on) => return self.apply_zen(*on, None),
3159            Change::Place(area, placement) => {
3160                if !matches!(area, Area::StartSide | Area::EndSide) {
3161                    return Err(format!(
3162                        "only a side area may lie over the centre, not {}",
3163                        area.name()
3164                    ));
3165                }
3166                self.layout.set_placement(*area, *placement);
3167                json!({ "area": area_name(*area), "placement": placement.as_str() })
3168            }
3169        };
3170        self.stale = true;
3171        Ok(out)
3172    }
3173
3174    /// Takes the space out to draw one of its docks, projecting the
3175    /// layout first if it changed.
3176    fn take_space(&mut self) -> Option<DockSpace<PanelId>> {
3177        if self.taken == 0 {
3178            self.project();
3179        }
3180        let s = self.space.take();
3181        if s.is_some() {
3182            self.taken += 1;
3183        }
3184        s
3185    }
3186
3187    /// Puts the space back once a dock is drawn; dropped if the layout
3188    /// changed meanwhile (it is projected again).
3189    fn put_space(&mut self, space: DockSpace<PanelId>) {
3190        self.taken = self.taken.saturating_sub(1);
3191        if !self.stale {
3192            self.space = Some(space);
3193        } else {
3194            // Its floats go on in the space projected next.
3195            self.retired = Some(space);
3196        }
3197    }
3198
3199    /// The areas holding panels, in order.
3200    pub fn areas(&self) -> Vec<Area> {
3201        let mut areas: Vec<Area> = Area::ALL
3202            .into_iter()
3203            .filter(|a| !self.panels_in(*a).is_empty())
3204            .collect();
3205        areas.sort();
3206        areas
3207    }
3208
3209    /// The panels an area holds now.
3210    pub fn panels_in(&self, area: Area) -> Vec<PanelId> {
3211        self.space
3212            .as_ref()
3213            .and_then(|s| s.dock(area_name(area)))
3214            .map(|t| t.tabs().cloned().collect())
3215            .unwrap_or_default()
3216    }
3217
3218    /// The area the space holds a panel in.
3219    fn area_in_space(&self, panel: &PanelId) -> Option<Area> {
3220        let space = self.space.as_ref()?;
3221        let path = space.state().find_tab(panel)?;
3222        space
3223            .dock_name(path.surface)
3224            .and_then(dock_area)
3225            .map(|(a, _)| a)
3226    }
3227
3228    /// The detached windows outlined in the last pass (`window_outline`).
3229    pub fn window_outlines(&self) -> &[PanelId] {
3230        &self.window_outlines
3231    }
3232
3233    /// The tab, or the tab group (dragged by its tab bar), being dragged
3234    /// between the areas, as the space's docks last saw it: what, its
3235    /// area and the pointer.
3236    fn dragged(&self, ctx: &egui::Context) -> Option<(Dragged, Area, Pos2)> {
3237        let space = self.space.as_ref()?;
3238        if let Some(dragged) = DockArea::dragged_tab(ctx, space_id()) {
3239            let leaf = space.state().leaf(dragged.path.node_path()).ok()?;
3240            let panel = leaf.tabs.get(dragged.path.tab.0)?.clone();
3241            let (area, _) = space.dock_name(dragged.path.surface).and_then(dock_area)?;
3242            return Some((Dragged::Tab(panel), area, dragged.pointer));
3243        }
3244        let dragged = DockArea::dragged_node(ctx, space_id())?;
3245        let leaf = space.state().leaf(dragged.path).ok()?;
3246        let shown = leaf.tabs.get(leaf.active.0).or(leaf.tabs.first())?.clone();
3247        let (area, _) = space.dock_name(dragged.path.surface).and_then(dock_area)?;
3248        let group = Dragged::Group {
3249            panels: leaf.tabs.clone(),
3250            shown,
3251        };
3252        Some((group, area, dragged.pointer))
3253    }
3254
3255    /// The area a palette dropped at `at` docks in: a side or bottom area
3256    /// drawn there, or a closed one when the pointer is within `edge` of
3257    /// the areas' edges (narrower than for tabs: a palette snapped to an
3258    /// edge must not dock); `None` over the centre (it floats there),
3259    /// unless the centre is empty: every panel moved out of it, it takes
3260    /// the palette as it takes a dragged tab.
3261    pub fn dock_at(&self, at: Pos2, edge: f32) -> Option<Area> {
3262        let shown = |a: Area| !self.panels_in(a).is_empty();
3263        let c = self.content;
3264        if c.is_positive() {
3265            let (left, right) = self.left_right();
3266            if !shown(left) && at.x < c.left() + edge {
3267                return Some(left);
3268            }
3269            if !shown(right) && at.x > c.right() - edge {
3270                return Some(right);
3271            }
3272            if !shown(Area::Bottom) && at.y > c.bottom() - edge {
3273                return Some(Area::Bottom);
3274            }
3275        }
3276        self.rects
3277            .iter()
3278            .filter(|(a, _)| **a != Area::Center || !shown(Area::Center))
3279            .find(|(_, r)| r.contains(at))
3280            .map(|(a, _)| *a)
3281    }
3282
3283    /// Whether a side area lies on the window's left now (the start one,
3284    /// unless the primary side bar is on the right).
3285    pub fn on_left(&self, area: Area) -> bool {
3286        on_left(area, self.flipped)
3287    }
3288
3289    /// The side areas on the left and on the right.
3290    fn left_right(&self) -> (Area, Area) {
3291        if self.flipped {
3292            (Area::EndSide, Area::StartSide)
3293        } else {
3294            (Area::StartSide, Area::EndSide)
3295        }
3296    }
3297
3298    /// Keeps where a dock painted the dragged tab's drop zone, if it did.
3299    fn note_landing(&mut self, seen: Mutex<Option<Painted>>, pass: u64) {
3300        let Some(painted) = seen.into_inner().ok().flatten() else {
3301            return;
3302        };
3303        // The dock it would go into (another than the one drawn, which may
3304        // have resolved the drag for every dock), as an area.
3305        let surface = match &painted.destination {
3306            egui_stack::TabDestination::Node(path, _) => path.surface,
3307            egui_stack::TabDestination::EmptySurface(surface) => *surface,
3308            egui_stack::TabDestination::Window(_) => return,
3309        };
3310        let Some(name) = self
3311            .space
3312            .as_ref()
3313            .and_then(|space| space.dock_name(surface))
3314            .map(str::to_owned)
3315        else {
3316            return;
3317        };
3318        self.cross_landing = Some((name.clone(), painted.refusal.clone(), pass));
3319        // Over a detached window's dock drawn with the main window's (a
3320        // backend that draws the windows in it): the window takes it.
3321        if let Some(window) = name
3322            .strip_prefix("window:")
3323            .and_then(|p| PanelId::new(p).ok())
3324        {
3325            let lead = (self.dragging.as_ref().map(|(d, ..)| d.lead().clone()))
3326                .or_else(|| self.cross.as_ref().map(|c| c.dragged.lead().clone()));
3327            if let Some(panel) = lead {
3328                self.window_drop = Some(WindowDrop {
3329                    panel,
3330                    window,
3331                    zone: zone_of(&painted.destination),
3332                    refusal: painted.refusal,
3333                });
3334            }
3335            return;
3336        }
3337        self.landing_rect = Some(painted.rect);
3338        let Some((area, bare)) = dock_area(&name) else {
3339            return;
3340        };
3341        let Some(landing) = Landing::of(&painted.destination, bare) else {
3342            return;
3343        };
3344        // The tab dragged, as the last pass followed it (the hint is
3345        // published only for a drag followed).
3346        let Some((dragged, _, _)) = &self.dragging else {
3347            return;
3348        };
3349        self.landing = Some(Seen {
3350            panel: dragged.lead().clone(),
3351            area,
3352            landing,
3353            refusal: painted.refusal,
3354        });
3355    }
3356
3357    /// Where a drop hint for `area` is drawn when no dock draws it: the
3358    /// area, or along the areas' edge for a closed one.
3359    pub fn hint_rect(&self, area: Area) -> Rect {
3360        self.rects
3361            .get(&area)
3362            .copied()
3363            .unwrap_or_else(|| self.edge_rect(area))
3364    }
3365
3366    /// Where a closed area takes a drop: a band along the areas' edge on
3367    /// its side (the centre: all of them).
3368    fn edge_rect(&self, area: Area) -> Rect {
3369        let c = self.content;
3370        let left = Rect::from_min_max(c.min, egui::pos2(c.left() + EDGE, c.bottom()));
3371        let right = Rect::from_min_max(egui::pos2(c.right() - EDGE, c.top()), c.max);
3372        match area {
3373            Area::StartSide | Area::EndSide if self.on_left(area) => left,
3374            Area::StartSide | Area::EndSide => right,
3375            Area::Bottom => Rect::from_min_max(egui::pos2(c.left(), c.bottom() - EDGE), c.max),
3376            Area::Center => c,
3377        }
3378    }
3379}
3380
3381/// Draws the detached panels, each in a window of its own (with its own
3382/// scale, and the application's frame when it draws one): egui_stack's
3383/// native floats (`FloatsArea`), each showing the window's dock of the
3384/// workbench's space, through egui-pop's host (`window_host`), which keeps
3385/// egui-pop's viewport ids. Closing such a window is the
3386/// `workbench.close_window` step (egui_stack's close policy says `Keep`),
3387/// whose default asks the window's `pop.window.close` on the bus: the
3388/// workbench's listener docks its panels back (`crate::bus::panels`, which
3389/// shows the windows too).
3390///
3391/// Each window is a window of the application in full: `keys` dispatches
3392/// its keys in its own context (its focus chain, `window` naming its
3393/// panel), the `WINDOW_OVERLAYS` zone draws the overlays opened from it
3394/// over it (dialogs, the command palette, popup menus; the toasts while
3395/// it is the active window), and a modal open in another window blocks
3396/// it (`overlay::block_window`).
3397///
3398/// A window's docks are the space's: a tab or a group dragged from one
3399/// window to another is one drag of the space (`DockSpace::dragging`),
3400/// which shows its drop zone in the window under the pointer, outlines
3401/// the windows where the system hides where they are, and lands it once.
3402/// A drop into or out of a detached window then runs the workbench's step
3403/// (`settle_drop`).
3404pub(crate) fn windows(
3405    app: &AppHandle,
3406    ctx: &egui::Context,
3407    app_name: &str,
3408    keys: &mut dyn FnMut(&egui::Context),
3409) {
3410    // A group let go outside every window, no window taking it: it opens
3411    // a window of its own.
3412    if let Some((group, End::Left { inside: false })) = drag::ended::<Dragged>(ctx)
3413        && group.is_group()
3414    {
3415        drag::take_ended::<Dragged>(ctx);
3416        detach_dropped(app, &group);
3417        drag::claim(ctx, "workbench.detach");
3418    }
3419    let auxiliary = app.workbench_mut().layout.auxiliary.clone();
3420    let screens = crate::window::screens();
3421    // A window gone: its next one opens with its own place.
3422    app.workbench_mut()
3423        .window_asks
3424        .retain(|p, _| auxiliary.iter().any(|a| a.panel == *p));
3425    // Titled after the panel it shows: not drawn while that panel is not
3426    // declared.
3427    let drawn: Vec<Auxiliary> = auxiliary
3428        .into_iter()
3429        .filter(|a| app.workbench_mut().spec(a.shown()).is_some())
3430        .collect();
3431    for aux in &drawn {
3432        // A place off every screen comes back onto one. The builder keeps
3433        // the place the window opened with: one that changed would be
3434        // asked of the system again by the backend, a size the system
3435        // just set asked back one pass late (#5241).
3436        let changed = app.workbench_mut().window_place(
3437            &aux.panel,
3438            (aux.rect, aux.maximized, aux.fullscreen),
3439            &screens,
3440        );
3441        if let Some((from, to)) = changed {
3442            crate::bus::panels::ask_place(ctx, window_id(&aux.panel), &aux.panel, from, to);
3443        }
3444    }
3445    let Some(mut space) = app.workbench_mut().take_space() else {
3446        return;
3447    };
3448    let mut floats = std::mem::replace(
3449        &mut app.workbench_mut().floats,
3450        ZoneLayout::new(Zone::leaf("windows", Content::Empty)),
3451    );
3452    // egui_stack's places, in its terms (named screens, physical pixels);
3453    // its own repair is left off (the host tells it no screen): egui-pop
3454    // brings windows back onto the screens (`window_place`, `screen.*`).
3455    let stack_screens = window_host::stack_screens(&crate::window::screen_list());
3456    sync_floats(&mut floats, &mut space, &drawn, &stack_screens);
3457    let kit = Kit::of(ctx);
3458    let panels: Vec<PanelId> = drawn.iter().flat_map(|a| a.panels().cloned()).collect();
3459    let cache_id = TAB_CACHE.keyed("windows");
3460    let mut cache = cache_id.update(ctx, std::mem::take);
3461    cache.prepare(app, ctx, &kit, &panels);
3462    let style = cache.dock_style(&ctx.global_style(), &kit);
3463    // What each window's dock holds, to name a drag begun there.
3464    let docks: HashMap<egui_stack::SurfaceIndex, (PanelId, Vec<PanelId>, usize)> = drawn
3465        .iter()
3466        .filter_map(|a| {
3467            let surface = space.dock_surface(&window_host::window_dock(&a.panel))?;
3468            let (tabs, active) = window_tabs_in(&space, &a.panel)?;
3469            Some((surface, (a.panel.clone(), tabs, active)))
3470        })
3471        .collect();
3472    let dragged = app
3473        .workbench_mut()
3474        .cross
3475        .as_ref()
3476        .map(|c| c.dragged.clone());
3477    let seen = Mutex::new(None);
3478    let outlined = Mutex::new(false);
3479    let painter = AreaPainter::new(&kit, false, &seen).outlines(&outlined);
3480    let mut viewer = Viewer {
3481        app,
3482        prepared: &cache.tabs,
3483        eject: false,
3484        ejected: None,
3485        groups: groups_of(space.state()),
3486        added: None,
3487    };
3488    space.state_mut().translations = dock_translations(ctx);
3489    // A backend without windows of its own (kittest, the web) draws them
3490    // in the main window: their docks share the main window's drag.
3491    let embedded = ctx.embed_viewports();
3492    let labels = group_labels(ctx);
3493    let mut window_drop = None;
3494    let mut window_outlines = Vec::new();
3495    let mut host = window_host::PanelWindows::new(app, ctx, app_name, keys);
3496    egui_stack::FloatsArea::new(&mut floats, &mut space)
3497        .host(&mut host)
3498        .style(style)
3499        .painter(&painter)
3500        .group_handles(group_handles(app))
3501        .group_drag_modifiers(group_drag_modifier(app).modifiers())
3502        .float_move(float_move(app))
3503        .move_from(dock_controls(app).float_move_from)
3504        .show_add_buttons(dock_controls(app).add_buttons)
3505        .configure(|_, area| {
3506            let area = area
3507                .labels(labels.clone())
3508                .group_context_menus(dock_controls(app).group_menus)
3509                .allowed_splits(egui_stack::AllowedSplits::None)
3510                .show_close_buttons(false)
3511                .show_add_buttons(dock_controls(app).add_buttons)
3512                .show_leaf_close_all_buttons(false)
3513                .show_leaf_collapse_buttons(false);
3514            if embedded { area.id(space_id()) } else { area }
3515        })
3516        .decorate(|ui, shown| {
3517            let Some(window) = PanelId::new(shown.key.as_str()).ok() else {
3518                return;
3519            };
3520            // The drop zone the space painted over this window's dock, or
3521            // its outline: where a tab dragged from another window goes.
3522            if let Some(painted) = seen.lock().ok().and_then(|mut s| s.take())
3523                && let Some(dragged) = &dragged
3524            {
3525                window_drop = Some(WindowDrop {
3526                    panel: dragged.lead().clone(),
3527                    window: window.clone(),
3528                    zone: zone_of(&painted.destination),
3529                    refusal: painted.refusal.clone(),
3530                });
3531                app.workbench_mut().cross_landing = Some((
3532                    window_host::window_dock(&window),
3533                    painted.refusal,
3534                    ctx.cumulative_pass_nr(),
3535                ));
3536            }
3537            if outlined.lock().is_ok_and(|mut o| std::mem::take(&mut *o)) {
3538                window_outlines.push(window.clone());
3539            }
3540            let area_id = if embedded {
3541                space_id()
3542            } else {
3543                space_id().with(("egui_stack.float", shown.key.as_str()))
3544            };
3545            let bars = if shown.tab_bars.is_empty() {
3546                // Drawn with the main window's docks: their bars together.
3547                let surface = docks
3548                    .iter()
3549                    .find(|(_, (w, ..))| *w == window)
3550                    .map(|(s, _)| *s);
3551                DockArea::tab_bars(ui.ctx(), area_id)
3552                    .into_iter()
3553                    .filter(|(path, _)| Some(path.surface) == surface)
3554                    .collect()
3555            } else {
3556                shown.tab_bars.clone()
3557            };
3558            if let Some((_, bar)) = bars.first() {
3559                let shown_panel = docks
3560                    .values()
3561                    .find(|(w, ..)| *w == window)
3562                    .and_then(|(_, tabs, active)| tabs.get(*active).cloned())
3563                    .unwrap_or_else(|| window.clone());
3564                dock_back_button(app, ui, &kit, *bar, &shown_panel);
3565            }
3566            window_drag(ui.ctx(), area_id, &window, &docks);
3567        })
3568        .show(ctx, &mut viewer);
3569    let added = viewer.added.take();
3570    // egui_stack's own record of the floats' life: egui-pop's steps and
3571    // the bus already say it.
3572    let _ = space.take_float_events();
3573    // A float egui_stack closed this pass kept its place in its own
3574    // terms: egui-pop's is the one kept (`closed_windows`).
3575    floats.closed.clear();
3576    cache_id.set(ctx, cache);
3577    let mut wb = app.workbench_mut();
3578    wb.floats = floats;
3579    if window_drop.is_some() {
3580        wb.window_drop = window_drop;
3581    }
3582    wb.window_outlines = window_outlines;
3583    wb.put_space(space);
3584    drop(wb);
3585    settle_drop(app, ctx);
3586    open_add_menu(app, ctx, added);
3587}
3588
3589/// The floats showing the detached windows drawn: one per window, keyed
3590/// by its panel, opened at its place (egui-pop's, read on egui_stack's
3591/// screens).
3592/// A window no longer drawn loses its dock, and egui_stack closes its
3593/// float (forgetting its window's builder).
3594///
3595/// One owner for a closed window's place: egui-pop's (`closed_windows`,
3596/// its screen named, the layout's form). The copy egui_stack keeps when it
3597/// closes a float (`ZoneLayout::closed`, screen points) is dropped, so a
3598/// float opened again is never moved by it.
3599fn sync_floats(
3600    floats: &mut ZoneLayout,
3601    space: &mut DockSpace<PanelId>,
3602    drawn: &[Auxiliary],
3603    screens: &[egui_stack::layout::Screen],
3604) {
3605    floats.closed.clear();
3606    let gone: Vec<String> = floats
3607        .floats
3608        .iter()
3609        .map(|f| f.key.clone())
3610        .filter(|key| !drawn.iter().any(|a| a.panel.as_str() == key))
3611        .collect();
3612    for key in gone {
3613        if let Ok(panel) = PanelId::new(key.as_str()) {
3614            let _ = space.remove_dock(&window_host::window_dock(&panel));
3615        }
3616    }
3617    for aux in drawn {
3618        let float = window_host::float_of(aux, screens);
3619        // An open float keeps the place egui_stack follows from the system:
3620        // egui_stack moves a window whose place changed from code (0.28.9),
3621        // and egui-pop asks its own moves itself (`window_asks`), so its
3622        // place, told by the system, is never written back (#5241).
3623        if floats.float_mut(&float.key).is_none() {
3624            let place = float.place.clone();
3625            floats.open_float(float).place = place;
3626        }
3627    }
3628}
3629
3630/// How a drop lands in a detached window's dock: among its tabs (they
3631/// hold no splits).
3632fn zone_of(destination: &egui_stack::TabDestination) -> DropZone {
3633    match Landing::of(destination, false) {
3634        Some(Landing::Split(zone)) => zone,
3635        _ => DropZone::Center,
3636    }
3637}
3638
3639/// A tab or a group dragged out of a detached window (its dock's area
3640/// `area_id`, drawn in `ctx`'s window): carried by a drag session
3641/// (`bus::drag`) too, so the drag is said on the bus (`drag.started`,
3642/// `drag.dropped` or `drag.refused`) whichever window it began in. Let go
3643/// in its own window over no target, its dock took it.
3644fn window_drag(
3645    ctx: &egui::Context,
3646    area_id: Id,
3647    window: &PanelId,
3648    docks: &HashMap<egui_stack::SurfaceIndex, (PanelId, Vec<PanelId>, usize)>,
3649) {
3650    let mine = |surface| docks.get(&surface).filter(|(w, ..)| w == window);
3651    let dragged = DockArea::dragged_tab(ctx, area_id)
3652        .and_then(|d| {
3653            let (_, tabs, _) = mine(d.path.surface)?;
3654            Some(Dragged::Tab(tabs.get(d.path.tab.0)?.clone()))
3655        })
3656        .or_else(|| {
3657            let d = DockArea::dragged_node(ctx, area_id)?;
3658            let (_, tabs, active) = mine(d.path.surface)?;
3659            Some(Dragged::Group {
3660                panels: tabs.clone(),
3661                shown: tabs.get(*active).or(tabs.first())?.clone(),
3662            })
3663        });
3664    let started_id = Id::unique(("egui_pop.window_dock", window.as_str())).with("drag_session");
3665    let started = ctx
3666        .data(|d| d.get_temp::<bool>(started_id))
3667        .unwrap_or(false);
3668    // A flag left by a window a drop emptied and closed does not hold
3669    // back the next drag: a session carrying the tab is what counts.
3670    let carried = |d: &Dragged| {
3671        drag::payload::<Dragged>(ctx).is_some_and(|p| d.panels().iter().all(|q| p.holds(q)))
3672    };
3673    match dragged {
3674        Some(d) if !carried(&d) => {
3675            let kind = if d.is_group() { "tab-group" } else { "tab" };
3676            drag::start(ctx, kind, d);
3677            ctx.data_mut(|data| data.insert_temp(started_id, true));
3678        }
3679        Some(_) => {}
3680        None if started => {
3681            ctx.data_mut(|d| d.remove_temp::<bool>(started_id));
3682            if let Some((_, End::Left { inside: true })) = drag::ended::<Dragged>(ctx) {
3683                drag::claim(ctx, "workbench.window");
3684            }
3685        }
3686        None => {}
3687    }
3688}
3689
3690/// The space's drag, followed each pass: when it begins, the layout is
3691/// kept as it was; when it ends, a tab or a group the space moved into a
3692/// detached window, or out of one, is put back and moved by the
3693/// workbench's step instead, as a drop on the window always was (a plugin
3694/// may veto or redirect it, the panels' registry follows its windows):
3695///
3696/// - into a detached window: `workbench.join_window` (`group` for a
3697///   group), said on the bus as dropped on that window;
3698/// - out of one into an area of the main window: `workbench.move` for
3699///   each of its panels, said as dropped on the area
3700///   (`workbench.area.<area>`).
3701///
3702/// A drag the space refused over another window (the drop zone painted
3703/// refused) is said refused with its reason. A drag inside the main
3704/// window is the areas' (`track_drag`). Either way the drag session
3705/// (`bus::drag`) ends there: a release the space took is never delivered
3706/// to a target of the session (`drag::taken`).
3707fn settle_drop(app: &AppHandle, ctx: &egui::Context) {
3708    let mut wb = app.workbench_mut();
3709    let pass = ctx.cumulative_pass_nr();
3710    let Some(space) = wb.space.as_ref().or(wb.retired.as_ref()) else {
3711        return;
3712    };
3713    let now = homes(space);
3714    // A move egui_stack made: the windows' docks no longer hold what the
3715    // layout says (a step that moved it since, a detach, made them agree).
3716    let moved = unsettled(space, &wb.layout.auxiliary);
3717    if let Some(drag) = space.dragging() {
3718        let dragged = match drag.payload {
3719            egui_stack::DragPayload::Tab(path) => space
3720                .state()
3721                .leaf(path.node_path())
3722                .ok()
3723                .and_then(|leaf| leaf.tabs.get(path.tab.0).cloned())
3724                .map(Dragged::Tab),
3725            egui_stack::DragPayload::Group(path) => {
3726                space.state().leaf(path).ok().and_then(|leaf| {
3727                    let shown = leaf.tabs.get(leaf.active.0).or(leaf.tabs.first())?.clone();
3728                    Some(Dragged::Group {
3729                        panels: leaf.tabs.clone(),
3730                        shown,
3731                    })
3732                })
3733            }
3734            _ => None,
3735        };
3736        let Some(dragged) = dragged else {
3737            return;
3738        };
3739        let source = drag.source;
3740        if wb.cross.as_ref().is_some_and(|c| c.dragged == dragged) {
3741            return;
3742        }
3743        let homes: Vec<Home> = (dragged.panels().iter())
3744            .filter_map(|p| now.get(p).cloned())
3745            .collect();
3746        wb.read_back();
3747        let cross = Cross {
3748            dragged,
3749            source,
3750            areas: wb.layout.areas.clone(),
3751            windows: wb.layout.auxiliary.clone(),
3752            in_windows: wb.layout.windows.clone(),
3753            homes,
3754        };
3755        wb.cross = Some(cross);
3756        return;
3757    }
3758    let Some(cross) = wb.cross.take() else {
3759        return;
3760    };
3761    let landing = wb.cross_landing.take().filter(|(_, _, at)| *at + 2 >= pass);
3762    let lead = cross.dragged.lead().clone();
3763    let was = cross.homes.first().cloned();
3764    let to = now.get(&lead).cloned();
3765    let crossed = moved
3766        && match (&was, &to) {
3767            (Some(Home::Window(a)), Some(Home::Window(b))) => a != b,
3768            (Some(Home::Window(_)), Some(Home::Area(_) | Home::InWindow(..)))
3769            | (_, Some(Home::Window(_))) => was != to,
3770            _ => false,
3771        };
3772    if !crossed {
3773        // Nothing moved across a window: a refusal over another window
3774        // is said, with its reason.
3775        let from_window = matches!(was, Some(Home::Window(_)));
3776        // Let go over the main window out of its docks (an area's margin):
3777        // the area there takes it, as the whole area always did.
3778        let area_at = (drag::pointer_here::<Dragged>(ctx))
3779            .filter(|_| from_window && cross.source != ctx.viewport_id())
3780            .filter(|_| !landing.as_ref().is_some_and(|(_, why, _)| why.is_some()))
3781            .and_then(|at| area_under(&wb, at));
3782        drop(wb);
3783        if let Some(area) = area_at {
3784            drop_into_area(app, ctx, &cross.dragged, area);
3785            return;
3786        }
3787        let Some((dock, Some(reason), _)) = landing else {
3788            return;
3789        };
3790        let into_window = dock.starts_with("window:");
3791        if !into_window && !from_window {
3792            return;
3793        }
3794        let (window, target) = drop_target_names(&dock);
3795        drag::taken::<Dragged>(ctx, &window, &target, Some(reason.clone()));
3796        match dock
3797            .strip_prefix("window:")
3798            .and_then(|p| PanelId::new(p).ok())
3799        {
3800            // As a drop on the window always did: its step says why.
3801            Some(w) => join_dropped(app, &cross.dragged, &w),
3802            None => app.workbench_refused(&format!("move {lead}"), &reason),
3803        }
3804        return;
3805    }
3806    // Put back as it was: the step moves it.
3807    wb.layout.areas = cross.areas.clone();
3808    wb.layout.windows = cross.in_windows.clone();
3809    for a in &mut wb.layout.auxiliary {
3810        if let Some(before) = cross.windows.iter().find(|b| b.panel == a.panel) {
3811            a.tabs.clone_from(&before.tabs);
3812            a.shown = before.shown;
3813        }
3814    }
3815    let gone: Vec<Auxiliary> = (cross.windows.iter())
3816        .filter(|b| !wb.layout.auxiliary.iter().any(|a| a.panel == b.panel))
3817        .cloned()
3818        .collect();
3819    wb.layout.auxiliary.extend(gone);
3820    wb.stale = true;
3821    drop(wb);
3822    match to {
3823        Some(Home::Window(window)) => {
3824            let target = crate::bus::panels::window_of_panel(&window);
3825            drag::taken::<Dragged>(ctx, &target, &target, None);
3826            join_dropped(app, &cross.dragged, &window);
3827        }
3828        Some(Home::Area(area)) => drop_into_area(app, ctx, &cross.dragged, area),
3829        Some(Home::InWindow(window, area)) => {
3830            drop_into_window_area(app, ctx, &cross.dragged, &window, area);
3831        }
3832        None => {}
3833    }
3834    ctx.request_repaint();
3835}
3836
3837/// A tab or a group from a detached window let go over an area of the main
3838/// window: each of its panels' `workbench.move` (the first refused or
3839/// vetoed stops it), said as dropped on `workbench.area.<area>`; refused
3840/// with the area's reason where the area keeps it out.
3841fn drop_into_area(app: &AppHandle, ctx: &egui::Context, dragged: &Dragged, area: Area) {
3842    let target = format!("workbench.area.{}", area_name(area));
3843    let why = {
3844        let wb = app.workbench_mut();
3845        let specs: Vec<PanelSpec> = (dragged.panels().iter())
3846            .filter_map(|p| wb.spec(p).cloned())
3847            .collect();
3848        specs.iter().find_map(|spec| {
3849            let title = strings::panel_title(ctx, spec.id.as_str(), &spec.title);
3850            refusal(ctx, spec, &title, area)
3851                .or_else(|| spec.refuses(&crate::mounts::panel_host(Place::Area(area))))
3852        })
3853    };
3854    drag::taken::<Dragged>(ctx, crate::windows::WindowId::MAIN, &target, why.clone());
3855    if let Some(why) = why {
3856        app.workbench_refused(&format!("move {}", dragged.lead()), &why);
3857        return;
3858    }
3859    for panel in dragged.panels() {
3860        let out = app.change_workbench(Change::Move(panel.clone(), area));
3861        if let Some(Outcome::Done(Err(e))) = &out {
3862            app.workbench_refused(&format!("move {panel}"), e);
3863            break;
3864        }
3865        if matches!(out, Some(Outcome::Vetoed { .. })) {
3866            break;
3867        }
3868    }
3869}
3870
3871/// A tab or a group from a detached window let go over an application
3872/// window's area: each of its panels' `workbench.move` with the window
3873/// (the first refused or vetoed stops it), said as dropped on
3874/// `workbench.area.<area>` of that window; refused with the area's reason
3875/// where the area keeps it out.
3876fn drop_into_window_area(
3877    app: &AppHandle,
3878    ctx: &egui::Context,
3879    dragged: &Dragged,
3880    window: &str,
3881    area: Area,
3882) {
3883    let target = format!("workbench.area.{}", area_name(area));
3884    let why = {
3885        let wb = app.workbench_mut();
3886        let specs: Vec<PanelSpec> = (dragged.panels().iter())
3887            .filter_map(|p| wb.spec(p).cloned())
3888            .collect();
3889        specs.iter().find_map(|spec| {
3890            let title = strings::panel_title(ctx, spec.id.as_str(), &spec.title);
3891            refusal(ctx, spec, &title, area)
3892                .or_else(|| spec.refuses(&crate::mounts::panel_host(Place::Area(area))))
3893        })
3894    };
3895    drag::taken::<Dragged>(ctx, window, &target, why.clone());
3896    if let Some(why) = why {
3897        app.workbench_refused(&format!("move {}", dragged.lead()), &why);
3898        return;
3899    }
3900    for panel in dragged.panels() {
3901        let change = Change::MoveInWindow(panel.clone(), window.to_owned(), area);
3902        let out = app.change_workbench(change);
3903        if let Some(Outcome::Done(Err(e))) = &out {
3904            app.workbench_refused(&format!("move {panel}"), e);
3905            break;
3906        }
3907        if matches!(out, Some(Outcome::Vetoed { .. })) {
3908            break;
3909        }
3910    }
3911}
3912
3913/// The area of the main window at `at` (its points): one drawn there, else
3914/// a closed one whose band along the areas' edge holds it, else the centre
3915/// when it lies in the areas.
3916fn area_under(wb: &Workbench, at: Pos2) -> Option<Area> {
3917    let closed = [Area::StartSide, Area::EndSide, Area::Bottom]
3918        .into_iter()
3919        .filter(|a| wb.panels_in(*a).is_empty() && !wb.main_zen())
3920        .find(|a| wb.edge_rect(*a).contains(at));
3921    let drawn = (wb.rects.iter())
3922        .filter(|(a, _)| **a == Area::Center || !wb.main_zen())
3923        .find(|(_, r)| r.contains(at))
3924        .map(|(a, _)| *a);
3925    closed
3926        .or(drawn)
3927        .or_else(|| wb.content.contains(at).then_some(Area::Center))
3928}
3929
3930/// The window and the target a drop on a dock of the space is said on
3931/// the bus with: a detached window by its window (`panel:<panel>`), an
3932/// area of the main window as `workbench.area.<area>`.
3933fn drop_target_names(dock: &str) -> (String, String) {
3934    match dock
3935        .strip_prefix("window:")
3936        .and_then(|p| PanelId::new(p).ok())
3937    {
3938        Some(w) => {
3939            let window = crate::bus::panels::window_of_panel(&w);
3940            (window.clone(), window)
3941        }
3942        None => {
3943            let area = dock_area(dock).map_or(Area::Center, |(a, _)| a);
3944            (
3945                crate::windows::WindowId::MAIN.to_string(),
3946                format!("workbench.area.{}", area_name(area)),
3947            )
3948        }
3949    }
3950}
3951
3952/// Follows a detached window's place into the layout: maximized and
3953/// full screen as they are; its normal size and position only out of
3954/// them; the position only where the system tells it (not on Wayland,
3955/// where the one kept stays: never a made-up one).
3956fn keep_window_place(app: &AppHandle, vctx: &egui::Context, panel: &PanelId) {
3957    let (info, size) = vctx.input(|i| (i.viewport().clone(), i.viewport_rect().size()));
3958    let maximized = info.maximized.unwrap_or(false);
3959    let fullscreen = info.fullscreen.unwrap_or(false);
3960    let size = info.inner_rect.map_or(size, |r| r.size());
3961    let mut guard = app.workbench_mut();
3962    let wb = &mut *guard;
3963    let Some(a) = wb.layout.auxiliary.iter_mut().find(|a| a.panel == *panel) else {
3964        return;
3965    };
3966    let was = a.clone();
3967    if a.maximized != maximized {
3968        a.maximized = maximized;
3969    }
3970    if a.fullscreen != fullscreen {
3971        a.fullscreen = fullscreen;
3972    }
3973    let normal = !(maximized
3974        || fullscreen
3975        || info.minimized == Some(true)
3976        || size.x <= 0.0
3977        || size.y <= 0.0);
3978    if normal {
3979        let [x, y, ..] = a.rect;
3980        let (x, y) = info.outer_rect.map_or((x, y), |r| (r.min.x, r.min.y));
3981        let rect = [x, y, size.x, size.y];
3982        if a.rect != rect {
3983            a.rect = rect;
3984        }
3985    }
3986    // The system's place: followed, never asked back (#5241).
3987    if a.rect != was.rect || a.maximized != was.maximized || a.fullscreen != was.fullscreen {
3988        let told = (a.rect, a.maximized, a.fullscreen);
3989        wb.window_told(panel, told);
3990    }
3991    let Some(a) = wb.layout.auxiliary.iter_mut().find(|a| a.panel == *panel) else {
3992        return;
3993    };
3994    if !normal {
3995        return;
3996    }
3997    // The screen it is on, by the name the system gives it: unplugged,
3998    // the window docks back (`pop.screen.removed`).
3999    if let Some(name) = info
4000        .outer_rect
4001        .and_then(|r| crate::window::screen_name_at(egui::Rect::from_min_size(r.min, size)))
4002        && a.screen != name
4003    {
4004        a.screen = name;
4005    }
4006    if *a != was {
4007        drop(guard);
4008        app.note_layout("window.place");
4009    }
4010}
4011
4012/// The Dock back button at the end of a detached window's tab bar (`bar`,
4013/// the whole bar), left of egui_stack's group grip and move handle: its
4014/// shown panel docks back where it came from, else in its own area
4015/// (`workbench.dock_back`, as the tab menu's Dock back and the
4016/// `workbench.panel.dock_back` command, `Ctrl+Shift+D`). Named for
4017/// assistive technology, its name its tooltip.
4018fn dock_back_button(app: &AppHandle, ui: &mut Ui, kit: &Kit, bar: Rect, shown: &PanelId) {
4019    let side = bar.height().min(kit.tab.data.height.max(16.0));
4020    let handles = group_handles(app);
4021    let ends = [GroupHandles::GRIP, GroupHandles::MOVE_WINDOW]
4022        .into_iter()
4023        .filter(|h| handles.contains(*h))
4024        .count() as f32;
4025    let right = bar.right() - ends * GROUP_HANDLE_SIZE;
4026    let rect = Rect::from_center_size(
4027        egui::pos2(right - side / 2.0 - 2.0, bar.center().y),
4028        egui::vec2(side, side),
4029    );
4030    let name = strings::tr(ui.ctx(), &txt::WORKBENCH_DOCK_BACK);
4031    let mut child = ui.new_child(
4032        egui::UiBuilder::new()
4033            .id_salt(("egui_pop.window_dock_back", shown.as_str()))
4034            .max_rect(rect),
4035    );
4036    let clicked = egui_pop_core::band::button(
4037        &mut child,
4038        side,
4039        egui_pop_core::icon::Icon::Layout,
4040        &name,
4041        false,
4042    )
4043    .clicked();
4044    if clicked {
4045        let out = app.change_workbench(Change::DockBack(shown.clone()));
4046        if let Some(Outcome::Done(Err(e))) = &out {
4047            app.workbench_refused(&format!("dock back {shown}"), e);
4048        }
4049    }
4050}
4051
4052/// The breadth of each of egui_stack's handles at the end of a tab bar
4053/// (the group grip, a float's move handle), in points.
4054const GROUP_HANDLE_SIZE: f32 = 16.0;
4055
4056/// The least width of a detached window's outline while a tab is dragged
4057/// out of another window where window positions are hidden
4058/// (`DockPainter::window_outline`), in points: seen at a glance around the
4059/// whole window.
4060const WINDOW_OUTLINE_WIDTH: f32 = 3.0;
4061
4062/// Forgets the overlays of the windows closed since the last pass: what
4063/// they showed is gone with them (a dialog shown there comes to the main
4064/// window).
4065pub(crate) fn forget_closed_windows(app: &AppHandle, ctx: &egui::Context) {
4066    let mut open: Vec<ViewportId> = app
4067        .workbench_mut()
4068        .layout
4069        .auxiliary
4070        .iter()
4071        .map(|a| window_id(&a.panel))
4072        .collect();
4073    // The application's own windows keep theirs too (ADR 0025).
4074    open.extend(app.windows().iter().skip(1).map(|w| w.viewport));
4075    egui_pop_core::overlay::retain_windows(ctx, &open);
4076}
4077
4078/// A detached panel's window id.
4079pub fn window_id(panel: &PanelId) -> ViewportId {
4080    panel_viewport(panel.as_str())
4081}
4082
4083/// A detached panel's window id, from the panel's id.
4084pub(crate) fn panel_viewport(panel: &str) -> ViewportId {
4085    ViewportId::from_hash_of(("egui_pop.aux", panel))
4086}
4087
4088/// An area's id: its egui panel's, and its tabs' cache key.
4089pub(crate) fn dock_id(area: Area) -> Id {
4090    Id::unique(("egui_pop.area", area_name(area)))
4091}
4092/// An area as the interface names it ("the start side bar").
4093pub(crate) fn area_text(ctx: &egui::Context, area: Area) -> String {
4094    strings::tr(
4095        ctx,
4096        match area {
4097            Area::Center => &txt::AREA_CENTER,
4098            Area::StartSide => &txt::AREA_START_SIDE,
4099            Area::EndSide => &txt::AREA_END_SIDE,
4100            Area::Bottom => &txt::AREA_BOTTOM,
4101        },
4102    )
4103}
4104
4105/// The title of the space's dock `dock` (an area's own, or its bare
4106/// target), as the tab menu's Move group list shows it: the area's title,
4107/// and the titles of the panels it holds, translated.
4108fn dock_title(app: &AppHandle, ctx: &egui::Context, dock: &str) -> Option<String> {
4109    let (area, _) = dock_area(dock)?;
4110    let title = strings::tr(
4111        ctx,
4112        match area {
4113            Area::Center => &txt::AREA_TITLE_CENTER,
4114            Area::StartSide => &txt::AREA_TITLE_START_SIDE,
4115            Area::EndSide => &txt::AREA_TITLE_END_SIDE,
4116            Area::Bottom => &txt::AREA_TITLE_BOTTOM,
4117        },
4118    );
4119    let panels: Vec<PanelId> = {
4120        let wb = app.workbench_mut();
4121        wb.layout
4122            .areas
4123            .iter()
4124            .find(|(a, _)| *a == area)
4125            .map(|(_, node)| node.panels().into_iter().cloned().collect())
4126            .unwrap_or_default()
4127    };
4128    if panels.is_empty() {
4129        return Some(title);
4130    }
4131    let panels: Vec<String> = panels.iter().map(|p| app.panel_title(ctx, p)).collect();
4132    Some(strings::tr_args(
4133        ctx,
4134        &txt::WORKBENCH_DOCK_TITLE,
4135        &[("area", &title), ("panels", &panels.join(", "))],
4136    ))
4137}
4138
4139/// Why a panel may not go to an area, as the interface says it.
4140fn refusal(ctx: &egui::Context, spec: &PanelSpec, title: &str, area: Area) -> Option<String> {
4141    (!spec.allows(area)).then(|| {
4142        strings::tr_args(
4143            ctx,
4144            &txt::WORKBENCH_STAYS_OUT,
4145            &[("panel", title), ("area", &area_text(ctx, area))],
4146        )
4147    })
4148}
4149
4150/// The layout's areas as one `egui_stack` space: each area a dock named
4151/// after it (`area_name`), holding its tree, kept when it is empty (a drop
4152/// target while a tab drags); and, for each area, its bare target. The
4153/// layout document stays the saved form, an area's tree as it was saved
4154/// before the areas shared a space: each tree becomes its area's dock
4155/// through `DockSpace::from_states`, the per-area docks of before taken in
4156/// once.
4157pub(crate) fn to_space(layout: &Layout) -> DockSpace<PanelId> {
4158    let states = Area::ALL.into_iter().map(|area| {
4159        let state = layout
4160            .areas
4161            .iter()
4162            .find(|(a, _)| *a == area)
4163            .map_or_else(empty_dock, |(_, node)| to_dock(node));
4164        (area_name(area).to_owned(), area_rules(), state)
4165    });
4166    let mut space = DockSpace::from_states(states).with_id(space_id());
4167    for area in Area::ALL {
4168        space.add_dock(bare_target(area), bare_rules(), Vec::new());
4169    }
4170    // Each detached window: a dock of its own, a native float's
4171    // (`windows`), holding its tabs, its shown one active.
4172    for a in &layout.auxiliary {
4173        let name = window_host::window_dock(&a.panel);
4174        if space.has_dock(&name) {
4175            continue;
4176        }
4177        space.add_dock(&name, window_rules(), a.panels().cloned().collect());
4178        if let Some(tree) = space.dock_mut(&name)
4179            && let Some(leaf) = tree.iter_mut().find_map(|n| n.get_leaf_mut())
4180            && let Some(i) = leaf.tabs.iter().position(|p| p == a.shown())
4181        {
4182            leaf.active = egui_stack::TabIndex(i);
4183        }
4184    }
4185    // Each application window's areas: docks of the same space.
4186    window_areas::add_docks(&mut space, &layout.windows);
4187    space
4188}
4189
4190/// A detached window's dock's tabs, in order, and the one it shows; `None`
4191/// when the space has no dock for it.
4192fn window_tabs_in(space: &DockSpace<PanelId>, window: &PanelId) -> Option<(Vec<PanelId>, usize)> {
4193    let tree = space.dock(&window_host::window_dock(window))?;
4194    let mut panels = Vec::new();
4195    let mut active = 0;
4196    for node in tree.iter() {
4197        if let Some(leaf) = node.get_leaf() {
4198            if panels.is_empty() {
4199                active = leaf.active.0;
4200            }
4201            panels.extend(leaf.tabs.iter().cloned());
4202        }
4203    }
4204    let last = panels.len().saturating_sub(1);
4205    Some((panels, active.min(last)))
4206}
4207
4208/// Whether a detached window's dock holds other panels than its window
4209/// (a tab moved into or out of it, its step not run yet).
4210fn unsettled(space: &DockSpace<PanelId>, windows: &[Auxiliary]) -> bool {
4211    windows.iter().any(|a| {
4212        window_tabs_in(space, &a.panel).is_some_and(|(panels, _)| {
4213            let mut now: Vec<&PanelId> = panels.iter().collect();
4214            let mut was: Vec<&PanelId> = a.panels().collect();
4215            now.sort();
4216            was.sort();
4217            now != was
4218        })
4219    })
4220}
4221
4222/// Where each panel is in the space: its area, or its detached window.
4223fn homes(space: &DockSpace<PanelId>) -> HashMap<PanelId, Home> {
4224    let mut out = HashMap::new();
4225    for (path, panel) in space.state().iter_all_tabs() {
4226        let Some(name) = space.dock_name(path.surface) else {
4227            continue;
4228        };
4229        let home = match dock_area(name) {
4230            Some((area, _)) => Home::Area(area),
4231            None => match name
4232                .strip_prefix("window:")
4233                .and_then(|p| PanelId::new(p).ok())
4234            {
4235                Some(window) => Home::Window(window),
4236                None => match window_areas::dock_place(name) {
4237                    Some((window, area)) => Home::InWindow(window.to_owned(), area),
4238                    None => continue,
4239                },
4240            },
4241        };
4242        out.insert(panel.clone(), home);
4243    }
4244    out
4245}
4246
4247/// The areas' trees, read back from the space; a tab dropped on an area's
4248/// bare target and not yet settled joins the area's first tabs.
4249pub(crate) fn from_space(space: &DockSpace<PanelId>) -> Vec<(Area, Node)> {
4250    let mut areas: Vec<(Area, Node)> = Vec::new();
4251    for area in Area::ALL {
4252        let mut node = space
4253            .dock(area_name(area))
4254            .and_then(|tree| read(tree, NodeIndex::root()));
4255        for panel in space
4256            .dock(bare_target(area))
4257            .into_iter()
4258            .flat_map(|t| t.tabs())
4259        {
4260            match &mut node {
4261                Some(n) => push_first(n, panel.clone()),
4262                None => node = Some(Node::tab(panel.clone())),
4263            }
4264        }
4265        if let Some(node) = node {
4266            areas.push((area, node));
4267        }
4268    }
4269    areas.sort_by_key(|(a, _)| *a);
4270    areas
4271}
4272
4273/// Adds a panel to a tree's first tabs, shown (as `Layout::place` does).
4274fn push_first(node: &mut Node, panel: PanelId) {
4275    match node {
4276        Node::Tabs { panels, active } => {
4277            panels.push(panel);
4278            *active = panels.len() - 1;
4279        }
4280        Node::Split { a, .. } => push_first(a, panel),
4281        Node::Grid { children, .. } => {
4282            if let Some(first) = children.first_mut() {
4283                push_first(first, panel);
4284            }
4285        }
4286    }
4287}
4288
4289/// Moves the tabs dropped on the areas' bare targets into the areas: each
4290/// joins its area's first tabs, as a drop on an area drawn bare does.
4291fn settle_bare_drops(space: &mut DockSpace<PanelId>) {
4292    for area in Area::ALL {
4293        let (Some(from), Some(to)) = (
4294            space.dock_surface(bare_target(area)),
4295            space.dock_surface(area_name(area)),
4296        ) else {
4297            continue;
4298        };
4299        loop {
4300            let found = space
4301                .state()
4302                .iter_all_tabs()
4303                .find(|(p, _)| p.surface == from)
4304                .map(|(p, _)| p);
4305            let Some(path) = found else {
4306                break;
4307            };
4308            let tree = &space.state()[to];
4309            let destination: egui_stack::TabDestination = if tree.is_empty() {
4310                to.into()
4311            } else {
4312                let node = egui_stack::NodePath {
4313                    surface: to,
4314                    node: first_leaf(tree),
4315                };
4316                (node, egui_stack::TabInsert::Append).into()
4317            };
4318            space.state_mut().move_tab(path, destination);
4319        }
4320    }
4321}
4322
4323/// A state whose main surface holds nothing: an empty dock, a drop target
4324/// as a whole.
4325fn empty_dock() -> DockState<PanelId> {
4326    let mut dock = DockState::new(Vec::new());
4327    *dock.main_surface_mut() = egui_stack::Tree::default();
4328    dock
4329}
4330
4331/// An area's tree of tabs, splits and grids as an `egui_stack` state.
4332///
4333/// The tree is built slot by slot: its nodes are first taken as leaves in
4334/// one row, then each is given its part of the layout. A chain of splits
4335/// of one direction becomes one row or column, as egui_stack keeps them.
4336pub(crate) fn to_dock(node: &Node) -> DockState<PanelId> {
4337    let Some(any) = node.panels().first().map(|p| (*p).clone()) else {
4338        return empty_dock();
4339    };
4340    let mut dock = DockState::new(vec![any.clone()]);
4341    let tree = dock.main_surface_mut();
4342    let count = slots(node);
4343    let mut free = Vec::new();
4344    if count > 1 {
4345        let [a, b] = tree.split(
4346            NodeIndex::root(),
4347            Split::Right,
4348            0.5,
4349            egui_stack::Node::leaf(any.clone()),
4350        );
4351        free.extend([a, b]);
4352        while free.len() + 1 < count {
4353            free.push(tree.insert_child(NodeIndex::root(), 0, egui_stack::Node::leaf(any.clone())));
4354        }
4355    }
4356    let mut free = free.into_iter();
4357    build(tree, NodeIndex::root(), node, &mut free);
4358    let first = first_leaf(tree);
4359    tree.set_focused_node(first);
4360    dock
4361}
4362
4363/// The children of a split as one row or column: the splits of the same
4364/// direction under it joined, each child with its share.
4365fn run<'a>(node: &'a Node, vertical: bool, weight: f32, out: &mut Vec<(&'a Node, f32)>) {
4366    match node {
4367        Node::Split {
4368            vertical: v,
4369            ratio,
4370            a,
4371            b,
4372        } if *v == vertical => {
4373            let r = ratio.clamp(0.05, 0.95);
4374            run(a, vertical, weight * r, out);
4375            run(b, vertical, weight * (1.0 - r), out);
4376        }
4377        _ => out.push((node, weight)),
4378    }
4379}
4380
4381/// The number of egui_stack nodes a node takes.
4382fn slots(node: &Node) -> usize {
4383    match node {
4384        Node::Tabs { .. } => 1,
4385        Node::Split { vertical, .. } => {
4386            let mut children = Vec::new();
4387            run(node, *vertical, 1.0, &mut children);
4388            1 + children.iter().map(|(c, _)| slots(c)).sum::<usize>()
4389        }
4390        Node::Grid { children, .. } => 1 + children.iter().map(slots).sum::<usize>(),
4391    }
4392}
4393
4394fn build(
4395    tree: &mut egui_stack::Tree<PanelId>,
4396    at: NodeIndex,
4397    node: &Node,
4398    free: &mut impl Iterator<Item = NodeIndex>,
4399) {
4400    let mut place = |tree: &mut egui_stack::Tree<PanelId>, children: &[&Node]| {
4401        let indices: Vec<NodeIndex> = children
4402            .iter()
4403            .map(|_| free.next().expect("one slot per node"))
4404            .collect();
4405        for (&child, &index) in children.iter().zip(&indices) {
4406            build(tree, index, child, free);
4407        }
4408        indices
4409    };
4410    match node {
4411        Node::Tabs { panels, active } => {
4412            tree[at] = egui_stack::Node::leaf_with(panels.clone());
4413            if let egui_stack::Node::Leaf(leaf) = &mut tree[at] {
4414                leaf.active = egui_stack::TabIndex((*active).min(panels.len().saturating_sub(1)));
4415            }
4416        }
4417        Node::Split { vertical, .. } => {
4418            let mut children = Vec::new();
4419            run(node, *vertical, 1.0, &mut children);
4420            let (nodes, shares): (Vec<&Node>, Vec<f32>) = children.into_iter().unzip();
4421            let indices = place(tree, &nodes);
4422            let dir = if *vertical {
4423                egui_stack::LinearDir::Vertical
4424            } else {
4425                egui_stack::LinearDir::Horizontal
4426            };
4427            tree[at] = egui_stack::Node::Linear(egui_stack::LinearNode::new(dir, indices, shares));
4428        }
4429        Node::Grid {
4430            columns,
4431            col_shares,
4432            row_shares,
4433            children,
4434        } => {
4435            let nodes: Vec<&Node> = children.iter().collect();
4436            let indices = place(tree, &nodes);
4437            let mut grid = egui_stack::GridNode::new(grid_layout(*columns), indices);
4438            let fits = |shares: &[f32], n: usize| {
4439                shares.len() == n && shares.iter().all(|s| s.is_finite() && *s > 0.0)
4440            };
4441            if fits(col_shares, grid.columns()) && fits(row_shares, grid.rows()) {
4442                grid.set_shares(col_shares.clone(), row_shares.clone());
4443            }
4444            tree[at] = egui_stack::Node::Grid(grid);
4445        }
4446    }
4447}
4448
4449/// A grid's layout from its saved number of columns.
4450fn grid_layout(columns: Option<usize>) -> egui_stack::GridLayout {
4451    match columns {
4452        Some(n) if n > 0 => egui_stack::GridLayout::Columns(n),
4453        _ => egui_stack::GridLayout::Auto,
4454    }
4455}
4456
4457/// The first leaf of a tree, as drawn (the root for a tree of one).
4458fn first_leaf(tree: &egui_stack::Tree<PanelId>) -> NodeIndex {
4459    let mut at = NodeIndex::root();
4460    while at.0 < tree.len()
4461        && let Some(&first) = tree[at].children().first()
4462    {
4463        at = first;
4464    }
4465    at
4466}
4467
4468/// An area's tree with the row, column or grid holding `panel`'s group
4469/// laid out again; `None` when the group is alone in the area.
4470fn arrange(node: &Node, panel: &PanelId, how: Arrangement) -> Option<Node> {
4471    let mut dock = to_dock(node);
4472    let tree = dock.main_surface_mut();
4473    let (leaf, _) = tree.find_tab(panel)?;
4474    let container = tree.parent(leaf)?;
4475    let done = match how {
4476        Arrangement::Grid(columns) => tree.arrange_as_grid(container, grid_layout(columns)),
4477        Arrangement::Row => tree.arrange_as_linear(container, egui_stack::LinearDir::Horizontal),
4478        Arrangement::Column => tree.arrange_as_linear(container, egui_stack::LinearDir::Vertical),
4479    };
4480    done.then(|| from_dock(&dock)).flatten()
4481}
4482
4483/// The tree a dock shows now; `None` when it holds no panel.
4484pub(crate) fn from_dock(dock: &DockState<PanelId>) -> Option<Node> {
4485    read(dock.main_surface(), NodeIndex::root())
4486}
4487
4488fn read(tree: &egui_stack::Tree<PanelId>, at: NodeIndex) -> Option<Node> {
4489    if at.0 >= tree.len() {
4490        return None;
4491    }
4492    match &tree[at] {
4493        egui_stack::Node::Leaf(leaf) => (!leaf.tabs.is_empty()).then(|| Node::Tabs {
4494            panels: leaf.tabs.clone(),
4495            active: leaf.active.0.min(leaf.tabs.len() - 1),
4496        }),
4497        egui_stack::Node::Linear(linear) => {
4498            let vertical = linear.dir == egui_stack::LinearDir::Vertical;
4499            let children: Vec<(Node, f32)> = (linear.children().iter().zip(linear.shares()))
4500                .filter_map(|(&c, &share)| read(tree, c).map(|n| (n, share.max(0.0))))
4501                .collect();
4502            chain(vertical, children)
4503        }
4504        egui_stack::Node::Grid(grid) => {
4505            let all = grid.children().len();
4506            let mut children: Vec<Node> = grid
4507                .children()
4508                .iter()
4509                .filter_map(|&c| read(tree, c))
4510                .collect();
4511            match children.len() {
4512                0 => None,
4513                1 => children.pop(),
4514                n => {
4515                    // Children gone (their panels closed): even shares.
4516                    let kept = n == all;
4517                    Some(Node::Grid {
4518                        columns: match grid.layout {
4519                            egui_stack::GridLayout::Columns(n) => Some(n),
4520                            _ => None,
4521                        },
4522                        col_shares: if kept {
4523                            grid.col_shares().to_vec()
4524                        } else {
4525                            Vec::new()
4526                        },
4527                        row_shares: if kept {
4528                            grid.row_shares().to_vec()
4529                        } else {
4530                            Vec::new()
4531                        },
4532                        children,
4533                    })
4534                }
4535            }
4536        }
4537        _ => None,
4538    }
4539}
4540
4541/// A row or column as splits nested on their second side.
4542fn chain(vertical: bool, mut children: Vec<(Node, f32)>) -> Option<Node> {
4543    match children.len() {
4544        0 => None,
4545        1 => children.pop().map(|(n, _)| n),
4546        _ => {
4547            let (a, share) = children.remove(0);
4548            let rest: f32 = children.iter().map(|(_, s)| s).sum();
4549            let ratio = if share + rest > 0.0 {
4550                share / (share + rest)
4551            } else {
4552                0.5
4553            };
4554            let b = chain(vertical, children)?;
4555            Some(Node::Split {
4556                vertical,
4557                ratio,
4558                a: Box::new(a),
4559                b: Box::new(b),
4560            })
4561        }
4562    }
4563}
4564
4565/// Draws the docked areas in `ui` (side and bottom areas, the centre
4566/// takes what is left), each area's dock where the area is laid out;
4567/// while a tab drags, the closed areas and those drawn bare as drop
4568/// targets too. A tab dropped in another area is then moved through the
4569/// `workbench.move` step.
4570pub(crate) fn show(app: &AppHandle, ui: &mut Ui) {
4571    // Zen mode on a panel of the main window: that panel alone, the
4572    // layout not drawn (and not changed).
4573    let alone = app.workbench_mut().zen_in_main();
4574    if let Some(panel) = alone {
4575        {
4576            let mut wb = app.workbench_mut();
4577            wb.content = ui.max_rect();
4578            wb.rects.clear();
4579            wb.bars.clear();
4580            wb.bare.clear();
4581        }
4582        app.set_drawing_areas(true);
4583        show_alone(app, ui, &panel);
4584        app.set_drawing_areas(false);
4585        return;
4586    }
4587    let ctx = ui.ctx().clone();
4588    let across = ui.max_rect().width();
4589    let bounds = app.shell_bounds();
4590    let (areas, sizes, before) = {
4591        let mut wb = app.workbench_mut();
4592        wb.project();
4593        wb.content = ui.max_rect();
4594        wb.rects.clear();
4595        wb.bars.clear();
4596        wb.bare.clear();
4597        wb.landing = None;
4598        wb.landing_rect = None;
4599        // Found again by this pass's docks.
4600        wb.window_drop = None;
4601        wb.window_outlines.clear();
4602        // A tab dragged: the layout before a drop, to put it back if the
4603        // move is vetoed.
4604        let before = wb.dragged(&ctx).map(|(dragged, from, _)| {
4605            wb.read_back();
4606            (dragged, from, wb.layout.areas.clone())
4607        });
4608        let sizes: BTreeMap<Area, (f32, f32, f32)> = Area::ALL
4609            .into_iter()
4610            .map(|a| (a, wb.area_sizes(&wb.panels_in(a), &bounds, across)))
4611            .collect();
4612        (wb.areas(), sizes, before)
4613    };
4614    let centre_min = app.centre_min_size().map(|m| m.resolve(across));
4615    let flipped = crate::layout_controls::side_bar_position(app).flipped();
4616    let zen = {
4617        let mut wb = app.workbench_mut();
4618        wb.flipped = flipped;
4619        wb.main_zen()
4620    };
4621    app.set_drawing_areas(true);
4622    // The activity bar: a zone of the layout, beside the primary side bar
4623    // as VS Code's, of a fixed breadth (no sash) and refusing drops.
4624    let activity = !zen && app.zone_has_blocks(&crate::zones::ACTIVITY_BAR);
4625    {
4626        // Zones that are not docks refuse drops, before the docks resolve
4627        // the drag.
4628        let mut wb = app.workbench_mut();
4629        let zones = std::mem::take(&mut wb.no_drop);
4630        if let Some(space) = wb.space.as_mut() {
4631            space.no_drop_zones(zones);
4632        }
4633    }
4634    let (folded, over) = {
4635        let wb = app.workbench_mut();
4636        (wb.layout.folded.clone(), wb.layout.over.clone())
4637    };
4638    let kit = Kit::of(&ctx);
4639    let mut saved = shell_sizes(app, &ctx, ui.scope_id());
4640    // Side areas lying over the centre, open next to their strip: the
4641    // layout keeps their strip in the flow and draws them over the centre
4642    // (`ZoneState::over`), until their grip folds them.
4643    let open: BTreeSet<Area> = over
4644        .iter()
4645        .copied()
4646        .filter(|a| matches!(a, Area::StartSide | Area::EndSide) && !folded.contains(a))
4647        .collect();
4648    let shown_now: BTreeSet<Area> = Area::ALL
4649        .into_iter()
4650        .filter(|a| !zen && areas.contains(a) && visible_in(app, *a))
4651        .collect();
4652    let leaf = |area: Area| -> Zone {
4653        let name = area_name(area);
4654        let zone = Zone::leaf(name, Content::Dock(name.to_owned()));
4655        if area == Area::Center {
4656            return zone.with(|c| c.grow = true);
4657        }
4658        let (min, default, max) = sizes[&area];
4659        let min = min.max(48.0);
4660        let max = max.max(min);
4661        let default = if default > 0.0 {
4662            default
4663        } else {
4664            area_default(area, default).max(min)
4665        };
4666        let side = matches!(area, Area::StartSide | Area::EndSide);
4667        let strip = folded.contains(&area) || (side && over.contains(&area));
4668        zone.with(|c| {
4669            c.min = Some(Size::Points(min));
4670            c.max = max.is_finite().then_some(Size::Points(max));
4671            c.default = Some(Size::Points(default.clamp(min, max)));
4672            // A side area's sash dragged past half its least size folds it
4673            // to its strip, as in VS Code and JetBrains' IDEs.
4674            if side {
4675                c.fold = Fold::ToStrip;
4676            }
4677        })
4678        .with_state(|s| {
4679            s.size = saved.get(name).copied();
4680            if !shown_now.contains(&area) {
4681                s.hidden = true;
4682            } else if strip && side && open.contains(&area) {
4683                s.over = true;
4684            } else if strip && side {
4685                s.folded = true;
4686            } else if strip {
4687                // A folded bottom area leaves no strip.
4688                s.hidden = true;
4689            }
4690        })
4691    };
4692    let areas_tree = shell_tree(&panel_alignment(app).order(), flipped, centre_min, &leaf);
4693    let mut layout = ZoneLayout::new(with_activity_bar(
4694        areas_tree,
4695        flipped,
4696        activity.then(|| activity_bar_width(&ctx)),
4697    ));
4698    // One strip breadth for the layout: the widest folded side's.
4699    let strip = [Area::StartSide, Area::EndSide]
4700        .into_iter()
4701        .filter(|a| shown_now.contains(a) && (folded.contains(a) || over.contains(a)))
4702        .map(|a| strip_width(app, &ctx, &kit, a))
4703        .fold(kit.area_strip.data.width.max(1.0), f32::max);
4704    let mut style = LayoutStyle::from_egui(ui.style());
4705    style.strip = strip;
4706    style.key_step = SASH_STEP;
4707    style.large_key_step = SASH_STEP * 4.0;
4708    style.sash_grab = 2.0 * ctx.global_style().interaction.resize_grab_radius_side;
4709    style.sash_width = ui.visuals().widgets.noninteractive.bg_stroke.width.max(1.0);
4710    // As in VS Code and JetBrains' IDEs: a sash does not snap to sizes, a
4711    // side area folds by drag and a folded one drags out of its strip.
4712    style.snap = 0.0;
4713    style.strip_drag = true;
4714    let painter = ShellPainter {
4715        kit: &kit,
4716        open: &open,
4717        flipped,
4718    };
4719    // The flyout, while its panel is in a folded side area drawn with its
4720    // strip (the layout closes it otherwise), at its width.
4721    let flyout = app.workbench_mut().flyout.clone();
4722    // Another panel's flyout held last pass leaves the overlay stack
4723    // now: closed later, as no longer shown, it would close the new one
4724    // opened above it.
4725    let held = app.workbench_mut().flyout_held.take();
4726    if let Some(old) = held
4727        && flyout.as_ref() != Some(&old)
4728    {
4729        app.close_overlay(
4730            &ctx,
4731            Id::unique(flyout_overlay(&old)),
4732            egui_pop_core::overlay::Closing::Owner,
4733        );
4734    }
4735    let flyout = flyout.and_then(|panel| {
4736        let area = app.workbench_mut().layout.area_of(&panel)?;
4737        let (width, ..) = flyout_width(app, &ctx, area, &panel, strip)?;
4738        layout.flyouts.insert(panel.as_str().to_owned(), width);
4739        Some((panel, area))
4740    });
4741    let mut viewer = ShellViewer {
4742        app,
4743        ctx: &ctx,
4744        kit: &kit,
4745        open: &open,
4746        areas: &areas,
4747        flipped,
4748        strip,
4749        flyout: flyout.as_ref().map(|(p, _)| p.clone()),
4750        flyout_closed: false,
4751    };
4752    let rect = ui.available_rect_before_wrap();
4753    let mut inner = ui.new_child(
4754        egui::UiBuilder::new()
4755            .id_salt("egui_pop.shell")
4756            .max_rect(rect),
4757    );
4758    // A press on an overlay of the stack (a combo box's list or a context
4759    // menu opened in the flyout, a dialog above it) is not a press away:
4760    // the stack closes what it covers. Escape is the stack's too, the top
4761    // overlay first.
4762    let in_overlay = |pos: Pos2, layer: Option<egui::LayerId>| {
4763        egui_pop_core::overlay::hit_at(&ctx, pos, layer).is_some()
4764    };
4765    let laid = LayoutArea::new(&mut layout)
4766        .id(shell_id())
4767        .labels(shell_labels(&ctx))
4768        .style(style)
4769        .painter(&painter)
4770        .flyout(
4771            flyout
4772                .as_ref()
4773                .map(|(p, area)| Flyout::new(p.as_str(), area_name(*area))),
4774        )
4775        .flyout_dismiss(Dismiss::OUTSIDE_PRESS)
4776        .over_dismiss(Dismiss::NEVER)
4777        .inside(&in_overlay)
4778        // The zones lying over and the flyout at their rank: under the
4779        // overlays (cards, toasts) and the menus, whatever was clicked.
4780        .sublayer_of(egui_pop_core::layers::base(
4781            &ctx,
4782            egui_pop_core::layers::Rank::Over,
4783        ))
4784        .show_inside(&mut inner, &mut viewer);
4785    let flyout_closed = viewer.flyout_closed;
4786    // The shell covers `ui` without moving its cursor past the window's
4787    // bottom: past it (plus the item spacing), what the pass still
4788    // allocates in `ui` (the live regions, the overlay zones) would grow
4789    // `ui` below the window, and a frame drawn around `ui` with it.
4790    ui.expand_to_include_rect(rect);
4791    for zone in &laid.zones {
4792        let Some(area) = area_from(&zone.name.0) else {
4793            continue;
4794        };
4795        if zone.strip.is_some() {
4796            name_grip(&ctx, area, &zone.name.0, open.contains(&area));
4797        }
4798        if matches!(zone.shown, Shown::Open | Shown::Over) {
4799            app.workbench_mut().rects.insert(area, zone.rect);
4800            if area != Area::Center {
4801                grip(&ctx, &kit, area, zone.rect, flipped);
4802            }
4803        }
4804    }
4805    // What the user changed: sizes kept, folds asked through their step
4806    // (a plugin may veto; the layout is built again from the workbench's
4807    // state each pass, so a veto puts it back).
4808    let mut resized = false;
4809    // As egui kept a side panel's size from its first pass on, an open
4810    // area keeps the size it was first shown at: a panel made active
4811    // later with another default size does not resize it. An area its
4812    // least size widened keeps that size once the least goes.
4813    for zone in laid.zones.iter().filter(|z| z.shown == Shown::Open) {
4814        let Some(area) = area_from(&zone.name.0).filter(|a| *a != Area::Center) else {
4815            continue;
4816        };
4817        let along = if area == Area::Bottom {
4818            zone.rect.height()
4819        } else {
4820            zone.rect.width()
4821        };
4822        let kept = saved.get(&zone.name.0).copied();
4823        // What it would have without its least size: the size kept, else
4824        // its default (not raised to the least).
4825        let (_, default, _) = sizes[&area];
4826        let wanted = kept.unwrap_or_else(|| area_default(area, default));
4827        let size = if along > wanted + 0.5 && along <= zone.least + 0.5 {
4828            along
4829        } else if kept.is_none() {
4830            // Its default as the layout took it (within its bounds).
4831            layout
4832                .zone(&zone.name.0)
4833                .and_then(|z| z.constraints.default)
4834                .map_or(along, |d| d.points(0.0))
4835        } else {
4836            continue;
4837        };
4838        saved.insert(zone.name.0.clone(), size);
4839        resized = true;
4840    }
4841    // What the user changed, as egui_stack says it on the bus
4842    // (`stack.layout.changed`, said as the space is bound to the layout).
4843    let events = shell_events(app, &laid, &layout);
4844    for event in &events {
4845        match event {
4846            ShellEvent::Resized { zone, size } => {
4847                // An area lying over the centre, from where the pointer is on
4848                // its edge rather than from the layout's sum of moves, which
4849                // a pass egui discards and runs again would count twice.
4850                let lying = laid
4851                    .zones
4852                    .iter()
4853                    .find(|z| z.name == *zone && z.shown == Shown::Over);
4854                let size = lying
4855                    .and_then(|z| {
4856                        let area = area_from(&zone.0)?;
4857                        let edge = shell_id().with(("over", &zone.0)).with("edge");
4858                        let at = ctx.read_response(edge)?.interact_pointer_pos()?;
4859                        let width = if on_left(area, flipped) {
4860                            at.x - z.rect.left()
4861                        } else {
4862                            z.rect.right() - at.x
4863                        };
4864                        Some(width.clamp(z.least, z.most.max(z.least)))
4865                    })
4866                    .unwrap_or(*size);
4867                saved.insert(zone.0.clone(), size);
4868                resized = true;
4869            }
4870            ShellEvent::Reset { zone } => {
4871                resized |= saved.remove(&zone.0).is_some();
4872            }
4873            ShellEvent::Folded { zone } => {
4874                // Its sash dragged past its fold point: it keeps the size it
4875                // had before the drag, not the least size the drag reached.
4876                let Some(area) = area_from(&zone.0) else {
4877                    continue;
4878                };
4879                if let Some(size) = layout.zone(&zone.0).and_then(|z| z.state.size) {
4880                    saved.insert(zone.0.clone(), size);
4881                    resized = true;
4882                }
4883                app.fold_area(area, true);
4884            }
4885            ShellEvent::Unfolded { zone } => {
4886                let Some(area) = area_from(&zone.0) else {
4887                    continue;
4888                };
4889                let edge = shell_id().with(("strip_edge", &zone.0));
4890                let dragged = ctx.read_response(edge).is_some_and(|r| r.drag_stopped());
4891                if dragged {
4892                    // Dragged out of its strip: an area lying over the
4893                    // centre is already open; one beside opens at the size
4894                    // it was dragged to.
4895                    if open.contains(&area) {
4896                        continue;
4897                    }
4898                    let size = layout.zone(&zone.0).and_then(|z| z.state.size);
4899                    if let Some(size) = size.filter(|_| !over.contains(&area)) {
4900                        saved.insert(zone.0.clone(), size);
4901                        resized = true;
4902                    }
4903                }
4904                app.fold_area(area, open.contains(&area));
4905            }
4906            ShellEvent::FlyoutResized { key, size } => {
4907                // The width follows the edge for now, and is saved through
4908                // its step once the edge is let go (below). From where the
4909                // pointer is, not from the layout's sum of moves, which a
4910                // pass egui discards and runs again would count twice.
4911                let Some((panel, area)) = flyout.as_ref().filter(|(p, _)| p.as_str() == key) else {
4912                    continue;
4913                };
4914                let edge = shell_id().with(("flyout", panel.as_str())).with("edge");
4915                let at = ctx
4916                    .read_response(edge)
4917                    .and_then(|r| r.interact_pointer_pos());
4918                let width = match (at, laid.flyout) {
4919                    (Some(at), Some(rect)) if on_left(*area, flipped) => at.x - rect.left(),
4920                    (Some(at), Some(rect)) => rect.right() - at.x,
4921                    _ => *size,
4922                };
4923                if let Some((_, min, max)) = flyout_width(app, &ctx, *area, panel, strip) {
4924                    let live = flyout_live_id(panel);
4925                    ctx.data_mut(|d| d.insert_temp(live, width.clamp(min, max)));
4926                }
4927            }
4928            ShellEvent::FlyoutClosed { key } => {
4929                let Some((panel, area)) = flyout.as_ref().filter(|(p, _)| p.as_str() == key) else {
4930                    continue;
4931                };
4932                let open_now = app.workbench_mut().flyout.as_ref() == Some(panel);
4933                if !open_now || flyout_closed {
4934                    continue;
4935                }
4936                if laid.flyout.is_none() {
4937                    // Its area is no longer folded with a strip: it is gone.
4938                    app.workbench_mut().flyout = None;
4939                    continue;
4940                }
4941                // A press away, or its strip's grip, which also unfolds the
4942                // area (the panel then shows in it).
4943                app.change_workbench(Change::Flyout(panel.clone(), false));
4944                let grip = shell_id().with(("grip", area_name(*area)));
4945                if ctx.read_response(grip).is_some_and(|r| r.clicked()) {
4946                    app.fold_area(*area, false);
4947                }
4948            }
4949        }
4950    }
4951    if let Some((panel, _)) = &flyout {
4952        // The flyout's edge let go: its width is saved, through its step.
4953        let live = flyout_live_id(panel);
4954        let edge = shell_id().with(("flyout", panel.as_str())).with("edge");
4955        let dragging = ctx.read_response(edge).is_some_and(|r| r.dragged());
4956        if !dragging && let Some(width) = ctx.data_mut(|d| d.remove_temp::<f32>(live)) {
4957            app.change_workbench(Change::FlyoutSize(panel.clone(), width));
4958        }
4959    }
4960    if flyout_closed && let Some((panel, _)) = &flyout {
4961        // Closed by the overlay stack: Escape, or a press away.
4962        app.change_workbench(Change::Flyout(panel.clone(), false));
4963    }
4964    if resized {
4965        ctx.data_mut(|d| d.insert_persisted(sizes_id(), saved.clone()));
4966        app.workbench_mut().shell_sizes = Some(saved.clone());
4967    }
4968    {
4969        let mut wb = app.workbench_mut();
4970        let drawn = laid.flyout.filter(|_| wb.flyout.is_some());
4971        wb.flyout_rect = drawn;
4972        wb.flyout_held = drawn.and(wb.flyout.clone());
4973    }
4974    // A tab dragged here, or from a detached window over this one: the
4975    // closed and bare areas take it too.
4976    let remote = (app.workbench_mut().space.as_ref())
4977        .and_then(|s| s.dragging())
4978        .is_some_and(|d| d.source != ctx.viewport_id());
4979    if before.is_some() || remote {
4980        drop_targets(app, ui, zen);
4981    }
4982    app.set_drawing_areas(false);
4983    if let Some(space) = app.workbench_mut().space.as_mut() {
4984        settle_bare_drops(space);
4985    }
4986    if !zen {
4987        crate::palettes::show(app, &ctx);
4988    }
4989    track_drag(app, &ctx, before);
4990    publish_hint(app, &ctx);
4991}
4992
4993/// While a tab drags, the areas a dock does not draw as targets: a closed
4994/// side or bottom area along the areas' edge (its empty dock), an area
4995/// drawn bare over its whole rect (its bare target, where the tab joins
4996/// its tabs). Drawn last, so they win over the docks beneath, and the
4997/// closed areas' bands after the bare areas, so they win at the edges.
4998fn drop_targets(app: &AppHandle, ui: &mut Ui, zen: bool) {
4999    let mut targets: Vec<(&'static str, Rect)> = {
5000        let wb = app.workbench_mut();
5001        Area::ALL
5002            .into_iter()
5003            .filter(|a| !zen || *a == Area::Center)
5004            .filter_map(|area| {
5005                if wb.panels_in(area).is_empty() {
5006                    let rect = match area {
5007                        Area::Center => wb.rects.get(&area).copied()?,
5008                        _ => wb.hint_rect(area),
5009                    };
5010                    Some((area_name(area), rect))
5011                } else if wb.bare.contains(&area) {
5012                    Some((bare_target(area), *wb.rects.get(&area)?))
5013                } else {
5014                    None
5015                }
5016            })
5017            .collect()
5018    };
5019    targets.sort_by_key(|(dock, _)| !dock.ends_with(".bare"));
5020    let ctx = ui.ctx().clone();
5021    let kit = Kit::of(&ctx);
5022    let mut style = dock_style(ui.style(), &kit);
5023    if let Some(space) = app.workbench_mut().space.as_ref() {
5024        from_elsewhere(&mut style, space, &ctx);
5025    }
5026    let prepared = HashMap::new();
5027    for (dock, rect) in targets {
5028        let Some(mut space) = app.workbench_mut().take_space() else {
5029            return;
5030        };
5031        let mut target = ui.new_child(
5032            egui::UiBuilder::new()
5033                .id_salt(("egui_pop.drop_target", dock))
5034                .max_rect(rect),
5035        );
5036        let seen = Mutex::new(None);
5037        let painter = AreaPainter::new(&kit, false, &seen);
5038        let mut viewer = Viewer {
5039            app,
5040            prepared: &prepared,
5041            eject: false,
5042            ejected: None,
5043            // An empty drop target: no group to open a panel in.
5044            groups: Vec::new(),
5045            added: None,
5046        };
5047        space.state_mut().translations = dock_translations(&ctx);
5048        let area = DockArea::dock(&mut space, dock)
5049            .style(style.clone())
5050            .painter(&painter);
5051        group_gestures(area, app, &ctx).show_inside(&mut target, &mut viewer);
5052        let mut wb = app.workbench_mut();
5053        wb.put_space(space);
5054        wb.note_landing(seen, ctx.cumulative_pass_nr());
5055    }
5056}
5057
5058/// A folded side area's strip: the layout draws it, its grip a button
5059/// that unfolds the area (or folds it back while it lies over the centre);
5060/// the kit paints it (`ShellPainter`). Below the grip, an icon per panel
5061/// ([`strip_icon`]), the strip widened to hold them, unless the strip is
5062/// bare ([`AppHandle::bare_strip`]): `rect` is the whole strip.
5063fn strip_icons(app: &AppHandle, ui: &mut Ui, kit: &Kit, area: Area, rect: Rect, open: bool) {
5064    let grip = kit.area_strip.data.width.max(1.0);
5065    let panels = strip_panels(app, area);
5066    let t = egui_pop_core::theme::Tokens::of(ui.ctx());
5067    let cell = t.size.icon_inline + 2.0 * t.space.s;
5068    // The panels' icons, under the glyph, in tab order.
5069    let shown: Vec<PanelId> = {
5070        let wb = app.workbench_mut();
5071        wb.layout.active_in(area).into_iter().cloned().collect()
5072    };
5073    let mut top = rect.top() + grip * 2.5;
5074    for p in &panels {
5075        let cell_rect =
5076            Rect::from_min_size(egui::pos2(rect.left(), top), egui::vec2(rect.width(), cell));
5077        if cell_rect.bottom() > rect.bottom() {
5078            break;
5079        }
5080        strip_icon(
5081            app,
5082            ui,
5083            kit,
5084            area,
5085            p,
5086            cell_rect,
5087            open,
5088            open && shown.contains(p),
5089        );
5090        top += cell + t.space.xs;
5091    }
5092}
5093
5094/// A folded side area's strip breadth: the kit's, widened to an icon's
5095/// cell when it shows its panels' icons.
5096fn strip_width(app: &AppHandle, ctx: &egui::Context, kit: &Kit, area: Area) -> f32 {
5097    let grip = kit.area_strip.data.width.max(1.0);
5098    if strip_panels(app, area).is_empty() {
5099        return grip;
5100    }
5101    let t = egui_pop_core::theme::Tokens::of(ctx);
5102    grip.max(t.size.icon_inline + 2.0 * t.space.s)
5103}
5104
5105/// A change of the shell's layout the workbench follows: a zone resized,
5106/// reset, folded or unfolded, a flyout resized or closed.
5107#[derive(Clone, Debug)]
5108enum ShellEvent {
5109    Resized { zone: ZoneName, size: f32 },
5110    Reset { zone: ZoneName },
5111    Folded { zone: ZoneName },
5112    Unfolded { zone: ZoneName },
5113    FlyoutResized { key: String, size: f32 },
5114    FlyoutClosed { key: String },
5115}
5116
5117impl ShellEvent {
5118    /// A change said on the bus, its sizes read from the layout it was
5119    /// made in; `None` for one the shell does not follow.
5120    fn of_change(change: &egui_stack::bus::LayoutChange, layout: &ZoneLayout) -> Option<Self> {
5121        use egui_stack::bus::Change;
5122        let name = change.zone.clone()?;
5123        Some(match change.change {
5124            Change::Resized => ShellEvent::Resized {
5125                size: layout.zone(&name)?.state.size?,
5126                zone: ZoneName(name),
5127            },
5128            Change::Reset => ShellEvent::Reset {
5129                zone: ZoneName(name),
5130            },
5131            Change::Folded => ShellEvent::Folded {
5132                zone: ZoneName(name),
5133            },
5134            Change::Unfolded => ShellEvent::Unfolded {
5135                zone: ZoneName(name),
5136            },
5137            Change::FlyoutResized => ShellEvent::FlyoutResized {
5138                size: *layout.flyouts.get(&name)?,
5139                key: name,
5140            },
5141            Change::FlyoutClosed => ShellEvent::FlyoutClosed { key: name },
5142            _ => return None,
5143        })
5144    }
5145
5146    /// A change as the layout pass reported it.
5147    fn of_event(event: &LayoutEvent) -> Option<Self> {
5148        Some(match event {
5149            LayoutEvent::Resized { zone, size } => ShellEvent::Resized {
5150                zone: zone.clone(),
5151                size: *size,
5152            },
5153            LayoutEvent::Reset { zone } => ShellEvent::Reset { zone: zone.clone() },
5154            LayoutEvent::Folded { zone } => ShellEvent::Folded { zone: zone.clone() },
5155            LayoutEvent::Unfolded { zone } => ShellEvent::Unfolded { zone: zone.clone() },
5156            LayoutEvent::FlyoutResized { key, size } => ShellEvent::FlyoutResized {
5157                key: key.clone(),
5158                size: *size,
5159            },
5160            LayoutEvent::FlyoutClosed { key } => ShellEvent::FlyoutClosed { key: key.clone() },
5161            _ => return None,
5162        })
5163    }
5164}
5165
5166/// Binds the space to the shell's layout, as laid out this pass (the
5167/// zones holding no dock refuse a tab's drop on the next pass), and reads
5168/// what the user changed: egui_stack says it on the bus as it is bound
5169/// (`stack.layout.changed`, [`STACK_LAYOUT`] keeps it), or, when the
5170/// space is not there to say it, from the pass itself.
5171fn shell_events(
5172    app: &AppHandle,
5173    laid: &egui_stack::layout::Laid,
5174    layout: &ZoneLayout,
5175) -> Vec<ShellEvent> {
5176    app.0.stack_changes.borrow_mut().clear();
5177    // Taken out while bound: a listener may read the workbench.
5178    let space = app.workbench_mut().take_space();
5179    let said = match space {
5180        Some(mut space) => {
5181            space.bind(laid);
5182            let said = space.bus().is_some();
5183            app.workbench_mut().put_space(space);
5184            said
5185        }
5186        None => false,
5187    };
5188    let changes = std::mem::take(&mut *app.0.stack_changes.borrow_mut());
5189    if !said {
5190        return laid
5191            .events
5192            .iter()
5193            .filter_map(ShellEvent::of_event)
5194            .collect();
5195    }
5196    changes
5197        .iter()
5198        .filter_map(|change| ShellEvent::of_change(change, layout))
5199        .collect()
5200}
5201
5202/// The layout's labels, translated: its sashes ("Resize the start side
5203/// bar") and strip grips ("Unfold ...", "Fold ..."), `{zone}` being the
5204/// area's text ([`ShellViewer`]'s `title`).
5205fn shell_labels(ctx: &egui::Context) -> egui_stack::Labels {
5206    let template = |key| strings::tr_args(ctx, key, &[("area", "{zone}")]);
5207    let mut labels = egui_stack::Labels::default();
5208    labels.resize_zone = template(&txt::AREA_RESIZE).into();
5209    labels.unfold_zone = template(&txt::WORKBENCH_UNFOLD).into();
5210    labels.fold_zone = template(&txt::WORKBENCH_FOLD).into();
5211    labels
5212}
5213
5214/// A strip's grip's tooltip: its name ("Unfold the start side bar",
5215/// "Fold ..." while it lies over the centre), which the layout gives it
5216/// for assistive technology ([`shell_labels`]).
5217fn name_grip(ctx: &egui::Context, area: Area, zone: &str, open: bool) {
5218    let name = strings::tr_args(
5219        ctx,
5220        if open {
5221            &txt::WORKBENCH_FOLD
5222        } else {
5223            &txt::WORKBENCH_UNFOLD
5224        },
5225        &[("area", &area_text(ctx, area))],
5226    );
5227    let id = shell_id().with(("grip", zone));
5228    if let Some(r) = ctx.read_response(id) {
5229        r.on_hover_text(name);
5230    }
5231}
5232
5233/// The shell's layout: the side and bottom areas around the centre, each
5234/// a zone holding the area's dock. `order` is the order the areas are
5235/// peeled off the window ([`PanelAlignment::order`]): an area peeled
5236/// earlier spans the whole height (a side bar) or width (the bottom). The
5237/// rest grows; the centre's least width holds against the side areas.
5238fn shell_tree(
5239    order: &[Area],
5240    flipped: bool,
5241    centre_min: Option<f32>,
5242    leaf: &dyn Fn(Area) -> Zone,
5243) -> Zone {
5244    let Some((&first, rest)) = order.split_first() else {
5245        return leaf(Area::Center);
5246    };
5247    let side = matches!(first, Area::StartSide | Area::EndSide);
5248    let inner = shell_tree(rest, flipped, centre_min, leaf).with(|c| {
5249        c.grow = true;
5250        if side && let Some(least) = centre_min {
5251            c.min = Some(Size::Points(least));
5252        }
5253    });
5254    let name = format!("around.{}", area_name(first));
5255    if side {
5256        let children = if on_left(first, flipped) {
5257            vec![leaf(first), inner]
5258        } else {
5259            vec![inner, leaf(first)]
5260        };
5261        Zone::split(name, Dir::Horizontal, children)
5262    } else {
5263        Zone::split(name, Dir::Vertical, vec![inner, leaf(first)])
5264    }
5265}
5266
5267/// The activity bar's zone (`Content::App`) and the shell's root, holding
5268/// it beside the areas' tree: on the primary side bar's side, `width`
5269/// wide (its least and largest size, so it has no sash), refusing drops;
5270/// hidden when `width` is `None`.
5271fn with_activity_bar(areas: Zone, flipped: bool, width: Option<f32>) -> Zone {
5272    let bar = Zone::leaf(ACTIVITY_ZONE, Content::App)
5273        .with(|c| {
5274            let width = Size::Points(width.unwrap_or(0.0));
5275            c.min = Some(width);
5276            c.max = Some(width);
5277            c.default = Some(width);
5278            c.drops = Drops::Refuse;
5279        })
5280        .with_state(|s| s.hidden = width.is_none());
5281    let areas = areas.with(|c| c.grow = true);
5282    let children = if flipped {
5283        vec![areas, bar]
5284    } else {
5285        vec![bar, areas]
5286    };
5287    Zone::split("shell", Dir::Horizontal, children)
5288}
5289
5290/// The activity bar's zone's name.
5291const ACTIVITY_ZONE: &str = "activity_bar";
5292
5293/// The activity bar's breadth: an icon and its padding.
5294fn activity_bar_width(ctx: &egui::Context) -> f32 {
5295    let t = egui_pop_core::theme::Tokens::of(ctx);
5296    t.size.icon_panel + 2.0 * t.space.s + 2.0 * t.space.xs
5297}
5298
5299/// Draws the activity bar in its zone, as the egui side panel it was:
5300/// the side panel's frame, its line on the edge facing the areas.
5301fn activity_bar(app: &AppHandle, ui: &mut Ui, flipped: bool) {
5302    let rect = ui.max_rect();
5303    let stroke = ui.visuals().widgets.noninteractive.bg_stroke;
5304    let line = stroke.width.round() as i8;
5305    let mut frame = egui::Frame::side_top_panel(ui.style());
5306    if flipped {
5307        frame.outer_margin.left = frame.outer_margin.left.saturating_add(line);
5308    } else {
5309        frame.outer_margin.right = frame.outer_margin.right.saturating_add(line);
5310    }
5311    let mut panel = ui.new_child(
5312        egui::UiBuilder::new()
5313            .id_salt("egui_pop.activity_bar")
5314            .max_rect(rect)
5315            .layout(egui::Layout::top_down(egui::Align::Min)),
5316    );
5317    let least = (rect.width() - frame.total_margin().sum().x).max(0.0);
5318    frame.show(&mut panel, |ui| {
5319        ui.set_min_height(ui.max_rect().height());
5320        ui.set_min_width(least);
5321        let region = focus::Region::new("activityBar", RANK_ACTIVITY_BAR);
5322        focus::region(ui, &region, |ui| {
5323            // One Tab stop, Up and Down between its items.
5324            let axis = egui_pop_core::tab::Axis::Vertical;
5325            egui_pop_core::tab::roving(ui, "activityBar", axis, |ui| {
5326                app.show_zone(ui, &crate::zones::ACTIVITY_BAR);
5327            });
5328        });
5329    });
5330    if stroke.width > 0.0 {
5331        // Just outside the frame, in the room kept for it.
5332        let margin = f32::from(line);
5333        let x = if flipped {
5334            rect.left() + margin - 0.5 * stroke.width
5335        } else {
5336            rect.right() - margin + 0.5 * stroke.width
5337        };
5338        ui.painter().vline(x, rect.y_range(), stroke);
5339    }
5340}
5341
5342/// An area's default size: its panels' (`default`, 0 when none says),
5343/// else 240 for a side area and 200 for the bottom one.
5344fn area_default(area: Area, default: f32) -> f32 {
5345    if default > 0.0 {
5346        default
5347    } else if area == Area::Bottom {
5348        200.0
5349    } else {
5350        240.0
5351    }
5352}
5353
5354/// The shell's layout's id: its sashes' and strips' ids derive from it.
5355fn shell_id() -> Id {
5356    Id::unique("egui_pop.shell")
5357}
5358
5359/// Where the areas' sizes the user gave are kept in egui's memory (saved
5360/// with it, as egui's side panels kept theirs).
5361fn sizes_id() -> Id {
5362    Id::unique("egui_pop.shell.sizes")
5363}
5364
5365/// The sizes the user gave the side and bottom areas, by zone name: kept
5366/// in the workbench, loaded once from egui's memory.
5367fn shell_sizes(app: &AppHandle, ctx: &egui::Context, scope: Id) -> BTreeMap<String, f32> {
5368    if let Some(sizes) = app.workbench_mut().shell_sizes.clone() {
5369        return sizes;
5370    }
5371    let saved = ctx.data_mut(|d| d.get_persisted::<BTreeMap<String, f32>>(sizes_id()));
5372    let sizes = migrate_sizes(saved, |area| old_panel_size(ctx, scope, area));
5373    app.workbench_mut().shell_sizes = Some(sizes.clone());
5374    sizes
5375}
5376
5377/// The areas' sizes as saved, completed by what the areas' former egui
5378/// panels kept (`old`), for a session saved before the shell was laid out
5379/// by egui_stack: an area keeps the width it had.
5380fn migrate_sizes(
5381    saved: Option<BTreeMap<String, f32>>,
5382    old: impl Fn(Area) -> Option<f32>,
5383) -> BTreeMap<String, f32> {
5384    let mut sizes = saved.unwrap_or_default();
5385    for area in [Area::StartSide, Area::EndSide, Area::Bottom] {
5386        let name = area_name(area);
5387        if !sizes.contains_key(name)
5388            && let Some(size) = old(area)
5389        {
5390            sizes.insert(name.to_owned(), size);
5391        }
5392    }
5393    sizes
5394}
5395
5396/// The size an area's egui panel had (its `PanelState`, under the `Ui`
5397/// the workbench was drawn in, `scope`): its width, the bottom's height.
5398fn old_panel_size(ctx: &egui::Context, scope: Id, area: Area) -> Option<f32> {
5399    let state = egui::containers::panel::PanelState::load(ctx, scope.with(dock_id(area)))?;
5400    let size = state.size();
5401    Some(if area == Area::Bottom { size.y } else { size.x })
5402}
5403
5404/// Paints the shell's layout with the kit: a strip's grip `selected`
5405/// while its area lies over the centre.
5406struct ShellPainter<'a> {
5407    kit: &'a Kit,
5408    open: &'a BTreeSet<Area>,
5409    flipped: bool,
5410}
5411
5412impl LayoutPainter for ShellPainter<'_> {
5413    fn sash(&self, painter: &egui::Painter, sash: &SashPaint<'_>) {
5414        // The line lies inside the area it resizes, on its side facing the
5415        // centre, where egui drew a side or bottom panel's separator.
5416        let inward =
5417            area_from(&sash.zone.0).map_or(egui::Vec2::ZERO, |area| inward(area, self.flipped));
5418        self.kit.paint_area_line(painter, sash, inward);
5419    }
5420
5421    /// The fold guide from the kit (`side-area.fold.border-*`), the others
5422    /// as egui_stack draws them.
5423    fn snap_guide(&self, painter: &egui::Painter, guide: &SnapGuidePaint<'_>) {
5424        self.kit.paint_snap_guide(painter, guide);
5425    }
5426
5427    /// The free edge of an area lying over the centre: its line while
5428    /// hovered or dragged when the kit gives the state's tokens, inside the
5429    /// area as a docked area's.
5430    fn over_edge(&self, painter: &egui::Painter, edge: &SashPaint<'_>) {
5431        let inward =
5432            area_from(&edge.zone.0).map_or(egui::Vec2::ZERO, |area| inward(area, self.flipped));
5433        self.kit.paint_over_edge(painter, edge, inward);
5434    }
5435
5436    fn strip(&self, painter: &egui::Painter, strip: &StripPaint<'_>) {
5437        let Some(area) = area_from(&strip.zone.0) else {
5438            LayoutPainter::strip(self.kit, painter, strip);
5439            return;
5440        };
5441        let inner = if on_left(area, self.flipped) {
5442            Side::Right
5443        } else {
5444            Side::Left
5445        };
5446        let flags = strip.grip_state;
5447        let state = State::REST
5448            .with(State::HOVER, flags.contains(PartState::HOVERED))
5449            .with(State::ACTIVE, flags.contains(PartState::PRESSED))
5450            .with(
5451                State::FOCUS,
5452                flags.contains(PartState::FOCUSED)
5453                    && egui_pop_core::focus::ring_shown(painter.ctx()),
5454            )
5455            .with(State::SELECTED, self.open.contains(&area));
5456        self.kit.paint_area_strip(painter, strip.rect, state, inner);
5457    }
5458
5459    /// A side area lying over the centre, or a flyout: the kit's
5460    /// `side-area` box, its shadow cast towards the centre, and the line on
5461    /// the centre's side, as a side panel's.
5462    fn flyout_frame(&self, painter: &egui::Painter, frame: &FlyoutPaint<'_>) {
5463        let Some(area) = area_from(&frame.zone.0) else {
5464            LayoutPainter::flyout_frame(self.kit, painter, frame);
5465            return;
5466        };
5467        let start = on_left(area, self.flipped);
5468        let side = &self.kit.side_area;
5469        let mut shadow = side.data.shadow;
5470        if !start {
5471            shadow.offset[0] = shadow.offset[0].saturating_neg();
5472        }
5473        let rect = frame.rect;
5474        if shadow != egui::Shadow::NONE {
5475            painter.add(shadow.as_shape(rect, egui::CornerRadius::ZERO));
5476        }
5477        let visuals = &painter.ctx().global_style().visuals;
5478        painter.rect_filled(rect, 0.0, visuals.panel_fill);
5479        if side.style(State::REST).border_width > 0.0 {
5480            let x = if start { rect.right() } else { rect.left() };
5481            painter.vline(x, rect.y_range(), visuals.widgets.noninteractive.bg_stroke);
5482        }
5483    }
5484}
5485
5486/// The centre every panel was moved out of: it stays laid out and stays a
5487/// drop target (its empty dock, drawn over it by [`drop_targets`] while a
5488/// tab drags; a palette docks there too, [`Workbench::dock_at`]), and says
5489/// so, to the eye and to a screen reader. It is a placeholder for the
5490/// paint guard: a window showing nothing else still gets the fallback
5491/// page.
5492fn empty_centre(app: &AppHandle, ui: &mut Ui) {
5493    let text = strings::tr(ui.ctx(), &txt::WORKBENCH_DROP_HERE);
5494    app.placeholder(ui, |ui| {
5495        ui.centered_and_justified(|ui| {
5496            ui.weak(text);
5497        });
5498    });
5499}
5500
5501/// The edge of a side or bottom area facing the centre, where its line is.
5502fn edge_toward_centre(area: Area, flipped: bool) -> Side {
5503    match area {
5504        Area::Bottom => Side::Top,
5505        _ if on_left(area, flipped) => Side::Right,
5506        _ => Side::Left,
5507    }
5508}
5509
5510/// The way from an area's edge facing the centre into the area.
5511fn inward(area: Area, flipped: bool) -> egui::Vec2 {
5512    match edge_toward_centre(area, flipped) {
5513        Side::Left => egui::Vec2::X,
5514        Side::Right => -egui::Vec2::X,
5515        Side::Top => egui::Vec2::Y,
5516        Side::Bottom => -egui::Vec2::Y,
5517    }
5518}
5519
5520/// Draws the shell's zones: each area in its frame, the strips' icons.
5521struct ShellViewer<'a> {
5522    app: &'a AppHandle,
5523    ctx: &'a egui::Context,
5524    kit: &'a Kit,
5525    open: &'a BTreeSet<Area>,
5526    areas: &'a [Area],
5527    flipped: bool,
5528    /// The strips' breadth.
5529    strip: f32,
5530    /// The panel shown as the flyout.
5531    flyout: Option<PanelId>,
5532    /// The overlay stack closed the flyout this pass.
5533    flyout_closed: bool,
5534}
5535
5536impl ZoneViewer for ShellViewer<'_> {
5537    fn flyout_title(&mut self, flyout: &Flyout) -> String {
5538        match &self.flyout {
5539            Some(panel) => self.app.panel_title(self.ctx, panel),
5540            None => flyout.key.clone(),
5541        }
5542    }
5543
5544    fn flyout(&mut self, ui: &mut Ui, flyout: &Flyout) {
5545        let (Some(panel), Some(area)) = (self.flyout.clone(), area_from(&flyout.zone.0)) else {
5546            return;
5547        };
5548        if !flyout_body(self.app, ui, self.kit, (area, self.strip), &panel) {
5549            self.flyout_closed = true;
5550        }
5551    }
5552
5553    /// An area's zone is named after the area ("the centre"), not its key,
5554    /// for screen readers and tests: its pane, and its sash and grip ("Resize
5555    /// the start side bar"); a split keeps its name.
5556    fn title(&mut self, zone: &ZoneName) -> String {
5557        if zone.0 == ACTIVITY_ZONE {
5558            return strings::tr(self.ctx, &txt::AREA_ACTIVITY_BAR);
5559        }
5560        area_from(&zone.0).map_or_else(|| zone.0.clone(), |area| area_text(self.ctx, area))
5561    }
5562
5563    fn ui(&mut self, ui: &mut Ui, zone: &ZoneName) {
5564        if zone.0 == ACTIVITY_ZONE {
5565            activity_bar(self.app, ui, self.flipped);
5566            return;
5567        }
5568        let Some(area) = area_from(&zone.0) else {
5569            return;
5570        };
5571        let app = self.app;
5572        if area == Area::Center {
5573            // The centre's margins are the side areas' (`dock-area`), so
5574            // their tab strips start at the same height.
5575            let frameless = app.edge_to_edge() || app.frameless(Area::Center);
5576            let frame = egui::Frame::central_panel(ui.style())
5577                .inner_margin(self.kit.dock_area_margin(frameless));
5578            frame.show(ui, |ui| {
5579                ui.set_min_size(ui.available_size());
5580                if !self.areas.contains(&Area::Center) {
5581                    empty_centre(app, ui);
5582                } else if visible_in(app, Area::Center) {
5583                    draw_area(app, ui, Area::Center);
5584                }
5585            });
5586            return;
5587        }
5588        let margin = self.kit.dock_area_margin(app.frameless(area));
5589        // The room the line facing the centre takes, outside the frame, as
5590        // an egui panel reserved it.
5591        let room = self.kit.area_line_room(ui.style()).clamp(0.0, 127.0) as i8;
5592        let mut outer = egui::Margin::ZERO;
5593        match edge_toward_centre(area, self.flipped) {
5594            Side::Left => outer.left = room,
5595            Side::Right => outer.right = room,
5596            Side::Top => outer.top = room,
5597            Side::Bottom => outer.bottom = room,
5598        }
5599        egui::Frame::side_top_panel(ui.style())
5600            .inner_margin(margin)
5601            .outer_margin(outer)
5602            .show(ui, |ui| {
5603                // The area keeps its size; content narrower than it does
5604                // not shrink it.
5605                ui.set_min_size(ui.available_size());
5606                draw_area(app, ui, area);
5607            });
5608    }
5609
5610    fn strip(&mut self, ui: &mut Ui, zone: &ZoneName) {
5611        let Some(area) = area_from(&zone.0) else {
5612            return;
5613        };
5614        // The `Ui` is the strip under its grip, a square at its top.
5615        let rest = ui.max_rect();
5616        let rect = Rect::from_min_max(egui::pos2(rest.left(), rest.top() - rest.width()), rest.max);
5617        ui.set_clip_rect(rect);
5618        strip_icons(
5619            self.app,
5620            ui,
5621            self.kit,
5622            area,
5623            rect,
5624            self.open.contains(&area),
5625        );
5626    }
5627}
5628
5629/// A panel's icon in a side area's strip, as agents read it
5630/// ([`strip`], the `workbench` collector's `strips`).
5631#[derive(Clone, Debug, PartialEq, serde::Serialize)]
5632pub struct StripIcon {
5633    /// The area whose strip it is in (`area_name`).
5634    pub area: &'static str,
5635    pub panel: PanelId,
5636    pub title: String,
5637    /// Its icon's name; `None`: its title's first letter is drawn.
5638    #[serde(skip_serializing_if = "Option::is_none")]
5639    pub icon: Option<String>,
5640    /// Its key (its focus command's, else its toggle command's).
5641    #[serde(skip_serializing_if = "Option::is_none")]
5642    pub key: Option<String>,
5643    /// The panel shows: in its area (open over the centre, the tab in
5644    /// front) or as the flyout.
5645    pub shown: bool,
5646    /// It is the flyout.
5647    #[serde(skip_serializing_if = "std::ops::Not::not")]
5648    pub flyout: bool,
5649    /// Its indicator's state, when a panel indicator speaks for it.
5650    #[serde(skip_serializing_if = "Option::is_none")]
5651    pub indicator: Option<crate::strips::IndicatorState>,
5652    /// Whether the icon shows the indicator's mark now (the panel not
5653    /// shown, the state saying something).
5654    #[serde(skip_serializing_if = "std::ops::Not::not")]
5655    pub marked: bool,
5656}
5657
5658/// Every icon of the side areas' strips (an area folded, or lying over
5659/// the centre), start side first, each in tab order, with its panel's
5660/// indicator; none for a bare strip ([`AppHandle::bare_strip`]). Empty
5661/// in zen mode.
5662pub fn strip(app: &AppHandle) -> Vec<StripIcon> {
5663    let (layout, zen, flyout) = {
5664        let mut wb = app.workbench_mut();
5665        (wb.layout(), wb.main_zen(), wb.flyout.clone())
5666    };
5667    if zen {
5668        return Vec::new();
5669    }
5670    let ctx = app.egui();
5671    let mut out = Vec::new();
5672    for area in [Area::StartSide, Area::EndSide] {
5673        let folded = layout.folded.contains(&area);
5674        if !folded && !layout.over.contains(&area) {
5675            continue;
5676        }
5677        let active = layout.active_in(area);
5678        for panel in strip_panels(app, area) {
5679            let flown = flyout.as_ref() == Some(&panel);
5680            let shown = flown || (!folded && active.contains(&&panel));
5681            let indicator = panel_indicator(app, &panel);
5682            let marked = !shown
5683                && indicator
5684                    .as_ref()
5685                    .is_some_and(|(i, s)| panel_mark(i, s).is_some());
5686            let icon = app
5687                .workbench_mut()
5688                .spec(&panel)
5689                .map(|s| s.icon.clone())
5690                .filter(|i| egui_pop_core::icon::Icon::by_name(i).is_some());
5691            out.push(StripIcon {
5692                area: area_name(area),
5693                title: app.panel_title(&ctx, &panel),
5694                icon,
5695                key: panel_key(app, &panel),
5696                shown,
5697                flyout: flown,
5698                indicator: indicator.map(|(_, s)| s),
5699                marked,
5700                panel,
5701            });
5702        }
5703    }
5704    out
5705}
5706
5707/// The panels a side area's strip shows icons for: those it holds that
5708/// have something to draw, in tab order; none on a bare strip
5709/// ([`AppHandle::bare_strip`]).
5710fn strip_panels(app: &AppHandle, area: Area) -> Vec<PanelId> {
5711    if app.bare_strip(area) {
5712        return Vec::new();
5713    }
5714    let panels = app.workbench_mut().panels_in(area);
5715    panels.into_iter().filter(|p| drawable(app, p)).collect()
5716}
5717
5718/// A panel's key: the first binding of its focus command, else of its
5719/// toggle command.
5720fn panel_key(app: &AppHandle, panel: &PanelId) -> Option<String> {
5721    ["focus", "toggle"].into_iter().find_map(|suffix| {
5722        let id = egui_pop_model::ids::CommandId::new(format!("{panel}.{suffix}")).ok()?;
5723        app.keys_for(&id).into_iter().next()
5724    })
5725}
5726
5727/// The indicator speaking for a panel ([`crate::strips::Indicator::panel`])
5728/// and its state.
5729fn panel_indicator(
5730    app: &AppHandle,
5731    panel: &PanelId,
5732) -> Option<(crate::strips::Indicator, crate::strips::IndicatorState)> {
5733    app.indicators()
5734        .into_iter()
5735        .find(|(i, _)| i.panel.as_ref() == Some(panel))
5736}
5737
5738/// The mark a panel's indicator state shows on its strip icon: a count
5739/// as a badge (in the accent tone unless the state has one), else its
5740/// errors or warnings, else a dot in its tone; nothing in the neutral
5741/// tone with nothing to count.
5742fn panel_mark(
5743    ind: &crate::strips::Indicator,
5744    state: &crate::strips::IndicatorState,
5745) -> Option<egui_pop_core::indicator::Indicator> {
5746    use egui_pop_core::indicator::Indicator as Mark;
5747    use egui_pop_core::kit::Tone;
5748    let tone = state.tone;
5749    let mark = if let Some(n) = state.count.filter(|n| *n > 0) {
5750        Mark::count(n).tone(if tone == Tone::Neutral {
5751            Tone::Accent
5752        } else {
5753            tone
5754        })
5755    } else if state.errors > 0 {
5756        Mark::count(state.errors).tone(Tone::Danger)
5757    } else if state.warnings > 0 {
5758        Mark::count(state.warnings).tone(Tone::Warning)
5759    } else if tone != Tone::Neutral {
5760        Mark::dot(tone)
5761    } else {
5762        return None;
5763    };
5764    let name = if state.text.is_empty() {
5765        ind.label.clone()
5766    } else {
5767        state.text.clone()
5768    };
5769    Some(mark.name(name).id(format!("strip:{}", ind.id)))
5770}
5771
5772/// One panel's icon in a side area's strip, drawn by the kit's
5773/// `activity-bar-item` (`selected` while its panel shows, in the area
5774/// or as the flyout): its [`PanelSpec::icon`], else its title's first
5775/// letter; its indicator's mark while the panel is not shown. A click
5776/// opens or closes its flyout (folded) or shows it (`open`); a double
5777/// click unfolds the area with it shown.
5778#[allow(
5779    clippy::too_many_arguments,
5780    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
5781)]
5782pub(crate) fn strip_icon(
5783    app: &AppHandle,
5784    ui: &mut Ui,
5785    kit: &Kit,
5786    area: Area,
5787    panel: &PanelId,
5788    rect: Rect,
5789    open: bool,
5790    shown: bool,
5791) {
5792    let ctx = ui.ctx().clone();
5793    let t = egui_pop_core::theme::Tokens::of(&ctx);
5794    let title = app.panel_title(&ctx, panel);
5795    let icon = app
5796        .workbench_mut()
5797        .spec(panel)
5798        .and_then(|s| egui_pop_core::icon::Icon::by_name(&s.icon));
5799    let flown = app.workbench_mut().flyout.as_ref() == Some(panel);
5800    let id = dock_id(area).with(("egui_pop.strip_icon", panel.as_str()));
5801    let r = ui.interact(rect, id, egui::Sense::click());
5802    let label = title.clone();
5803    r.widget_info(move || WidgetInfo::labeled(Role::Button, true, &label));
5804    let indicator = panel_indicator(app, panel);
5805    let mut tip = title.clone();
5806    if let Some(key) = panel_key(app, panel) {
5807        tip.push('\n');
5808        tip.push_str(&key);
5809    }
5810    let visible = shown || flown;
5811    let mark = indicator
5812        .as_ref()
5813        .filter(|_| !visible)
5814        .and_then(|(i, s)| panel_mark(i, s).map(|m| (m, s.detail.clone())));
5815    if let Some((_, detail)) = &mark
5816        && !detail.is_empty()
5817    {
5818        tip.push('\n');
5819        tip.push_str(detail);
5820    }
5821    let state = State::REST
5822        .with(State::HOVER, r.hovered() && !visible)
5823        .with(State::ACTIVE, r.is_pointer_button_down_on())
5824        .with(State::FOCUS, egui_pop_core::focus::shows_ring(&r))
5825        .with(State::SELECTED, visible);
5826    if r.has_focus() {
5827        egui_pop_core::focus::own_ring(&r.ctx, r.id);
5828    }
5829    let item = &kit.activity_bar_item;
5830    let cx = KitCx {
5831        painter: ui.painter(),
5832        ppp: ctx.pixels_per_point(),
5833    };
5834    item.paint(
5835        &cx,
5836        &Part {
5837            rect,
5838            room: rect,
5839            state,
5840            label: None,
5841        },
5842    );
5843    let color = item.style(state).text;
5844    let inner = Rect::from_center_size(
5845        rect.center(),
5846        egui::vec2(t.size.icon_inline, t.size.icon_inline),
5847    );
5848    match icon {
5849        Some(i) => egui_pop_core::icon::Source::from(i).paint(ui, inner, color),
5850        None => {
5851            let letter: String = title
5852                .chars()
5853                .next()
5854                .map(|c| c.to_uppercase().collect())
5855                .unwrap_or_else(|| "?".into());
5856            ui.painter().text(
5857                inner.center(),
5858                egui::Align2::CENTER_CENTER,
5859                letter,
5860                egui::FontId::proportional(t.size.icon_inline),
5861                color,
5862            );
5863        }
5864    }
5865    if let Some((m, _)) = mark {
5866        m.on(ui, &r, egui_pop_core::indicator::Anchor::TopEnd);
5867    }
5868    let r = r.on_hover_text(tip);
5869    if r.double_clicked() {
5870        // Unfolds the area with the panel shown.
5871        app.change_workbench(Change::Flyout(panel.clone(), false));
5872        app.focus_panel(panel);
5873    } else if r.clicked() {
5874        if open {
5875            app.focus_panel(panel);
5876        } else {
5877            app.change_workbench(Change::Flyout(panel.clone(), !flown));
5878        }
5879    }
5880}
5881
5882// F6's order (`egui_pop_core::regions`); palettes, of one rank, go as drawn.
5883const RANK_ACTIVITY_BAR: u32 = 0;
5884const RANK_START_SIDE: u32 = 10;
5885const RANK_END_SIDE: u32 = 11;
5886const RANK_BOTTOM: u32 = 12;
5887const RANK_CENTER: u32 = 20;
5888pub(crate) const RANK_PALETTE: u32 = 30;
5889const RANK_FLYOUT: u32 = 40;
5890pub(crate) const RANK_STATUS_BAR: u32 = 50;
5891
5892fn rank_of(area: Area) -> u32 {
5893    match area {
5894        Area::StartSide => RANK_START_SIDE,
5895        Area::EndSide => RANK_END_SIDE,
5896        Area::Bottom => RANK_BOTTOM,
5897        Area::Center => RANK_CENTER,
5898    }
5899}
5900
5901/// An area's region's name.
5902fn area_region(area: Area) -> String {
5903    format!("region.area.{}", area_name(area))
5904}
5905
5906/// Runs `workbench.next_region` or `workbench.previous_region`: see
5907/// [Moving between regions](self#moving-between-regions).
5908pub(crate) fn go_to_region(
5909    app: &AppHandle,
5910    origin: &egui_pop_model::commands::Origin,
5911    back: bool,
5912) -> Result<Json, String> {
5913    let ctx = app.egui();
5914    let agent = !matches!(origin, egui_pop_model::commands::Origin::User);
5915    if (agent && focus::text_input_owns_keyboard(&ctx)) || open_on_top(app, &ctx) {
5916        return Ok(json!({ "moved": false }));
5917    }
5918    let Some(hop) = egui_pop_core::regions::next(&ctx, back) else {
5919        return Ok(json!({ "moved": false }));
5920    };
5921    match hop.target {
5922        Some(id) => ctx.memory_mut(|m| {
5923            m.request_focus(id);
5924            m.move_focus(egui::FocusDirection::None);
5925        }),
5926        None => {
5927            // A panel of text alone holds the focus itself, its own stop.
5928            let area = Area::ALL
5929                .into_iter()
5930                .find(|a| area_region(*a) == hop.region);
5931            let active = area.map(|a| {
5932                let wb = app.workbench_mut();
5933                let panels: Vec<PanelId> = wb.layout.active_in(a).into_iter().cloned().collect();
5934                panels
5935            });
5936            let panel = active
5937                .and_then(|p| p.into_iter().find(|p| drawable(app, p)))
5938                .or_else(|| window_areas::region_panel(app, &hop.region));
5939            if let Some(panel) = panel {
5940                app.focus_panel(&panel);
5941            }
5942        }
5943    }
5944    Ok(json!({ "moved": true, "region": hop.region }))
5945}
5946
5947/// The panel beside `panel` in its tab group, the previous one with `back`,
5948/// wrapping; none for a panel alone in its group.
5949fn tab_beside(node: &Node, panel: &PanelId, back: bool) -> Option<PanelId> {
5950    match node {
5951        Node::Tabs { panels, .. } => {
5952            let i = panels.iter().position(|p| p == panel)?;
5953            let n = panels.len();
5954            (n > 1).then(|| panels[if back { (i + n - 1) % n } else { (i + 1) % n }].clone())
5955        }
5956        Node::Split { a, b, .. } => {
5957            tab_beside(a, panel, back).or_else(|| tab_beside(b, panel, back))
5958        }
5959        Node::Grid { children, .. } => children.iter().find_map(|c| tab_beside(c, panel, back)),
5960    }
5961}
5962
5963/// The arrange commands: the row, column or grid around a panel's group
5964/// (`panel` in the arguments, or the focused one) laid out `as` says, a
5965/// grid with the arguments' `columns` if any. Nothing to arrange (no
5966/// panel focused, or its group alone in its area) is not an error.
5967/// The `workbench.move_to_window` command: `panel` (the focused one by
5968/// default) joins the window holding `window`, through the
5969/// `workbench.join_window` step.
5970pub(crate) fn move_to_window_command(app: &AppHandle, args: &Json) -> Result<Json, String> {
5971    let panel = match args.get("panel").and_then(Json::as_str) {
5972        Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
5973        None => app.try_workbench().and_then(|wb| wb.focused.clone()),
5974    };
5975    let panel = panel.ok_or("no panel is focused: name one (`panel`)")?;
5976    let window = args
5977        .get("window")
5978        .and_then(Json::as_str)
5979        .ok_or("`window` is missing: a panel of the window")?;
5980    let window = PanelId::new(window).map_err(|e| e.to_string())?;
5981    let change = if args.get("group").and_then(Json::as_bool) == Some(true) {
5982        Change::JoinWindowGroup(panel, window)
5983    } else {
5984        Change::JoinWindow(panel, window)
5985    };
5986    match app.change_workbench(change) {
5987        Some(Outcome::Done(r)) => r,
5988        Some(Outcome::Vetoed { by, reason }) => Err(format!("stopped by `{by}`: {reason}")),
5989        _ => Ok(json!({ "queued": true })),
5990    }
5991}
5992
5993pub(crate) fn arrange_command(app: &AppHandle, args: &Json, how: &str) -> Result<Json, String> {
5994    let panel = match args.get("panel").and_then(Json::as_str) {
5995        Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
5996        None => app.try_workbench().and_then(|wb| wb.focused.clone()),
5997    };
5998    let Some(panel) = panel else {
5999        return Ok(json!({ "arranged": false }));
6000    };
6001    let mut step = json!({ "as": how });
6002    if let Some(columns) = args.get("columns") {
6003        step["columns"] = columns.clone();
6004    }
6005    let how = Arrangement::from_args(&step)?;
6006    let alone = {
6007        let layout = app.layout();
6008        !(layout.areas.iter()).any(|(_, n)| arrange(n, &panel, how).is_some())
6009    };
6010    if alone {
6011        return Ok(json!({ "arranged": false }));
6012    }
6013    match app.arrange(&panel, how) {
6014        Some(Outcome::Done(Ok(result))) => {
6015            let mut result = result;
6016            result["arranged"] = json!(true);
6017            Ok(result)
6018        }
6019        Some(Outcome::Done(Err(e))) => Err(e),
6020        Some(Outcome::Vetoed { by, reason }) => Err(format!("stopped by `{by}`: {reason}")),
6021        _ => Ok(json!({ "arranged": true, "queued": true })),
6022    }
6023}
6024
6025/// Moves the keyboard to the tab beside the focused panel's, in its group, as
6026/// VS Code's Ctrl+Page Down and Up: that panel is shown and focused, through
6027/// the `workbench.focus` step.
6028pub(crate) fn go_to_tab(app: &AppHandle, back: bool) -> Result<Json, String> {
6029    let focused = app.try_workbench().and_then(|wb| wb.focused.clone());
6030    let Some(panel) = focused else {
6031        return Ok(json!({ "moved": false }));
6032    };
6033    let layout = app.layout();
6034    let target = (layout.areas.iter()).find_map(|(_, node)| tab_beside(node, &panel, back));
6035    let Some(target) = target else {
6036        return Ok(json!({ "moved": false }));
6037    };
6038    match app.focus_panel(&target) {
6039        Some(Outcome::Vetoed { by, reason }) => Err(format!("stopped by `{by}`: {reason}")),
6040        _ => Ok(json!({ "moved": true, "panel": target })),
6041    }
6042}
6043
6044/// A menu or a popover is open, not the flyout: Escape comes first, F6 would
6045/// leave it open behind the focus.
6046fn open_on_top(app: &AppHandle, ctx: &egui::Context) -> bool {
6047    let flyout = app.workbench_mut().flyout.clone();
6048    let flyout = flyout.map(|p| Id::unique(flyout_overlay(&p)));
6049    egui::Popup::is_any_open(ctx)
6050        || egui_pop_core::overlay::stack(ctx)
6051            .iter()
6052            .any(|o| Some(o.id) != flyout)
6053}
6054
6055/// What names a panel's flyout in the overlay stack.
6056fn flyout_overlay(panel: &PanelId) -> (&'static str, &str) {
6057    ("egui_pop.flyout", panel.as_str())
6058}
6059
6060/// Where a flyout's width follows its edge while it is dragged.
6061fn flyout_live_id(panel: &PanelId) -> Id {
6062    Id::unique(("egui_pop.flyout.live", panel.as_str()))
6063}
6064
6065/// A panel's flyout's width, then its least and largest: as its edge is
6066/// dragged, else as saved, else the panel's default, else its area's size,
6067/// else 240; `None` when the panel is not known. The largest leaves the
6068/// strips room (`strip` wide).
6069fn flyout_width(
6070    app: &AppHandle,
6071    ctx: &egui::Context,
6072    area: Area,
6073    panel: &PanelId,
6074    strip: f32,
6075) -> Option<(f32, f32, f32)> {
6076    let wb = app.workbench_mut();
6077    let spec = wb.spec(panel)?;
6078    let min = spec.min_size.max(48.0);
6079    let max = (wb.content.width() - 2.0 * strip).max(min);
6080    let width = ctx
6081        .data(|d| d.get_temp::<f32>(flyout_live_id(panel)))
6082        .or_else(|| wb.layout.flyouts.get(panel).copied())
6083        .or(spec.default_size)
6084        .or_else(|| wb.shell_sizes.as_ref()?.get(area_name(area)).copied())
6085        .unwrap_or(240.0)
6086        .clamp(min, max);
6087    Some((width, min, max))
6088}
6089
6090/// A folded side area's panel shown alone over the centre, next to the
6091/// strip (the layout's flyout, `ui` its rect): a band with its title and a
6092/// pin button unfolding the area, then the panel. An overlay of the stack
6093/// (`overlay::hold`), so Escape (the top overlay first) or a click away
6094/// closes it; a combo box or a context menu opened in it is part of it.
6095/// Returns false once the stack closed it.
6096pub(crate) fn flyout_body(
6097    app: &AppHandle,
6098    ui: &mut Ui,
6099    kit: &Kit,
6100    (area, strip): (Area, f32),
6101    panel: &PanelId,
6102) -> bool {
6103    let ctx = ui.ctx().clone();
6104    let title = app.panel_title(&ctx, panel);
6105    let rect = ui.max_rect();
6106    // In the overlay stack: its rect takes in the resize edge, the strip
6107    // is its anchor (a click on another icon switches the flyout).
6108    let anchor = if app.workbench_mut().on_left(area) {
6109        Rect::from_x_y_ranges(rect.left() - strip..=rect.left(), rect.y_range())
6110    } else {
6111        Rect::from_x_y_ranges(rect.right()..=rect.right() + strip, rect.y_range())
6112    };
6113    let reach = ctx.global_style().interaction.resize_grab_radius_side;
6114    let spec = egui_pop_core::overlay::OverlaySpec::new(
6115        flyout_overlay(panel),
6116        &title,
6117        egui_pop_core::overlay::Kind::Popover,
6118    );
6119    let mut open = true;
6120    egui_pop_core::overlay::hold(
6121        &ctx,
6122        &spec,
6123        &mut open,
6124        Some(anchor),
6125        rect.expand2(egui::vec2(reach, 0.0)),
6126        || draw_flyout(app, ui, kit, panel, &title),
6127    )
6128    .is_some()
6129}
6130
6131/// Draws the panel zen mode shows alone, over the whole of `ui`: in the
6132/// main window, or in its detached window.
6133pub(crate) fn show_alone(app: &AppHandle, ui: &mut Ui, panel: &PanelId) {
6134    let kit = Kit::of(ui.ctx());
6135    let pad = egui::vec2(kit.dock_area.data.padding_x, kit.dock_area.data.padding_y);
6136    let rect = ui.max_rect();
6137    ui.painter().rect_filled(rect, 0.0, ui.visuals().panel_fill);
6138    let body = rect.shrink2(pad);
6139    let mut inner = ui.new_child(
6140        egui::UiBuilder::new()
6141            .id_salt(("egui_pop.zen.panel", panel.as_str()))
6142            .max_rect(body),
6143    );
6144    inner.set_clip_rect(body);
6145    inner.set_min_size(inner.available_size());
6146    let region = focus::Region::new("region.zen", RANK_CENTER);
6147    focus::region(&mut inner, &region, |inner| app.show_panel(inner, panel));
6148    ui.expand_to_include_rect(rect);
6149}
6150
6151/// Draws an open flyout's content (`flyout_body`): its band, its panel.
6152fn draw_flyout(app: &AppHandle, ui: &mut Ui, kit: &Kit, panel: &PanelId, title: &str) {
6153    let pad = egui::vec2(kit.dock_area.data.padding_x, kit.dock_area.data.padding_y);
6154    let t = egui_pop_core::theme::Tokens::of(ui.ctx());
6155    let body = ui.max_rect().shrink2(pad);
6156    let mut inner = ui.new_child(
6157        egui::UiBuilder::new()
6158            .id_salt("egui_pop.flyout.inner")
6159            .max_rect(body),
6160    );
6161    inner.set_clip_rect(body);
6162    inner.set_min_size(inner.available_size());
6163    let region = focus::Region::new("region.flyout", RANK_FLYOUT);
6164    let pinned = focus::region(&mut inner, &region, |inner| {
6165        // The band: the title, then the pin button at the end.
6166        let pin = strings::tr_args(inner.ctx(), &txt::WORKBENCH_FLYOUT_PIN, &[("panel", title)]);
6167        let button = t.size.control_height.max(24.0);
6168        let header = kit.header_band.style(State::REST).text;
6169        // The pin first, from the end: a truncated title laid out
6170        // before it would take the whole row and push it out.
6171        let pinned = inner
6172            .horizontal(|ui| {
6173                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
6174                    let pinned = egui_pop_core::band::button(
6175                        ui,
6176                        button,
6177                        egui_pop_core::icon::Icon::Unlock,
6178                        &pin,
6179                        false,
6180                    )
6181                    .clicked();
6182                    ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
6183                        ui.add(
6184                            egui::Label::new(egui::RichText::new(title).strong().color(header))
6185                                .truncate()
6186                                .selectable(false),
6187                        );
6188                    });
6189                    pinned
6190                })
6191                .inner
6192            })
6193            .inner;
6194        inner.separator();
6195        app.show_panel(inner, panel);
6196        pinned
6197    });
6198    if pinned {
6199        app.change_workbench(Change::Flyout(panel.clone(), false));
6200        app.focus_panel(panel);
6201    }
6202}
6203
6204/// How far an arrow moves an area's line, in points; Shift moves it four
6205/// times as far (as egui_stack's separators).
6206const SASH_STEP: f32 = 16.0;
6207
6208/// A side area's resize grip (the kit's `area-grip`) at the middle of its
6209/// edge, above the panels; the layout's sash takes the drag. Nothing is
6210/// drawn while the kit's grip is transparent in every state (the default
6211/// kit).
6212fn grip(ctx: &egui::Context, kit: &Kit, area: Area, rect: Rect, flipped: bool) {
6213    let g = &kit.area_grip;
6214    if [State::REST, State::HOVER, State::ACTIVE]
6215        .iter()
6216        .all(|s| g.style(*s).fill.a() == 0)
6217    {
6218        return;
6219    }
6220    let (w, h, off) = (g.data.width, g.data.height, g.data.offset);
6221    let (centre, size) = match area {
6222        Area::StartSide | Area::EndSide if on_left(area, flipped) => (
6223            egui::pos2(rect.right() + off, rect.center().y),
6224            egui::vec2(w, h),
6225        ),
6226        Area::StartSide | Area::EndSide => (
6227            egui::pos2(rect.left() - off, rect.center().y),
6228            egui::vec2(w, h),
6229        ),
6230        _ => (
6231            egui::pos2(rect.center().x, rect.top() - off),
6232            egui::vec2(h, w),
6233        ),
6234    };
6235    let reach = ctx.global_style().interaction.resize_grab_radius_side;
6236    let near = ctx.pointer_hover_pos().is_some_and(|p| match area {
6237        Area::StartSide | Area::EndSide => {
6238            (p.x - centre.x).abs() <= reach && rect.y_range().contains(p.y)
6239        }
6240        _ => (p.y - centre.y).abs() <= reach && rect.x_range().contains(p.x),
6241    });
6242    let state = State::REST.with(State::HOVER, near).with(
6243        State::ACTIVE,
6244        near && ctx.input(|i| i.pointer.primary_down()),
6245    );
6246    let painter = ctx.layer_painter(egui::LayerId::new(
6247        egui::Order::Middle,
6248        Id::unique("egui_pop.area_grips"),
6249    ));
6250    let rect = Rect::from_center_size(centre, size);
6251    g.paint(
6252        &KitCx {
6253            painter: &painter,
6254            ppp: ctx.pixels_per_point(),
6255        },
6256        &Part {
6257            rect,
6258            room: rect,
6259            state,
6260            label: None,
6261        },
6262    );
6263}
6264
6265/// Whether a panel has something to draw (a zone panel's zone has
6266/// blocks).
6267pub(crate) fn drawable(app: &AppHandle, panel: &PanelId) -> bool {
6268    let zone = app.workbench_mut().zone_of.get(panel).cloned();
6269    zone.is_none_or(|z| app.zone_has_blocks(&z))
6270}
6271
6272/// Whether an area has a panel to draw.
6273fn visible_in(app: &AppHandle, area: Area) -> bool {
6274    let panels = app.workbench_mut().panels_in(area);
6275    panels.iter().any(|p| drawable(app, p))
6276}
6277
6278/// Draws one area: a bare panel alone plainly, else its dock.
6279fn draw_area(app: &AppHandle, ui: &mut Ui, area: Area) {
6280    let region =
6281        focus::Region::new(area_region(area), rank_of(area)).holding(visible_in(app, area));
6282    focus::region(ui, &region, |ui| draw_dock(app, ui, area));
6283}
6284
6285/// Draws an area's dock, or its one bare panel.
6286fn draw_dock(app: &AppHandle, ui: &mut Ui, area: Area) {
6287    let tabs = app.workbench_mut().panels_in(area);
6288    let drawable_tabs: Vec<&PanelId> = tabs.iter().filter(|p| drawable(app, p)).collect();
6289    let bare = drawable_tabs.len() == 1
6290        && app
6291            .workbench_mut()
6292            .spec(drawable_tabs[0])
6293            .is_some_and(|s| s.bare);
6294    if bare {
6295        let id = drawable_tabs[0].clone();
6296        app.show_panel(ui, &id);
6297        // A drop target while a tab drags (`drop_targets`).
6298        app.workbench_mut().bare.insert(area);
6299        return;
6300    }
6301    let Some(mut space) = app.workbench_mut().take_space() else {
6302        return;
6303    };
6304    let ctx = ui.ctx().clone();
6305    let kit = Kit::of(&ctx);
6306    let cache_id = TAB_CACHE.keyed(dock_id(area));
6307    let mut cache = cache_id.update(&ctx, std::mem::take);
6308    cache.prepare(app, &ctx, &kit, &tabs);
6309    let mut style = cache.dock_style(ui.style(), &kit);
6310    from_elsewhere(&mut style, &space, &ctx);
6311    let frameless = app.frameless(area);
6312    if frameless {
6313        // The panels' bodies run to the area's edges, with no border
6314        // (`AreaPainter`); the separator's line alone sets them apart.
6315        let body = &mut style.tab.tab_body;
6316        body.inner_margin = egui::Margin::ZERO;
6317        body.stroke = egui::Stroke::NONE;
6318        body.corner_radius = egui::CornerRadius::ZERO;
6319    }
6320    let mut viewer = Viewer {
6321        app,
6322        prepared: &cache.tabs,
6323        eject: false,
6324        ejected: None,
6325        groups: groups_of(space.state()),
6326        added: None,
6327    };
6328    let seen = Mutex::new(None);
6329    let painter = AreaPainter::new(&kit, frameless, &seen);
6330    // egui_stack lays the tabs out and takes their input, and follows a
6331    // drag across the areas (the first dock drawn in a pass resolves it
6332    // for all of them); the kit measures and paints the tabs, bars,
6333    // bodies, separators and drop zones (`egui_pop_core::kit`).
6334    space.state_mut().translations = dock_translations(&ctx);
6335    let dock = DockArea::dock(&mut space, area_name(area))
6336        .style(style)
6337        .painter(&painter);
6338    viewer.eject = dock_controls(app).eject_group;
6339    group_gestures(dock, app, &ctx)
6340        .show_close_buttons(false)
6341        .show_add_buttons(dock_controls(app).add_buttons)
6342        .show_leaf_close_all_buttons(false)
6343        .show_leaf_collapse_buttons(false)
6344        .show_inside(ui, &mut viewer);
6345    let ejected = viewer.ejected.take();
6346    let added = viewer.added.take();
6347    let bar = space
6348        .dock(area_name(area))
6349        .and_then(|tree| first_bar(tree, &kit, &cache.tabs));
6350    // The group whose "Eject group" was clicked: its shown tab leads it
6351    // into a window of its own.
6352    let eject = ejected.and_then(|path| {
6353        let leaf = space.state().leaf(path).ok()?;
6354        leaf.tabs.get(leaf.active.0).or(leaf.tabs.first()).cloned()
6355    });
6356    cache_id.set(&ctx, cache);
6357    {
6358        let mut wb = app.workbench_mut();
6359        if let Some(bar) = bar {
6360            wb.bars.insert(area, bar);
6361        }
6362        wb.put_space(space);
6363        wb.note_landing(seen, ctx.cumulative_pass_nr());
6364    }
6365    if let Some(panel) = eject
6366        && let Some(Outcome::Done(Err(e))) =
6367            &app.change_workbench(Change::DetachGroup(panel.clone()))
6368    {
6369        app.workbench_refused(&format!("detach {panel}"), e);
6370    }
6371    open_add_menu(app, &ctx, added);
6372}
6373
6374/// The tab bar of an area's first tabs (where `Layout::place` adds a
6375/// panel), as drawn this pass: `None` when hidden.
6376fn first_bar(
6377    tree: &egui_stack::Tree<PanelId>,
6378    kit: &Kit,
6379    prepared: &HashMap<PanelId, PreparedTab>,
6380) -> Option<TabBar> {
6381    let at = first_leaf(tree);
6382    if at.0 >= tree.len() {
6383        return None;
6384    }
6385    let leaf = tree[at].get_leaf()?;
6386    if leaf.tabs.is_empty() || leaf.tab_bar_hidden {
6387        return None;
6388    }
6389    let height = kit.tab_bar.data.height.max(kit.tab.data.height);
6390    let rect = Rect::from_min_size(leaf.rect.min, egui::vec2(leaf.rect.width(), height));
6391    // The right edge of its last tab: the tabs side by side as wide as
6392    // the kit measures them (`DockPainter::tab_width`), from where they
6393    // are scrolled to; tabs scrolled out end at the bar's right.
6394    let width: f32 = leaf
6395        .tabs
6396        .iter()
6397        .filter_map(|p| prepared.get(p))
6398        .map(|t| t.width)
6399        .sum();
6400    let end = (rect.left() + leaf.scroll + width)
6401        .max(rect.left())
6402        .min(rect.right());
6403    Some(TabBar {
6404        rect,
6405        end,
6406        tabs: leaf.tabs.len(),
6407    })
6408}
6409
6410/// A dock's group gestures, as the application allows and the user
6411/// set them ([`group_handles`], [`group_drag_modifier`]), and the names
6412/// of its grip and move handle, translated.
6413fn group_gestures<'a>(
6414    area: DockArea<'a, PanelId>,
6415    app: &AppHandle,
6416    ctx: &egui::Context,
6417) -> DockArea<'a, PanelId> {
6418    area.group_handles(group_handles(app))
6419        .group_drag_modifiers(group_drag_modifier(app).modifiers())
6420        .group_context_menus(dock_controls(app).group_menus)
6421        .labels(group_labels(ctx))
6422}
6423
6424/// The names of a dock's group grip and a float's move handle, translated.
6425fn group_labels(ctx: &egui::Context) -> egui_stack::Labels {
6426    let mut labels = egui_stack::Labels::default();
6427    labels.move_group = strings::tr(ctx, &txt::WORKBENCH_MOVE_GROUP).into();
6428    labels.move_window = strings::tr(ctx, &txt::WORKBENCH_MOVE_WINDOW).into();
6429    labels
6430}
6431
6432/// A dock's menu texts, translated: its tab menu's "Move group" and that
6433/// submenu's "New window".
6434fn dock_translations(ctx: &egui::Context) -> egui_stack::Translations {
6435    let mut translations = egui_stack::Translations::english();
6436    let menu = &mut translations.tab_context_menu;
6437    menu.move_group_menu = strings::tr(ctx, &txt::WORKBENCH_MOVE_GROUP);
6438    menu.move_group_new_window = strings::tr(ctx, &txt::WORKBENCH_NEW_WINDOW);
6439    translations
6440}
6441
6442/// A dragged tab's drop zone as an area's painter painted it: where, the
6443/// destination, and the reason it is refused (empty when the veto gave
6444/// none).
6445struct Painted {
6446    rect: Rect,
6447    destination: egui_stack::TabDestination,
6448    refusal: Option<String>,
6449}
6450
6451/// The kit as an area's dock painter: everything as the kit paints it,
6452/// except the panels' bodies in a frameless area, which have no border
6453/// there (`AppBuilder::frameless`). It notes where the drop zone of a
6454/// dragged tab is painted, for the drop hint, and, painting the detached
6455/// windows' docks, whether it outlined one (a tab dragged out of another
6456/// window where window positions are hidden).
6457struct AreaPainter<'a> {
6458    kit: &'a Kit,
6459    frameless: bool,
6460    seen: &'a Mutex<Option<Painted>>,
6461    outlined: Option<&'a Mutex<bool>>,
6462}
6463
6464impl<'a> AreaPainter<'a> {
6465    fn new(kit: &'a Kit, frameless: bool, seen: &'a Mutex<Option<Painted>>) -> Self {
6466        Self {
6467            kit,
6468            frameless,
6469            seen,
6470            outlined: None,
6471        }
6472    }
6473
6474    /// Notes each outline it paints in `outlined`.
6475    fn outlines(mut self, outlined: &'a Mutex<bool>) -> Self {
6476        self.outlined = Some(outlined);
6477        self
6478    }
6479}
6480
6481impl egui_stack::DockPainter for AreaPainter<'_> {
6482    fn tab_width(&self, tab: &egui_stack::TabMeasure<'_>) -> f32 {
6483        self.kit.tab_width(tab)
6484    }
6485
6486    fn tab_bar(&self, painter: &egui::Painter, bar: &egui_stack::TabBarPaint<'_>) {
6487        self.kit.tab_bar(painter, bar);
6488    }
6489
6490    fn tab(&self, painter: &egui::Painter, tab: &egui_stack::TabPaint<'_>) {
6491        self.kit.tab(painter, tab);
6492    }
6493
6494    fn tab_bar_tail(&self, painter: &egui::Painter, tail: &egui_stack::TabBarTailPaint<'_>) {
6495        self.kit.tab_bar_tail(painter, tail);
6496    }
6497
6498    fn tab_body(&self, painter: &egui::Painter, body: &egui_stack::TabBodyPaint<'_>) {
6499        if !self.frameless {
6500            self.kit.tab_body(painter, body);
6501        }
6502    }
6503
6504    fn separator(&self, painter: &egui::Painter, separator: &egui_stack::SeparatorPaint<'_>) {
6505        self.kit.separator(painter, separator);
6506    }
6507
6508    fn drop_target(&self, painter: &egui::Painter, target: &egui_stack::DropTargetPaint<'_>) {
6509        self.kit.drop_target(painter, target);
6510    }
6511
6512    fn drop_button(&self, painter: &egui::Painter, button: &egui_stack::DropButtonPaint<'_>) {
6513        self.kit.drop_button(painter, button);
6514    }
6515
6516    /// A detached window's dock outlined (the kit's `dock-preview` border,
6517    /// disabled where the panel may not go), at least
6518    /// [`WINDOW_OUTLINE_WIDTH`] wide.
6519    fn window_outline(
6520        &self,
6521        painter: &egui::Painter,
6522        outline: &egui_stack::WindowOutlinePaint<'_>,
6523    ) {
6524        let style = self
6525            .kit
6526            .dock_preview
6527            .style(State::REST.with(State::DISABLED, outline.refused));
6528        let width = style.border_width.max(WINDOW_OUTLINE_WIDTH);
6529        painter.rect_stroke(
6530            outline.rect,
6531            egui::CornerRadius::same(style.radius.round().clamp(0.0, 255.0) as u8),
6532            egui::Stroke::new(width, style.border_color),
6533            egui::StrokeKind::Inside,
6534        );
6535        if let Some(outlined) = self.outlined
6536            && let Ok(mut o) = outlined.lock()
6537        {
6538            *o = true;
6539        }
6540    }
6541
6542    fn drop_preview(&self, painter: &egui::Painter, drop: &egui_stack::DropPaint<'_>) {
6543        if let Ok(mut seen) = self.seen.lock() {
6544            let refusal = drop.refusal.map(|r| {
6545                r.reason
6546                    .as_ref()
6547                    .map_or_else(String::new, |g| g.text().to_owned())
6548            });
6549            *seen = Some(Painted {
6550                rect: drop.rect,
6551                destination: drop.destination.clone(),
6552                refusal,
6553            });
6554        }
6555        self.kit.drop_preview(painter, drop);
6556    }
6557
6558    fn section_band(&self, painter: &egui::Painter, band: &egui_stack::SectionBandPaint<'_>) {
6559        self.kit.section_band(painter, band);
6560    }
6561
6562    fn section_boundary(
6563        &self,
6564        painter: &egui::Painter,
6565        boundary: &egui_stack::SectionBoundaryPaint<'_>,
6566    ) {
6567        self.kit.section_boundary(painter, boundary);
6568    }
6569
6570    fn tool_item(&self, painter: &egui::Painter, item: &egui_stack::ToolItemPaint<'_>) {
6571        self.kit.tool_item(painter, item);
6572    }
6573
6574    fn tool_more(&self, painter: &egui::Painter, more: &egui_stack::ToolMorePaint<'_>) {
6575        self.kit.tool_more(painter, more);
6576    }
6577
6578    fn tool_separator(
6579        &self,
6580        painter: &egui::Painter,
6581        separator: &egui_stack::ToolSeparatorPaint<'_>,
6582    ) {
6583        self.kit.tool_separator(painter, separator);
6584    }
6585}
6586
6587struct Viewer<'a> {
6588    app: &'a AppHandle,
6589    prepared: &'a HashMap<PanelId, PreparedTab>,
6590    /// Whether the docked tab bars show the "Eject group" button
6591    /// ([`DockControls::eject_group`]).
6592    eject: bool,
6593    /// The group whose "Eject group" button was clicked this pass.
6594    ejected: Option<egui_stack::NodePath>,
6595    /// Each tab group drawn, by its path, with one of its panels: the
6596    /// group its menu and its "+" open a panel in.
6597    groups: Vec<(egui_stack::NodePath, PanelId)>,
6598    /// The group whose "+" was clicked this pass, by one of its panels.
6599    added: Option<PanelId>,
6600}
6601
6602impl Viewer<'_> {
6603    /// A panel of the group at `path`.
6604    fn group_at(&self, path: egui_stack::NodePath) -> Option<&PanelId> {
6605        self.groups.iter().find(|(p, _)| *p == path).map(|(_, g)| g)
6606    }
6607}
6608
6609/// Opens the menu of the closed panels a tab group may take, at the
6610/// pointer: its "+" was clicked (or its menu's "Add tab").
6611fn open_add_menu(app: &AppHandle, ctx: &egui::Context, group: Option<PanelId>) {
6612    let Some(group) = group else { return };
6613    let at = ctx.input(|i| i.pointer.interact_pos()).unwrap_or_default();
6614    crate::menus::popup_at_with(
6615        app,
6616        &panel_menu::MENU_GROUP_ADD,
6617        at,
6618        json!({ "group": group }),
6619    );
6620}
6621
6622/// Each tab group of a dock state, by its path, with its shown panel.
6623fn groups_of(state: &egui_stack::DockState<PanelId>) -> Vec<(egui_stack::NodePath, PanelId)> {
6624    state
6625        .iter_leaves()
6626        .filter_map(|(path, leaf)| {
6627            let p = leaf.tabs.get(leaf.active.0).or(leaf.tabs.first())?;
6628            Some((path, p.clone()))
6629        })
6630        .collect()
6631}
6632
6633/// A tab or a group dragged from another window over this one: the drop
6634/// zone follows the pointer at once (no preference held for a moment, as
6635/// for a drag begun here), the pointer coming from the other window's
6636/// passes.
6637fn from_elsewhere(style: &mut egui_stack::Style, space: &DockSpace<PanelId>, ctx: &egui::Context) {
6638    if space
6639        .dragging()
6640        .is_some_and(|d| d.source != ctx.viewport_id())
6641    {
6642        style.overlay.feel.max_preference_time = 0.0;
6643    }
6644}
6645
6646/// egui_stack's style for an area: its tab bars as high as the kit's
6647/// (the kit paints every part, `egui_pop_core::kit`).
6648fn dock_style(style: &egui::Style, kit: &Kit) -> egui_stack::Style {
6649    let mut s = egui_stack::Style::from_egui(style);
6650    s.tab_bar.height = kit.tab_bar.data.height.max(kit.tab.data.height);
6651    // The kit paints the bodies' borders (`dock-body`); their background
6652    // takes its corners at rest.
6653    let body = kit.dock_body.style(egui_pop_core::kit::State::REST);
6654    s.tab.tab_body.stroke = egui::Stroke::NONE;
6655    s.tab.tab_body.corner_radius =
6656        egui::CornerRadius::same(body.radius.round().clamp(0.0, 255.0) as u8);
6657    // Drops are shown on the node itself (the region the tab would take,
6658    // bordered and tinted), not on a cross of buttons. The kit paints
6659    // them (`dock-preview`); the style says the same for anything
6660    // egui_stack draws by itself.
6661    s.overlay.overlay_type = egui_stack::OverlayType::Zones;
6662    let zone = kit.dock_preview.style(egui_pop_core::kit::State::REST);
6663    s.overlay.zone_fill = zone.fill.gamma_multiply(kit.dock_preview.data.opacity);
6664    s.overlay.zone_stroke = egui::Stroke::new(zone.border_width, zone.border_color);
6665    s.overlay.zone_corner_radius =
6666        egui::CornerRadius::same(zone.radius.round().clamp(0.0, 255.0) as u8);
6667    // The group grip at the end of a tab bar, in the tabs' colours: a
6668    // tab's text at rest, and its text and fill under the pointer.
6669    let rest = kit.tab.style(egui_pop_core::kit::State::REST);
6670    let hover = kit.tab.style(egui_pop_core::kit::State::HOVER);
6671    s.buttons.group_grip_color = rest.text;
6672    s.buttons.group_grip_active_color = hover.text;
6673    s.buttons.group_grip_bg_fill = hover.fill;
6674    s
6675}
6676
6677/// A tab ready for the kit: its title, its label laid out with no colour
6678/// (the kit gives it its state's) and its width as the kit measures it.
6679/// The label is laid out again each pass through egui's own galley cache
6680/// (cheap): a galley kept across passes points into the font atlas of the
6681/// pass it was made in, and a theme that installs other fonts rebuilds
6682/// that atlas, which scrambled the tab labels.
6683#[derive(Clone)]
6684struct PreparedTab {
6685    /// The panel's English title, as declared: translated again only when
6686    /// it changes.
6687    english: String,
6688    title: String,
6689    label: Arc<egui::Galley>,
6690    width: f32,
6691}
6692
6693/// An area's prepared tabs and egui_stack style, kept across passes: a tab
6694/// is translated again only when its title changes, and
6695/// everything when the kit (a theme install, a light or dark switch) or
6696/// the scale changes; the style again when egui's style does. Per dock
6697/// (and one for a dragged tab's ghost).
6698const TAB_CACHE: Slot<TabCache> = Slot::opaque("api.workbench.tab_cache");
6699
6700#[derive(Clone, Default)]
6701struct TabCache {
6702    /// The kit the cache was made for, kept: compared by address, which
6703    /// a kit dropped could otherwise lend to the next one (of another
6704    /// theme, or of the other variant).
6705    kit: Option<Arc<Kit>>,
6706    /// The pixels per point and the strings provider the cache was made
6707    /// for.
6708    key: Option<(u32, Option<usize>)>,
6709    tabs: HashMap<PanelId, PreparedTab>,
6710    /// egui_stack's style and the egui style it was made from (kept, as
6711    /// the kit is).
6712    style: Option<(Arc<egui::Style>, Arc<egui_stack::Style>)>,
6713}
6714
6715impl TabCache {
6716    fn prepare(&mut self, app: &AppHandle, ctx: &egui::Context, kit: &Arc<Kit>, tabs: &[PanelId]) {
6717        let key = (ctx.pixels_per_point().to_bits(), strings::provider_id(ctx));
6718        if self.key != Some(key) || !self.kit.as_ref().is_some_and(|k| Arc::ptr_eq(k, kit)) {
6719            *self = TabCache {
6720                kit: Some(kit.clone()),
6721                key: Some(key),
6722                ..TabCache::default()
6723            };
6724        }
6725        self.tabs.retain(|p, _| tabs.contains(p));
6726        let font = egui::TextStyle::Button.resolve(&ctx.global_style());
6727        let layout = |title: &str| {
6728            let label = ctx.fonts_mut(|f| {
6729                f.layout_no_wrap(title.to_owned(), font.clone(), Color32::PLACEHOLDER)
6730            });
6731            let width = kit.tab.measure(label.size()).x;
6732            (label, width)
6733        };
6734        for panel in tabs {
6735            let english = {
6736                let wb = app.workbench_mut();
6737                let english = wb.spec(panel).map_or(panel.as_str(), |s| s.title.as_str());
6738                if let Some(t) = self.tabs.get_mut(panel).filter(|t| t.english == english) {
6739                    (t.label, t.width) = layout(&t.title);
6740                    continue;
6741                }
6742                english.to_string()
6743            };
6744            let title = app.panel_title(ctx, panel);
6745            let (label, width) = layout(&title);
6746            self.tabs.insert(
6747                panel.clone(),
6748                PreparedTab {
6749                    english,
6750                    title,
6751                    label,
6752                    width,
6753                },
6754            );
6755        }
6756    }
6757
6758    fn dock_style(&mut self, style: &Arc<egui::Style>, kit: &Kit) -> egui_stack::Style {
6759        match &self.style {
6760            Some((from, dock)) if Arc::ptr_eq(from, style) => (**dock).clone(),
6761            _ => {
6762                let dock = dock_style(style, kit);
6763                self.style = Some((style.clone(), Arc::new(dock.clone())));
6764                dock
6765            }
6766        }
6767    }
6768}
6769
6770impl TabViewer for Viewer<'_> {
6771    type Tab = PanelId;
6772
6773    fn id(&mut self, tab: &mut PanelId) -> Id {
6774        Id::unique(("egui_pop.panel", tab.as_str()))
6775    }
6776
6777    fn title(&mut self, tab: &mut PanelId) -> egui::WidgetText {
6778        // The prepared label: egui_stack lays nothing out again.
6779        match self.prepared.get(tab) {
6780            Some(p) => p.label.clone().into(),
6781            None => self.app.panel_title(&self.app.egui(), tab).into(),
6782        }
6783    }
6784
6785    fn ui(&mut self, ui: &mut Ui, tab: &mut PanelId) {
6786        self.app.show_panel(ui, tab);
6787    }
6788
6789    fn on_tab_button(&mut self, tab: &mut PanelId, response: &egui::Response) {
6790        // A tab, named by its panel's title, as egui_stack's accessible tab
6791        // pattern has it: its list names the dock, and the active tab's body
6792        // is a tab panel of the same name.
6793        match self.prepared.get(tab) {
6794            Some(p) => egui_pop_core::a11y::name(response, egui::Role::Tab, &p.title),
6795            None => {
6796                let title = self.app.panel_title(&response.ctx, tab);
6797                egui_pop_core::a11y::name(response, egui::Role::Tab, &title);
6798            }
6799        }
6800        // Its state's mark (`pop.panel.state`) or its kind's, the tab's one
6801        // mark slot.
6802        let kind = self.app.panel_kind(tab);
6803        crate::bus::panel_state::paint_tab(
6804            &self.app.0.bus.panel_states,
6805            response,
6806            tab.as_str(),
6807            kind,
6808        );
6809        if response.has_focus() {
6810            // Painted in the kit's focus state (`DockPainter::tab`).
6811            egui_pop_core::focus::own_ring(&response.ctx, response.id);
6812        }
6813    }
6814
6815    fn context_menu(&mut self, ui: &mut Ui, tab: &mut PanelId, _path: egui_stack::TabPath) {
6816        // The panel menu, the one a floating panel's title opens too.
6817        panel_menu::show(ui, self.app, tab);
6818    }
6819
6820    fn group_context_menu(&mut self, ui: &mut Ui, path: egui_stack::NodePath) {
6821        // Open panel ▸: a panel opened in this group (`pop.panel.open`).
6822        if let Some(group) = self.group_at(path).cloned() {
6823            panel_menu::show_group(ui, self.app, &group);
6824        }
6825    }
6826
6827    fn on_add(&mut self, path: egui_stack::NodePath) {
6828        // The "+", or the group menu's "Add tab": the menu of the closed
6829        // panels this group may take opens once the dock is drawn.
6830        self.added = self.group_at(path).cloned();
6831    }
6832
6833    fn group_bar_buttons(&mut self, _path: egui_stack::NodePath) -> Vec<String> {
6834        if self.eject {
6835            vec![strings::tr(&self.app.egui(), &txt::WORKBENCH_EJECT_GROUP)]
6836        } else {
6837            Vec::new()
6838        }
6839    }
6840
6841    fn on_group_bar_button(
6842        &mut self,
6843        ui: &mut Ui,
6844        path: egui_stack::NodePath,
6845        _index: usize,
6846        response: &egui::Response,
6847    ) {
6848        // The one button: "Eject group", two overlapping windows.
6849        let color = ui.style().interact(response).fg_stroke.color;
6850        let side = egui_pop_core::theme::Tokens::of(ui.ctx()).size.icon_inline;
6851        let rect = Rect::from_center_size(response.rect.center(), egui::vec2(side, side));
6852        egui_pop_core::icon::Icon::WindowRestore.paint(ui.painter(), rect, color);
6853        let tip = strings::tr(&response.ctx, &txt::WORKBENCH_EJECT_GROUP);
6854        response.clone().on_hover_text(tip);
6855        if response.clicked() {
6856            self.ejected = Some(path);
6857        }
6858    }
6859
6860    fn dock_title(&mut self, dock: &str) -> Option<egui::WidgetText> {
6861        dock_title(self.app, &self.app.egui(), dock).map(Into::into)
6862    }
6863
6864    fn allowed_in_windows(&self, _tab: &mut PanelId) -> bool {
6865        // Detached panels get windows of their own (a step), not
6866        // egui_stack's floating windows.
6867        false
6868    }
6869
6870    fn close_policy(&mut self, close: &egui_stack::FloatClose) -> egui_stack::ClosePolicy {
6871        use egui_stack::ClosePolicy;
6872        // Drawn in the main window, its host follows the close (`window_host`).
6873        if self.app.egui().embed_viewports() {
6874            return ClosePolicy::Keep;
6875        }
6876        let Ok(panel) = PanelId::new(close.key.as_str()) else {
6877            return ClosePolicy::Keep;
6878        };
6879        // A detached window's close is the workbench's step
6880        // (`workbench.close_window`), whose default asks the window's
6881        // `pop.window.close`: its panels dock back through the layout, so
6882        // egui_stack only drops the window's tabs from its dock. Vetoed,
6883        // the window stays.
6884        self.app
6885            .change_workbench(Change::CloseWindow(panel.clone()));
6886        let kept = (self.app.workbench_mut().layout.auxiliary.iter()).any(|a| a.panel == panel);
6887        if kept {
6888            ClosePolicy::Keep
6889        } else {
6890            ClosePolicy::CloseTabs
6891        }
6892    }
6893}
6894
6895/// A tab or a group dropped on a detached window: it joins the window's
6896/// tabs (`workbench.join_window`, with `group` for a group), a refusal
6897/// said.
6898fn join_dropped(app: &AppHandle, dragged: &Dragged, window: &PanelId) {
6899    let panel = dragged.lead().clone();
6900    let change = if dragged.is_group() {
6901        Change::JoinWindowGroup(panel.clone(), window.clone())
6902    } else {
6903        Change::JoinWindow(panel.clone(), window.clone())
6904    };
6905    if let Some(Outcome::Done(Err(e))) = &app.change_workbench(change) {
6906        app.workbench_refused(&format!("move {panel}"), e);
6907    }
6908}
6909
6910/// A group let go outside every window: it opens a window of its own
6911/// (`workbench.detach` with `group`), a refusal said.
6912fn detach_dropped(app: &AppHandle, group: &Dragged) {
6913    let panel = group.lead().clone();
6914    if let Some(Outcome::Done(Err(e))) = &app.change_workbench(Change::DetachGroup(panel.clone())) {
6915        app.workbench_refused(&format!("detach {panel}"), e);
6916    }
6917}
6918
6919/// Runs the `workbench.move` step of each tab the space moved into, out
6920/// of or between the application windows' areas (read back from the
6921/// space, `Workbench::read_back`), as a tab dropped in another of the main
6922/// window's areas runs it (`track_drag`): a plugin may veto it, and the
6923/// move is a step. One refused or vetoed puts the areas back as they were
6924/// before the drop. Not while the areas are drawn (a step asked then
6925/// waits for the pass's end, too late to put the drop back).
6926pub(crate) fn settle_area_moves(app: &AppHandle) {
6927    if app.drawing_areas() {
6928        return;
6929    }
6930    let moves = {
6931        let mut wb = app.workbench_mut();
6932        wb.read_back();
6933        wb.area_moves.take()
6934    };
6935    let Some(moves) = moves else {
6936        return;
6937    };
6938    let mut undone = false;
6939    for (panel, (window, area)) in &moves.moved {
6940        let change = match window {
6941            Some(w) => Change::MoveInWindow(panel.clone(), w.clone(), *area),
6942            None => Change::Move(panel.clone(), *area),
6943        };
6944        undone = match &app.change_workbench(change) {
6945            Some(Outcome::Done(Err(e))) => {
6946                app.workbench_refused(&format!("move {panel}"), e);
6947                true
6948            }
6949            Some(Outcome::Vetoed { .. }) => true,
6950            _ => false,
6951        };
6952        if undone {
6953            break;
6954        }
6955    }
6956    if undone {
6957        let mut wb = app.workbench_mut();
6958        wb.layout.areas = moves.areas;
6959        wb.layout.windows = moves.windows;
6960        wb.stale = true;
6961        drop(wb);
6962        app.note_layout("workbench.move");
6963    }
6964}
6965
6966/// A tab or a group dragged at the start of a pass: what, its area, and
6967/// the areas' trees before a drop.
6968type Before = (Dragged, Area, Vec<(Area, Node)>);
6969
6970/// Follows a tab drag across the areas, which egui_stack's space resolves
6971/// (its zones, preview and veto): carries the dragged tab in a drag
6972/// session (`bus::drag`), which the detached windows are targets of and
6973/// which delivers a drop egui_stack cannot see to the window it is let go
6974/// over (`windows`); once let go over no window, runs the
6975/// `workbench.move` step for a tab dropped in another area. A veto, or a
6976/// refusal, puts the areas back as they were before the drop.
6977fn track_drag(app: &AppHandle, ctx: &egui::Context, before: Option<Before>) {
6978    settle_area_moves(app);
6979    let dragged = app.workbench_mut().dragged(ctx);
6980    if let Some((dragged, from, pointer)) = dragged {
6981        let started = app.workbench_mut().dragging.is_none();
6982        if started {
6983            let kind = if dragged.is_group() {
6984                "tab-group"
6985            } else {
6986                "tab"
6987            };
6988            drag::start(ctx, kind, dragged.clone());
6989        }
6990        // The main window's pointer, which keeps following a drag past its
6991        // edges.
6992        let at = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(pointer);
6993        app.workbench_mut().dragging = Some((dragged, from, at));
6994        return;
6995    }
6996    if app.workbench_mut().dragging.take().is_none() {
6997        return;
6998    }
6999    // Let go over a detached window, or outside the main window waiting
7000    // for one to see the pointer (where the system hides where windows
7001    // are), or cancelled: the session has it (`windows`). Let go in the
7002    // main window, over no window: the areas take it.
7003    if drag::waiting(ctx) {
7004        return;
7005    }
7006    // Moved into a detached window's dock: the window's step takes it
7007    // (`settle_drop`), and says it.
7008    let into_window = before.as_ref().is_some_and(|(dragged, ..)| {
7009        let wb = app.workbench_mut();
7010        let at = wb.space.as_ref().map(homes).unwrap_or_default();
7011        dragged
7012            .panels()
7013            .iter()
7014            .any(|p| matches!(at.get(p), Some(Home::Window(_))))
7015    });
7016    if into_window {
7017        return;
7018    }
7019    match drag::ended::<Dragged>(ctx) {
7020        Some((_, End::Left { inside: true })) => drag::claim(ctx, "workbench.areas"),
7021        None => {}
7022        Some(_) => return,
7023    }
7024    let Some((dragged, from, areas)) = before else {
7025        return;
7026    };
7027    // Each panel dropped in another area: its `workbench.move`, as a tab
7028    // dropped there runs; one refused or vetoed puts them all back.
7029    let mut undone = false;
7030    for panel in dragged.panels() {
7031        let to = app.workbench_mut().area_in_space(panel);
7032        let Some(to) = to.filter(|a| *a != from) else {
7033            continue;
7034        };
7035        let out = app.change_workbench(Change::Move(panel.clone(), to));
7036        undone = match &out {
7037            Some(Outcome::Done(Err(e))) => {
7038                app.workbench_refused(&format!("move {panel}"), e);
7039                true
7040            }
7041            Some(Outcome::Vetoed { .. }) => true,
7042            _ => false,
7043        };
7044        if undone {
7045            break;
7046        }
7047    }
7048    if undone {
7049        let mut wb = app.workbench_mut();
7050        wb.layout.areas = areas;
7051        wb.stale = true;
7052    }
7053}
7054
7055/// The drop hint: where the dragged tab would land, as the space resolved
7056/// it this frame (the zone egui_stack painted, the panel's refusal), or a
7057/// palette dragged over an area it docks in, with the ghost of its tab
7058/// where it would go.
7059fn publish_hint(app: &AppHandle, ctx: &egui::Context) {
7060    let mut wb = app.workbench_mut();
7061    wb.hint = None;
7062    if let Some((dragged, _, _)) = wb.dragging.clone() {
7063        // Over a detached window, the window shows where it goes.
7064        if wb.window_drop.is_some() {
7065            return;
7066        }
7067        let panel = dragged.lead().clone();
7068        let Some(seen) = wb.landing.take().filter(|s| dragged.holds(&s.panel)) else {
7069            return;
7070        };
7071        let rect = wb
7072            .landing_rect
7073            .take()
7074            .unwrap_or_else(|| wb.hint_rect(seen.area));
7075        let tabs_at = |path: egui_stack::NodePath| {
7076            wb.space
7077                .as_ref()
7078                .and_then(|s| s.state().leaf(path).ok())
7079                .map_or(0, |leaf| leaf.tabs.iter().filter(|p| **p != panel).count())
7080        };
7081        let (zone, index) = match seen.landing {
7082            Landing::At(i) => (DropZone::Center, Some(i)),
7083            Landing::End(path) => (DropZone::Center, Some(tabs_at(path))),
7084            Landing::Split(zone) => (zone, None),
7085            Landing::Whole { bare: false } => (DropZone::Center, Some(0)),
7086            Landing::Whole { bare: true } => {
7087                let first = wb.space.as_ref().and_then(|s| {
7088                    let surface = s.dock_surface(area_name(seen.area))?;
7089                    let tree = s.dock(area_name(seen.area))?;
7090                    Some(egui_stack::NodePath {
7091                        surface,
7092                        node: first_leaf(tree),
7093                    })
7094                });
7095                (DropZone::Center, Some(first.map_or(0, tabs_at)))
7096            }
7097        };
7098        wb.hint = Some(DropHint {
7099            panel,
7100            area: area_name(seen.area),
7101            rect,
7102            refusal: seen.refusal,
7103            zone,
7104            index,
7105            preview: None,
7106            armed: true,
7107        });
7108        return;
7109    }
7110    // A palette over an area it docks in.
7111    let target = wb
7112        .palette_drag
7113        .clone()
7114        .filter(|_| wb.group_hint.is_none())
7115        .and_then(|d| {
7116            let edge = crate::palettes::magnet(ctx);
7117            wb.dock_at(d.at, edge).map(|to| (d.panel, to, d.armed))
7118        });
7119    let Some((panel, to, armed)) = target else {
7120        return;
7121    };
7122    let Some(spec) = wb.spec(&panel).cloned() else {
7123        return;
7124    };
7125    let rect = wb.hint_rect(to);
7126    let bar = wb.bars.get(&to).copied();
7127    let joined = bar.map_or_else(|| wb.panels_in(to).len(), |b| b.tabs);
7128    let content = wb.content;
7129    drop(wb);
7130    let title = strings::panel_title(ctx, spec.id.as_str(), &spec.title);
7131    let why = refusal(ctx, &spec, &title, to);
7132    let kit = Kit::of(ctx);
7133    // The ghost: the panel's tab, laid out once per drag (a cache of its
7134    // own, as the areas' tabs are), where a drop puts it.
7135    let ghost = if why.is_none() && armed {
7136        let cache_id = TAB_CACHE.keyed("ghost");
7137        let mut cache = cache_id.update(ctx, std::mem::take);
7138        cache.prepare(app, ctx, &kit, std::slice::from_ref(&panel));
7139        let prep = cache.tabs.get(&panel).cloned();
7140        cache_id.set(ctx, cache);
7141        prep.map(|p| {
7142            let at = ghost_rect(&kit, bar, rect, content, p.width);
7143            (p, at)
7144        })
7145    } else {
7146        None
7147    };
7148    app.workbench_mut().hint = Some(DropHint {
7149        panel,
7150        area: area_name(to),
7151        rect,
7152        refusal: why.clone(),
7153        zone: DropZone::Center,
7154        index: Some(joined),
7155        preview: ghost.as_ref().map(|(_, at)| TabPreview {
7156            area: area_name(to),
7157            index: joined,
7158            rect: *at,
7159        }),
7160        armed,
7161    });
7162    // Not armed (a plain drag that only moves): nothing drawn.
7163    if !armed {
7164        return;
7165    }
7166    // The kit's `dock-preview`: at rest where the panel may go, disabled
7167    // with its label saying why where it may not.
7168    let t = egui_pop_core::theme::Tokens::of(ctx);
7169    let painter = ctx.layer_painter(egui::LayerId::new(
7170        egui::Order::Foreground,
7171        Id::unique("egui_pop.workbench.drop"),
7172    ));
7173    let label = why.map(|why| {
7174        let font = egui::FontId::proportional(t.font.body);
7175        ctx.fonts_mut(|f| f.layout_no_wrap(why, font, Color32::PLACEHOLDER))
7176    });
7177    let part = Part {
7178        rect,
7179        room: rect,
7180        state: State::REST.with(State::DISABLED, label.is_some()),
7181        label: label.as_ref(),
7182    };
7183    let cx = KitCx {
7184        painter: &painter,
7185        ppp: ctx.pixels_per_point(),
7186    };
7187    kit.dock_preview.paint_part(&cx, &part);
7188    // Over it, the kit's `tab-preview`.
7189    if let Some((prep, at)) = &ghost {
7190        kit.tab_preview.paint_part(
7191            &cx,
7192            &Part {
7193                rect: *at,
7194                room: *at,
7195                state: State::REST,
7196                label: Some(&prep.label),
7197            },
7198        );
7199    }
7200}
7201
7202/// Where a dragged tab's ghost goes: after the last tab of the area's
7203/// first tab bar (kept inside the bar), else, for an area drawn bare or
7204/// closed, at the top-left of where the hint is (kept inside the areas).
7205fn ghost_rect(kit: &Kit, bar: Option<TabBar>, hint: Rect, content: Rect, width: f32) -> Rect {
7206    let (row, start) = match bar {
7207        Some(b) => (b.rect, b.end),
7208        None => {
7209            let height = kit.tab_bar.data.height.max(kit.tab.data.height);
7210            let row = Rect::from_min_size(hint.min, egui::vec2(hint.width(), height));
7211            let room = if content.is_positive() { content } else { row };
7212            (
7213                Rect::from_x_y_ranges(room.x_range(), row.y_range()),
7214                hint.left(),
7215            )
7216        }
7217    };
7218    let x = start.min(row.right() - width).max(row.left());
7219    Rect::from_min_size(egui::pos2(x, row.top()), egui::vec2(width, row.height()))
7220}
7221
7222#[cfg(test)]
7223mod tests {
7224    use super::*;
7225
7226    #[test]
7227    fn the_former_panels_sizes_carry_over_once() {
7228        // A session saved before the shell was laid out by egui_stack:
7229        // the areas' egui panels kept their outer rect.
7230        let ctx = egui::Context::default();
7231        let scope = Id::unique("scope");
7232        let store = |area: Area, rect: Rect| {
7233            let state = egui::containers::panel::PanelState { outer_rect: rect };
7234            ctx.data_mut(|d| d.insert_persisted(scope.with(dock_id(area)), state));
7235        };
7236        store(
7237            Area::StartSide,
7238            Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(312.0, 700.0)),
7239        );
7240        store(
7241            Area::Bottom,
7242            Rect::from_min_size(egui::pos2(0.0, 500.0), egui::vec2(900.0, 180.0)),
7243        );
7244        // The side's width, the bottom's height; none for the end side.
7245        let sizes = migrate_sizes(None, |a| old_panel_size(&ctx, scope, a));
7246        assert_eq!(sizes.get("start_side"), Some(&312.0));
7247        assert_eq!(sizes.get("bottom"), Some(&180.0));
7248        assert_eq!(sizes.get("end_side"), None);
7249        // What the layout saved since wins over the former panel's.
7250        let saved = BTreeMap::from([("start_side".to_owned(), 250.0)]);
7251        let sizes = migrate_sizes(Some(saved), |a| old_panel_size(&ctx, scope, a));
7252        assert_eq!(sizes.get("start_side"), Some(&250.0));
7253        assert_eq!(sizes.get("bottom"), Some(&180.0));
7254    }
7255
7256    #[test]
7257    fn the_shell_tree_follows_the_alignment_and_the_side_bar_position() {
7258        let leaf = |area: Area| Zone::leaf(area_name(area), Content::Dock(area_name(area).into()));
7259        let order = |zone: &Zone| {
7260            let mut names = Vec::new();
7261            zone.visit(&mut |z| {
7262                if matches!(z.kind, egui_stack::layout::ZoneKind::Leaf { .. }) {
7263                    names.push(z.name.0.clone());
7264                }
7265            });
7266            names
7267        };
7268        // The default: the side bars down to the bottom, the bottom area
7269        // under the centre; leaves left to right, top to bottom.
7270        let tree = shell_tree(&PanelAlignment::Center.order(), false, Some(320.0), &leaf);
7271        assert_eq!(order(&tree), ["start_side", "center", "bottom", "end_side"]);
7272        let centre = tree.find("center").unwrap();
7273        assert!(centre.constraints.grow);
7274        // The middle, between the side bars, keeps the centre's least width.
7275        let middle = tree.find("around.end_side").unwrap();
7276        let inner = &middle.children()[0];
7277        assert_eq!(inner.constraints.min, Some(Size::Points(320.0)));
7278        // The side bar on the right: the start side last.
7279        let tree = shell_tree(&PanelAlignment::Center.order(), true, None, &leaf);
7280        assert_eq!(tree.children()[1].name.0, "start_side");
7281        // Justified: the bottom area across the whole width.
7282        let tree = shell_tree(&PanelAlignment::Justify.order(), false, None, &leaf);
7283        assert_eq!(tree.children()[1].name.0, "bottom");
7284    }
7285
7286    #[test]
7287    fn a_window_opened_again_takes_egui_pops_place_and_egui_stacks_copy_goes() {
7288        let panel = PanelId::from_static("demo.log");
7289        let kept = [700.0, 50.0, 500.0, 300.0];
7290        let aux = Auxiliary::window(panel.clone(), crate::window::UNNAMED_SCREEN, kept);
7291        let mut floats = ZoneLayout::new(Zone::leaf("windows", Content::Empty));
7292        let mut space = to_space(&Layout::default());
7293        // egui_stack closed the window's float somewhere else: it kept
7294        // that place in its own terms.
7295        let mut elsewhere = window_host::float_of(&aux, &[]);
7296        elsewhere.place = egui_stack::layout::Place::new(Rect::from_min_size(
7297            egui::pos2(10.0, 10.0),
7298            egui::vec2(200.0, 100.0),
7299        ));
7300        floats.open_float(elsewhere);
7301        floats.close_float(panel.as_str());
7302        assert!(floats.closed_place(panel.as_str()).is_some());
7303        // Detached again: egui-pop's place, and no second copy left.
7304        sync_floats(&mut floats, &mut space, std::slice::from_ref(&aux), &[]);
7305        let open = floats.float_mut(panel.as_str()).expect("open again");
7306        assert_eq!(open.place, window_host::float_of(&aux, &[]).place);
7307        assert!(floats.closed.is_empty());
7308    }
7309}