Skip to main content

sui_widgets/
docking.rs

1//! Retained, same-window docking workspace for editor-style applications.
2//!
3//! The workspace owns every registered panel widget in one stable registry.
4//! Docking, tab selection, and floating only change the logical layout graph;
5//! a panel's [`WidgetId`] and widget-local state therefore survive layout
6//! changes. Native operating-system window tear-out is intentionally outside
7//! this widget's scope.
8
9use crate::draw::inset_rect_evenly;
10use std::{
11    borrow::Cow,
12    collections::{HashMap, HashSet},
13    fmt,
14    sync::{Arc, Mutex, MutexGuard, PoisonError},
15};
16use sui_text::TextAlign;
17
18use sui_core::{
19    Event, KeyState, Point, PointerButton, PointerEventKind, Rect, SemanticsAction,
20    SemanticsActionRequest, SemanticsNode, SemanticsRole, SemanticsValue, Size, Vector, WidgetId,
21};
22use sui_layout::{Axis, Constraints};
23use sui_reactive::Signal;
24use sui_runtime::{
25    ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, SemanticsCtx, StackHostOptions, StackOrderPolicy,
26    Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
27};
28
29use crate::controls::draw_icon_glyph;
30#[cfg(feature = "serde")]
31#[path = "docking_serde.rs"]
32mod serde_support;
33
34use crate::frame::{snap_to_pixels, stroke_border};
35use crate::{DefaultTheme, IconGlyph, text_align::paint_text_line};
36
37const MAX_DOCK_DEPTH: usize = 64;
38const MAX_DOCK_NODES: usize = 4_096;
39const MAX_FLOATING_GROUPS: usize = 256;
40const MIN_SPLIT_FRACTION: f32 = 0.05;
41const MAX_SPLIT_FRACTION: f32 = 0.95;
42const DEFAULT_SPLITTER_THICKNESS: f32 = 4.0;
43const MIN_DOCK_PANE_EXTENT: f32 = 96.0;
44const MIN_FLOATING_WIDTH: f32 = 180.0;
45const MIN_FLOATING_HEIGHT: f32 = 120.0;
46const FLOATING_RESIZE_HANDLE: f32 = 16.0;
47const FLOATING_GRIP_WIDTH: f32 = 32.0;
48const TAB_DRAG_THRESHOLD: f32 = 5.0;
49const DROP_EDGE_FRACTION: f32 = 0.24;
50const DROP_ZONE_INSET: f32 = 6.0;
51const SEMANTIC_SPLIT_STEP: f32 = 0.05;
52const TAB_TEXT_INSET: f32 = 8.0;
53const TAB_ICON_EXTENT: f32 = 14.0;
54const TAB_CLOSE_EXTENT: f32 = 16.0;
55const TAB_DIRTY_EXTENT: f32 = 6.0;
56const TAB_PART_GAP: f32 = 6.0;
57const TAB_MIN_WIDTH: f32 = 72.0;
58const TAB_MAX_TITLE_WIDTH: f32 = 180.0;
59const TAB_MIN_CLOSE_WIDTH: f32 = 44.0;
60const TAB_MIN_ICON_WIDTH: f32 = 64.0;
61const TAB_INSERT_INDICATOR: f32 = 2.0;
62
63/// Stable application-defined identity for one dockable panel.
64///
65/// Persist this value in application settings. It is deliberately independent
66/// from the runtime-generated [`WidgetId`]. Zero is reserved as an invalid ID.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68pub struct DockPanelId(u64);
69
70impl DockPanelId {
71    pub const fn new(raw: u64) -> Self {
72        Self(raw)
73    }
74
75    pub const fn get(self) -> u64 {
76        self.0
77    }
78
79    const fn is_valid(self) -> bool {
80        self.0 != 0
81    }
82}
83
84impl From<u64> for DockPanelId {
85    fn from(value: u64) -> Self {
86        Self::new(value)
87    }
88}
89
90impl From<DockPanelId> for u64 {
91    fn from(value: DockPanelId) -> Self {
92        value.get()
93    }
94}
95
96impl fmt::Display for DockPanelId {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        write!(formatter, "{}", self.0)
99    }
100}
101
102/// One node in the persisted docking graph.
103#[derive(Debug, Clone, PartialEq, Default)]
104pub enum DockNode {
105    #[default]
106    Empty,
107    Tabs {
108        panels: Vec<DockPanelId>,
109        active: DockPanelId,
110    },
111    Split {
112        axis: Axis,
113        fraction: f32,
114        first: Box<DockNode>,
115        second: Box<DockNode>,
116    },
117}
118
119impl DockNode {
120    pub const fn empty() -> Self {
121        Self::Empty
122    }
123
124    pub fn tabs(panels: impl IntoIterator<Item = DockPanelId>, active: DockPanelId) -> Self {
125        Self::Tabs {
126            panels: panels.into_iter().collect(),
127            active,
128        }
129    }
130
131    pub fn split(axis: Axis, fraction: f32, first: Self, second: Self) -> Self {
132        Self::Split {
133            axis,
134            fraction: normalize_fraction(fraction),
135            first: Box::new(first),
136            second: Box::new(second),
137        }
138    }
139
140    pub const fn is_empty(&self) -> bool {
141        matches!(self, Self::Empty)
142    }
143}
144
145/// A tab group floating above the docked graph inside the same SUI window.
146///
147/// `bounds` is relative to the workspace's top-left corner, so a saved
148/// layout holds wherever the workspace is placed or scrolled.
149#[derive(Debug, Clone, PartialEq)]
150pub struct DockFloatingGroup {
151    pub id: u64,
152    pub panels: Vec<DockPanelId>,
153    pub active: DockPanelId,
154    pub bounds: Rect,
155}
156
157impl DockFloatingGroup {
158    pub fn new(
159        id: u64,
160        panels: impl IntoIterator<Item = DockPanelId>,
161        active: DockPanelId,
162        bounds: Rect,
163    ) -> Self {
164        Self {
165            id,
166            panels: panels.into_iter().collect(),
167            active,
168            bounds,
169        }
170    }
171}
172
173/// Plain persistence boundary for a docking workspace.
174///
175/// SUI does not prescribe a serializer or settings location. Applications may
176/// map this value into their own versioned settings format and later restore it
177/// through [`DockWorkspaceState::apply_snapshot`]. Floating groups are ordered
178/// back-to-front.
179#[derive(Debug, Clone, PartialEq, Default)]
180pub struct DockWorkspaceSnapshot {
181    pub root: DockNode,
182    pub floating: Vec<DockFloatingGroup>,
183    pub hidden: Vec<DockPanelId>,
184}
185
186impl DockWorkspaceSnapshot {
187    pub fn new(root: DockNode) -> Self {
188        Self {
189            root,
190            floating: Vec::new(),
191            hidden: Vec::new(),
192        }
193    }
194
195    pub fn with_floating(mut self, group: DockFloatingGroup) -> Self {
196        self.floating.push(group);
197        self
198    }
199
200    pub fn with_hidden(mut self, panel: DockPanelId) -> Self {
201        self.hidden.push(panel);
202        self
203    }
204
205    /// Drops every panel `keep` rejects and collapses the groups and splits
206    /// left empty.
207    ///
208    /// Use it before restoring a saved layout whose panels may no longer all
209    /// exist, such as documents that were deleted or extensions that were
210    /// removed.
211    pub fn retain_panels(&mut self, keep: impl Fn(DockPanelId) -> bool) {
212        let mut panels = HashSet::new();
213        collect_snapshot_panels(self, &mut panels);
214        for panel in panels {
215            if !keep(panel) {
216                remove_panel_from_snapshot(self, panel);
217            }
218        }
219    }
220}
221
222/// Destination zone used when docking a panel relative to a tab group or the
223/// workspace root.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum DockZone {
226    Center,
227    Left,
228    Right,
229    Top,
230    Bottom,
231}
232
233/// Presentation and behavior of one dock panel's tab.
234///
235/// Options are owned by the workspace's panel registry. Change them after
236/// registration with [`DockWorkspaceState::update_panel`].
237#[derive(Debug, Clone, PartialEq)]
238pub struct DockPanelOptions {
239    pub title: String,
240    pub icon: Option<IconGlyph>,
241    /// Shows a close button on the tab. A close press is routed through
242    /// [`DockWorkspace::on_close_request`].
243    pub closable: bool,
244    /// Marks the tab as holding unsaved changes.
245    pub dirty: bool,
246    /// Smallest content size the panel remains usable at. Splits keep every
247    /// docked group, and the workspace keeps every floating group, at least
248    /// this large while the workspace has room.
249    pub min_size: Size,
250}
251
252impl DockPanelOptions {
253    pub fn new(title: impl Into<String>) -> Self {
254        Self {
255            title: title.into(),
256            icon: None,
257            closable: false,
258            dirty: false,
259            min_size: Size::ZERO,
260        }
261    }
262
263    pub fn icon(mut self, icon: IconGlyph) -> Self {
264        self.icon = Some(icon);
265        self
266    }
267
268    pub fn closable(mut self, closable: bool) -> Self {
269        self.closable = closable;
270        self
271    }
272
273    pub fn dirty(mut self, dirty: bool) -> Self {
274        self.dirty = dirty;
275        self
276    }
277
278    pub fn min_size(mut self, min_size: Size) -> Self {
279        self.min_size = min_size;
280        self
281    }
282}
283
284impl From<&str> for DockPanelOptions {
285    fn from(title: &str) -> Self {
286        Self::new(title)
287    }
288}
289
290impl From<String> for DockPanelOptions {
291    fn from(title: String) -> Self {
292        Self::new(title)
293    }
294}
295
296/// Where a panel added at runtime first appears.
297#[derive(Debug, Clone, Copy, PartialEq)]
298pub enum DockPlacement {
299    /// Relative to the whole docked graph.
300    Root(DockZone),
301    /// Relative to the tab group that contains `target`.
302    Beside { target: DockPanelId, zone: DockZone },
303    /// In a new same-window floating group.
304    Floating(Rect),
305    /// Registered but not shown until [`DockWorkspaceState::show`].
306    Hidden,
307}
308
309/// What the workspace does after a tab's close button is pressed.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
311pub enum DockCloseAction {
312    /// Keep the panel widget and move it to the hidden list.
313    #[default]
314    Hide,
315    /// Drop the panel widget and forget its ID.
316    Remove,
317    /// Leave the panel open, for example while the application asks about
318    /// unsaved changes.
319    Keep,
320}
321
322/// Validation or mutation failure for a docking layout.
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub struct DockLayoutError {
325    message: String,
326}
327
328impl DockLayoutError {
329    fn new(message: impl Into<String>) -> Self {
330        Self {
331            message: message.into(),
332        }
333    }
334}
335
336impl fmt::Display for DockLayoutError {
337    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
338        formatter.write_str(&self.message)
339    }
340}
341
342impl std::error::Error for DockLayoutError {}
343
344/// Cloneable observable state for [`DockWorkspace`].
345#[derive(Clone)]
346pub struct DockWorkspaceState {
347    snapshot: Signal<DockWorkspaceSnapshot>,
348    registry: Arc<Mutex<DockRegistryQueue>>,
349    registry_revision: Signal<u64>,
350}
351
352impl fmt::Debug for DockWorkspaceState {
353    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
354        formatter
355            .debug_struct("DockWorkspaceState")
356            .field("snapshot", &self.snapshot)
357            .field("pending_registry_ops", &self.registry().ops.len())
358            .finish()
359    }
360}
361
362/// Registry changes requested through the state and applied by the workspace
363/// widget, which owns the panel widgets, on its next measure pass.
364///
365/// The queue holds plain data only, so the state stays `Send + Sync` and can
366/// be driven from another thread like the layout signal it sits beside.
367#[derive(Default)]
368struct DockRegistryQueue {
369    registered: HashSet<DockPanelId>,
370    ops: Vec<DockRegistryOp>,
371}
372
373enum DockRegistryOp {
374    Add {
375        id: DockPanelId,
376        options: DockPanelOptions,
377    },
378    Remove(DockPanelId),
379    Update {
380        id: DockPanelId,
381        update: Box<dyn FnOnce(&mut DockPanelOptions) + Send>,
382    },
383}
384
385impl DockWorkspaceState {
386    pub fn new(snapshot: DockWorkspaceSnapshot) -> Result<Self, DockLayoutError> {
387        validate_snapshot(&snapshot)?;
388        Ok(Self {
389            snapshot: Signal::named("Dock workspace state", snapshot),
390            registry: Arc::new(Mutex::new(DockRegistryQueue::default())),
391            registry_revision: Signal::named("Dock workspace panel registry", 0),
392        })
393    }
394
395    pub fn empty() -> Self {
396        Self::new(DockWorkspaceSnapshot::default())
397            .expect("the empty dock workspace snapshot is valid")
398    }
399
400    pub fn snapshot(&self) -> DockWorkspaceSnapshot {
401        self.snapshot.get()
402    }
403
404    /// Applies a structurally valid dock graph.
405    ///
406    /// Panel widgets are registered by [`DockWorkspace`], not by this state
407    /// object, so this method cannot reject otherwise-valid snapshots that
408    /// reference an unregistered panel ID. Prefer
409    /// [`DockWorkspace::apply_snapshot`] when restoring application-owned
410    /// settings after the panel registry has been assembled.
411    pub fn apply_snapshot(&self, snapshot: DockWorkspaceSnapshot) -> Result<bool, DockLayoutError> {
412        validate_snapshot(&snapshot)?;
413        Ok(self.snapshot.set(snapshot))
414    }
415
416    pub fn dock(
417        &self,
418        panel: DockPanelId,
419        target: DockPanelId,
420        zone: DockZone,
421    ) -> Result<bool, DockLayoutError> {
422        validate_panel_id(panel)?;
423        validate_panel_id(target)?;
424        if panel == target {
425            return self.activate(panel);
426        }
427
428        self.mutate(|snapshot| {
429            if !visible_snapshot_contains_panel(snapshot, target) {
430                return Err(DockLayoutError::new(format!(
431                    "dock target panel {target} is not visible in the workspace"
432                )));
433            }
434            remove_panel_from_snapshot(snapshot, panel);
435
436            if dock_into_root_node(&mut snapshot.root, panel, target, zone) {
437                return Ok(());
438            }
439
440            let Some(group) = snapshot
441                .floating
442                .iter_mut()
443                .find(|group| group.panels.contains(&target))
444            else {
445                return Err(DockLayoutError::new(format!(
446                    "dock target panel {target} disappeared during mutation"
447                )));
448            };
449            if zone != DockZone::Center {
450                return Err(DockLayoutError::new(
451                    "floating tab groups accept center docking only",
452                ));
453            }
454            insert_tab(&mut group.panels, &mut group.active, panel);
455            Ok(())
456        })
457    }
458
459    pub fn dock_to_root(
460        &self,
461        panel: DockPanelId,
462        zone: DockZone,
463    ) -> Result<bool, DockLayoutError> {
464        validate_panel_id(panel)?;
465        self.mutate(|snapshot| {
466            remove_panel_from_snapshot(snapshot, panel);
467            let incoming = DockNode::tabs([panel], panel);
468            if snapshot.root.is_empty() {
469                snapshot.root = incoming;
470                return Ok(());
471            }
472
473            if zone == DockZone::Center {
474                if insert_into_first_tab_group(&mut snapshot.root, panel) {
475                    return Ok(());
476                }
477                snapshot.root = incoming;
478                return Ok(());
479            }
480
481            let previous = std::mem::take(&mut snapshot.root);
482            snapshot.root = split_for_zone(previous, incoming, zone);
483            Ok(())
484        })
485    }
486
487    pub fn float_panel(&self, panel: DockPanelId, bounds: Rect) -> Result<u64, DockLayoutError> {
488        validate_panel_id(panel)?;
489        validate_floating_bounds(bounds)?;
490        let mut assigned = 0;
491        self.mutate(|snapshot| {
492            remove_panel_from_snapshot(snapshot, panel);
493            assigned = next_floating_group_id(snapshot)?;
494            snapshot.floating.push(DockFloatingGroup::new(
495                assigned,
496                [panel],
497                panel,
498                normalized_floating_bounds(bounds),
499            ));
500            Ok(())
501        })?;
502        Ok(assigned)
503    }
504
505    pub fn hide(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
506        validate_panel_id(panel)?;
507        self.mutate(|snapshot| {
508            remove_panel_from_snapshot(snapshot, panel);
509            if !snapshot.hidden.contains(&panel) {
510                snapshot.hidden.push(panel);
511            }
512            Ok(())
513        })
514    }
515
516    pub fn show(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
517        validate_panel_id(panel)?;
518        self.mutate(|snapshot| {
519            snapshot.hidden.retain(|candidate| *candidate != panel);
520            if snapshot_contains_panel(snapshot, panel) {
521                activate_panel(snapshot, panel);
522            } else if !insert_into_first_tab_group(&mut snapshot.root, panel) {
523                snapshot.root = DockNode::tabs([panel], panel);
524            }
525            Ok(())
526        })
527    }
528
529    pub fn activate(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
530        validate_panel_id(panel)?;
531        self.mutate(|snapshot| {
532            if !activate_panel(snapshot, panel) {
533                return Err(DockLayoutError::new(format!(
534                    "panel {panel} is not visible in the workspace"
535                )));
536            }
537            Ok(())
538        })
539    }
540
541    pub fn set_floating_bounds(
542        &self,
543        group_id: u64,
544        bounds: Rect,
545    ) -> Result<bool, DockLayoutError> {
546        validate_floating_bounds(bounds)?;
547        self.mutate(|snapshot| {
548            let Some(group) = snapshot
549                .floating
550                .iter_mut()
551                .find(|group| group.id == group_id)
552            else {
553                return Err(DockLayoutError::new(format!(
554                    "floating group {group_id} does not exist"
555                )));
556            };
557            group.bounds = normalized_floating_bounds(bounds);
558            Ok(())
559        })
560    }
561
562    pub fn bring_floating_to_front(&self, group_id: u64) -> Result<bool, DockLayoutError> {
563        self.mutate(|snapshot| {
564            let Some(index) = snapshot
565                .floating
566                .iter()
567                .position(|group| group.id == group_id)
568            else {
569                return Err(DockLayoutError::new(format!(
570                    "floating group {group_id} does not exist"
571                )));
572            };
573            if index + 1 != snapshot.floating.len() {
574                let group = snapshot.floating.remove(index);
575                snapshot.floating.push(group);
576            }
577            Ok(())
578        })
579    }
580
581    /// Moves `panel` into the tab group that contains `anchor`, immediately
582    /// before or after the anchor's tab, and activates it.
583    ///
584    /// Use it to reorder tabs within a group as well as to insert a tab at a
585    /// chosen position in another group.
586    pub fn dock_tab(
587        &self,
588        panel: DockPanelId,
589        anchor: DockPanelId,
590        after: bool,
591    ) -> Result<bool, DockLayoutError> {
592        validate_panel_id(panel)?;
593        validate_panel_id(anchor)?;
594        if panel == anchor {
595            return self.activate(panel);
596        }
597        self.mutate(|snapshot| {
598            if !visible_snapshot_contains_panel(snapshot, anchor) {
599                return Err(DockLayoutError::new(format!(
600                    "dock anchor panel {anchor} is not visible in the workspace"
601                )));
602            }
603            remove_panel_from_snapshot(snapshot, panel);
604            if insert_tab_beside_in_node(&mut snapshot.root, panel, anchor, after) {
605                return Ok(());
606            }
607            let Some(group) = snapshot
608                .floating
609                .iter_mut()
610                .find(|group| group.panels.contains(&anchor))
611            else {
612                return Err(DockLayoutError::new(format!(
613                    "dock anchor panel {anchor} disappeared during mutation"
614                )));
615            };
616            insert_tab_beside(&mut group.panels, &mut group.active, panel, anchor, after);
617            Ok(())
618        })
619    }
620
621    /// Registers a panel while the workspace is mounted and places it.
622    ///
623    /// The workspace creates the panel's widget on its next measure pass by
624    /// calling its [`DockWorkspace::panel_builder`] with `id`. The ID must not
625    /// belong to a panel that is already registered.
626    pub fn add_panel(
627        &self,
628        id: DockPanelId,
629        options: impl Into<DockPanelOptions>,
630        placement: DockPlacement,
631    ) -> Result<(), DockLayoutError> {
632        validate_panel_id(id)?;
633        if self.registry().registered.contains(&id) {
634            return Err(DockLayoutError::new(format!(
635                "dock panel {id} is already registered"
636            )));
637        }
638        match placement {
639            DockPlacement::Root(zone) => {
640                self.dock_to_root(id, zone)?;
641            }
642            DockPlacement::Beside { target, zone } => {
643                self.dock(id, target, zone)?;
644            }
645            DockPlacement::Floating(bounds) => {
646                self.float_panel(id, bounds)?;
647            }
648            DockPlacement::Hidden => {
649                self.hide(id)?;
650            }
651        }
652        {
653            let mut registry = self.registry();
654            registry.registered.insert(id);
655            registry.ops.push(DockRegistryOp::Add {
656                id,
657                options: options.into(),
658            });
659        }
660        self.bump_registry();
661        Ok(())
662    }
663
664    /// Removes a panel from the layout and drops its widget.
665    ///
666    /// Returns whether the panel was registered. Unlike [`Self::hide`], the
667    /// panel's widget-local state is discarded and its ID may be reused.
668    pub fn remove_panel(&self, id: DockPanelId) -> Result<bool, DockLayoutError> {
669        validate_panel_id(id)?;
670        self.mutate(|snapshot| {
671            remove_panel_from_snapshot(snapshot, id);
672            Ok(())
673        })?;
674        let was_registered = {
675            let mut registry = self.registry();
676            let was_registered = registry.registered.remove(&id);
677            if was_registered {
678                registry.ops.push(DockRegistryOp::Remove(id));
679            }
680            was_registered
681        };
682        if was_registered {
683            self.bump_registry();
684        }
685        Ok(was_registered)
686    }
687
688    /// Changes a registered panel's tab options, such as its title or its
689    /// unsaved-changes marker.
690    pub fn update_panel(
691        &self,
692        id: DockPanelId,
693        update: impl FnOnce(&mut DockPanelOptions) + Send + 'static,
694    ) -> Result<(), DockLayoutError> {
695        validate_panel_id(id)?;
696        {
697            let mut registry = self.registry();
698            if !registry.registered.contains(&id) {
699                return Err(DockLayoutError::new(format!(
700                    "dock panel {id} is not registered"
701                )));
702            }
703            registry.ops.push(DockRegistryOp::Update {
704                id,
705                update: Box::new(update),
706            });
707        }
708        self.bump_registry();
709        Ok(())
710    }
711
712    /// Whether a panel widget is registered or queued for registration.
713    pub fn is_registered(&self, id: DockPanelId) -> bool {
714        self.registry().registered.contains(&id)
715    }
716
717    fn registry(&self) -> MutexGuard<'_, DockRegistryQueue> {
718        self.registry.lock().unwrap_or_else(PoisonError::into_inner)
719    }
720
721    fn bump_registry(&self) {
722        self.registry_revision
723            .set(self.registry_revision.get().wrapping_add(1));
724    }
725
726    fn mutate(
727        &self,
728        mutate: impl FnOnce(&mut DockWorkspaceSnapshot) -> Result<(), DockLayoutError>,
729    ) -> Result<bool, DockLayoutError> {
730        let mut snapshot = self.snapshot();
731        let previous = snapshot.clone();
732        mutate(&mut snapshot)?;
733        validate_snapshot(&snapshot)?;
734        if snapshot == previous {
735            return Ok(false);
736        }
737        Ok(self.snapshot.set(snapshot))
738    }
739
740    fn set_split_fraction(
741        &self,
742        path: &[DockBranch],
743        fraction: f32,
744    ) -> Result<bool, DockLayoutError> {
745        self.mutate(|snapshot| {
746            let Some(node) = node_at_path_mut(&mut snapshot.root, path) else {
747                return Err(DockLayoutError::new("split path is no longer valid"));
748            };
749            let DockNode::Split {
750                fraction: current, ..
751            } = node
752            else {
753                return Err(DockLayoutError::new(
754                    "split path does not identify a split node",
755                ));
756            };
757            *current = normalize_fraction(fraction);
758            Ok(())
759        })
760    }
761}
762
763impl Default for DockWorkspaceState {
764    fn default() -> Self {
765        Self::empty()
766    }
767}
768
769fn validate_panel_id(panel: DockPanelId) -> Result<(), DockLayoutError> {
770    if panel.is_valid() {
771        Ok(())
772    } else {
773        Err(DockLayoutError::new("dock panel ID zero is reserved"))
774    }
775}
776
777fn validate_snapshot(snapshot: &DockWorkspaceSnapshot) -> Result<(), DockLayoutError> {
778    if snapshot.floating.len() > MAX_FLOATING_GROUPS {
779        return Err(DockLayoutError::new(format!(
780            "dock snapshot contains more than {MAX_FLOATING_GROUPS} floating groups"
781        )));
782    }
783
784    let mut panels = HashSet::new();
785    let mut node_count = 0;
786    validate_node(&snapshot.root, 0, &mut node_count, &mut panels)?;
787
788    let mut floating_ids = HashSet::new();
789    for group in &snapshot.floating {
790        if group.id == 0 || !floating_ids.insert(group.id) {
791            return Err(DockLayoutError::new(format!(
792                "floating group ID {} is zero or duplicated",
793                group.id
794            )));
795        }
796        if group.panels.is_empty() {
797            return Err(DockLayoutError::new(format!(
798                "floating group {} has no panels",
799                group.id
800            )));
801        }
802        if !group.panels.contains(&group.active) {
803            return Err(DockLayoutError::new(format!(
804                "floating group {} active panel {} is not a member",
805                group.id, group.active
806            )));
807        }
808        validate_floating_bounds(group.bounds)?;
809        for panel in &group.panels {
810            validate_panel_id(*panel)?;
811            if !panels.insert(*panel) {
812                return Err(DockLayoutError::new(format!(
813                    "panel {panel} appears more than once in the dock snapshot"
814                )));
815            }
816        }
817    }
818
819    for panel in &snapshot.hidden {
820        validate_panel_id(*panel)?;
821        if !panels.insert(*panel) {
822            return Err(DockLayoutError::new(format!(
823                "panel {panel} appears more than once in the dock snapshot"
824            )));
825        }
826    }
827    Ok(())
828}
829
830fn validate_node(
831    node: &DockNode,
832    depth: usize,
833    node_count: &mut usize,
834    panels: &mut HashSet<DockPanelId>,
835) -> Result<(), DockLayoutError> {
836    if depth > MAX_DOCK_DEPTH {
837        return Err(DockLayoutError::new(format!(
838            "dock graph exceeds maximum depth {MAX_DOCK_DEPTH}"
839        )));
840    }
841    *node_count += 1;
842    if *node_count > MAX_DOCK_NODES {
843        return Err(DockLayoutError::new(format!(
844            "dock graph exceeds maximum node count {MAX_DOCK_NODES}"
845        )));
846    }
847
848    match node {
849        DockNode::Empty => Ok(()),
850        DockNode::Tabs {
851            panels: members,
852            active,
853        } => {
854            if members.is_empty() {
855                return Err(DockLayoutError::new(
856                    "dock tab nodes must contain at least one panel",
857                ));
858            }
859            if !members.contains(active) {
860                return Err(DockLayoutError::new(format!(
861                    "active panel {active} is not a member of its dock tab node"
862                )));
863            }
864            for panel in members {
865                validate_panel_id(*panel)?;
866                if !panels.insert(*panel) {
867                    return Err(DockLayoutError::new(format!(
868                        "panel {panel} appears more than once in the dock snapshot"
869                    )));
870                }
871            }
872            Ok(())
873        }
874        DockNode::Split {
875            fraction,
876            first,
877            second,
878            ..
879        } => {
880            if !fraction.is_finite()
881                || *fraction < MIN_SPLIT_FRACTION
882                || *fraction > MAX_SPLIT_FRACTION
883            {
884                return Err(DockLayoutError::new(format!(
885                    "dock split fraction {fraction} is outside {MIN_SPLIT_FRACTION}..={MAX_SPLIT_FRACTION}"
886                )));
887            }
888            if first.is_empty() || second.is_empty() {
889                return Err(DockLayoutError::new(
890                    "dock split nodes cannot contain an empty branch",
891                ));
892            }
893            validate_node(first, depth + 1, node_count, panels)?;
894            validate_node(second, depth + 1, node_count, panels)
895        }
896    }
897}
898
899fn validate_floating_bounds(bounds: Rect) -> Result<(), DockLayoutError> {
900    if !bounds.x().is_finite()
901        || !bounds.y().is_finite()
902        || !bounds.width().is_finite()
903        || !bounds.height().is_finite()
904        || bounds.width() <= 0.0
905        || bounds.height() <= 0.0
906    {
907        return Err(DockLayoutError::new(
908            "floating bounds must have finite coordinates and positive finite size",
909        ));
910    }
911    Ok(())
912}
913
914fn normalized_floating_bounds(bounds: Rect) -> Rect {
915    Rect::new(
916        bounds.x(),
917        bounds.y(),
918        bounds.width().max(MIN_FLOATING_WIDTH),
919        bounds.height().max(MIN_FLOATING_HEIGHT),
920    )
921}
922
923fn normalize_fraction(fraction: f32) -> f32 {
924    if fraction.is_finite() {
925        fraction.clamp(MIN_SPLIT_FRACTION, MAX_SPLIT_FRACTION)
926    } else {
927        0.5
928    }
929}
930
931fn snapshot_contains_panel(snapshot: &DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
932    visible_snapshot_contains_panel(snapshot, panel) || snapshot.hidden.contains(&panel)
933}
934
935fn visible_snapshot_contains_panel(snapshot: &DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
936    node_contains_panel(&snapshot.root, panel)
937        || snapshot
938            .floating
939            .iter()
940            .any(|group| group.panels.contains(&panel))
941}
942
943fn node_contains_panel(node: &DockNode, panel: DockPanelId) -> bool {
944    match node {
945        DockNode::Empty => false,
946        DockNode::Tabs { panels, .. } => panels.contains(&panel),
947        DockNode::Split { first, second, .. } => {
948            node_contains_panel(first, panel) || node_contains_panel(second, panel)
949        }
950    }
951}
952
953fn remove_panel_from_snapshot(snapshot: &mut DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
954    let mut removed = remove_panel_from_node(&mut snapshot.root, panel);
955    for group in &mut snapshot.floating {
956        if let Some(index) = group
957            .panels
958            .iter()
959            .position(|candidate| *candidate == panel)
960        {
961            group.panels.remove(index);
962            if group.active == panel
963                && let Some(next) = group.panels.first().copied()
964            {
965                group.active = next;
966            }
967            removed = true;
968        }
969    }
970    snapshot.floating.retain(|group| !group.panels.is_empty());
971    let hidden_len = snapshot.hidden.len();
972    snapshot.hidden.retain(|candidate| *candidate != panel);
973    removed || snapshot.hidden.len() != hidden_len
974}
975
976fn remove_panel_from_node(node: &mut DockNode, panel: DockPanelId) -> bool {
977    match node {
978        DockNode::Empty => false,
979        DockNode::Tabs { panels, active } => {
980            let Some(index) = panels.iter().position(|candidate| *candidate == panel) else {
981                return false;
982            };
983            panels.remove(index);
984            if panels.is_empty() {
985                *node = DockNode::Empty;
986            } else if *active == panel {
987                *active = panels[index.min(panels.len() - 1)];
988            }
989            true
990        }
991        DockNode::Split { first, second, .. } => {
992            let removed =
993                remove_panel_from_node(first, panel) || remove_panel_from_node(second, panel);
994            if removed {
995                compact_split(node);
996            }
997            removed
998        }
999    }
1000}
1001
1002fn compact_split(node: &mut DockNode) {
1003    let replacement = match node {
1004        DockNode::Split { first, second, .. } if first.is_empty() => {
1005            Some(std::mem::take(second.as_mut()))
1006        }
1007        DockNode::Split { first, second, .. } if second.is_empty() => {
1008            Some(std::mem::take(first.as_mut()))
1009        }
1010        _ => None,
1011    };
1012    if let Some(replacement) = replacement {
1013        *node = replacement;
1014    }
1015}
1016
1017fn insert_tab(panels: &mut Vec<DockPanelId>, active: &mut DockPanelId, panel: DockPanelId) {
1018    if !panels.contains(&panel) {
1019        panels.push(panel);
1020    }
1021    *active = panel;
1022}
1023
1024fn insert_tab_beside(
1025    panels: &mut Vec<DockPanelId>,
1026    active: &mut DockPanelId,
1027    panel: DockPanelId,
1028    anchor: DockPanelId,
1029    after: bool,
1030) {
1031    let index = panels
1032        .iter()
1033        .position(|candidate| *candidate == anchor)
1034        .map_or(panels.len(), |index| index + usize::from(after));
1035    panels.insert(index, panel);
1036    *active = panel;
1037}
1038
1039fn insert_tab_beside_in_node(
1040    node: &mut DockNode,
1041    panel: DockPanelId,
1042    anchor: DockPanelId,
1043    after: bool,
1044) -> bool {
1045    match node {
1046        DockNode::Empty => false,
1047        DockNode::Tabs { panels, active } if panels.contains(&anchor) => {
1048            insert_tab_beside(panels, active, panel, anchor, after);
1049            true
1050        }
1051        DockNode::Tabs { .. } => false,
1052        DockNode::Split { first, second, .. } => {
1053            insert_tab_beside_in_node(first, panel, anchor, after)
1054                || insert_tab_beside_in_node(second, panel, anchor, after)
1055        }
1056    }
1057}
1058
1059fn insert_into_first_tab_group(node: &mut DockNode, panel: DockPanelId) -> bool {
1060    match node {
1061        DockNode::Empty => false,
1062        DockNode::Tabs { panels, active } => {
1063            insert_tab(panels, active, panel);
1064            true
1065        }
1066        DockNode::Split { first, second, .. } => {
1067            insert_into_first_tab_group(first, panel) || insert_into_first_tab_group(second, panel)
1068        }
1069    }
1070}
1071
1072fn dock_into_root_node(
1073    node: &mut DockNode,
1074    panel: DockPanelId,
1075    target: DockPanelId,
1076    zone: DockZone,
1077) -> bool {
1078    match node {
1079        DockNode::Empty => false,
1080        DockNode::Tabs { panels, active } if panels.contains(&target) => {
1081            if zone == DockZone::Center {
1082                insert_tab(panels, active, panel);
1083            } else {
1084                let previous = std::mem::take(node);
1085                *node = split_for_zone(previous, DockNode::tabs([panel], panel), zone);
1086            }
1087            true
1088        }
1089        DockNode::Tabs { .. } => false,
1090        DockNode::Split { first, second, .. } => {
1091            dock_into_root_node(first, panel, target, zone)
1092                || dock_into_root_node(second, panel, target, zone)
1093        }
1094    }
1095}
1096
1097fn split_for_zone(existing: DockNode, incoming: DockNode, zone: DockZone) -> DockNode {
1098    match zone {
1099        DockZone::Left => DockNode::split(Axis::Horizontal, 0.28, incoming, existing),
1100        DockZone::Right => DockNode::split(Axis::Horizontal, 0.72, existing, incoming),
1101        DockZone::Top => DockNode::split(Axis::Vertical, 0.28, incoming, existing),
1102        DockZone::Bottom => DockNode::split(Axis::Vertical, 0.72, existing, incoming),
1103        DockZone::Center => existing,
1104    }
1105}
1106
1107fn activate_panel(snapshot: &mut DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
1108    if activate_in_node(&mut snapshot.root, panel) {
1109        return true;
1110    }
1111    let Some(index) = snapshot
1112        .floating
1113        .iter()
1114        .position(|group| group.panels.contains(&panel))
1115    else {
1116        return false;
1117    };
1118    snapshot.floating[index].active = panel;
1119    if index + 1 != snapshot.floating.len() {
1120        let group = snapshot.floating.remove(index);
1121        snapshot.floating.push(group);
1122    }
1123    true
1124}
1125
1126fn activate_in_node(node: &mut DockNode, panel: DockPanelId) -> bool {
1127    match node {
1128        DockNode::Empty => false,
1129        DockNode::Tabs { panels, active } if panels.contains(&panel) => {
1130            *active = panel;
1131            true
1132        }
1133        DockNode::Tabs { .. } => false,
1134        DockNode::Split { first, second, .. } => {
1135            activate_in_node(first, panel) || activate_in_node(second, panel)
1136        }
1137    }
1138}
1139
1140fn next_floating_group_id(snapshot: &DockWorkspaceSnapshot) -> Result<u64, DockLayoutError> {
1141    snapshot
1142        .floating
1143        .iter()
1144        .map(|group| group.id)
1145        .max()
1146        .unwrap_or(0)
1147        .checked_add(1)
1148        .filter(|id| *id != 0)
1149        .ok_or_else(|| DockLayoutError::new("floating group ID space is exhausted"))
1150}
1151
1152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1153enum DockBranch {
1154    First,
1155    Second,
1156}
1157
1158fn node_at_path_mut<'a>(
1159    mut node: &'a mut DockNode,
1160    path: &[DockBranch],
1161) -> Option<&'a mut DockNode> {
1162    for branch in path {
1163        let DockNode::Split { first, second, .. } = node else {
1164            return None;
1165        };
1166        node = match branch {
1167            DockBranch::First => first,
1168            DockBranch::Second => second,
1169        };
1170    }
1171    Some(node)
1172}
1173
1174fn node_at_path<'a>(mut node: &'a DockNode, path: &[DockBranch]) -> Option<&'a DockNode> {
1175    for branch in path {
1176        let DockNode::Split { first, second, .. } = node else {
1177            return None;
1178        };
1179        node = match branch {
1180            DockBranch::First => first,
1181            DockBranch::Second => second,
1182        };
1183    }
1184    Some(node)
1185}
1186
1187struct DockPanelEntry {
1188    id: DockPanelId,
1189    options: DockPanelOptions,
1190    child: WidgetPod,
1191}
1192
1193#[derive(Debug, Clone, PartialEq, Eq)]
1194enum DockGroupLocation {
1195    Docked(Vec<DockBranch>),
1196    Floating(u64),
1197}
1198
1199#[derive(Debug, Clone)]
1200struct DockTabLayout {
1201    panel: DockPanelId,
1202    bounds: Rect,
1203    label: Rect,
1204    icon: Option<Rect>,
1205    dirty: Option<Rect>,
1206    close: Option<Rect>,
1207}
1208
1209/// A position between two tabs of one group that a dragged tab can take.
1210#[derive(Debug, Clone, Copy, PartialEq)]
1211struct DockTabInsert {
1212    anchor: DockPanelId,
1213    after: bool,
1214    indicator: Rect,
1215}
1216
1217#[derive(Debug, Clone)]
1218struct DockGroupLayout {
1219    location: DockGroupLocation,
1220    bounds: Rect,
1221    header: Rect,
1222    content: Rect,
1223    panels: Vec<DockPanelId>,
1224    active: DockPanelId,
1225    tabs: Vec<DockTabLayout>,
1226}
1227
1228impl DockGroupLayout {
1229    fn is_floating(&self) -> bool {
1230        matches!(self.location, DockGroupLocation::Floating(_))
1231    }
1232
1233    fn tab_at(&self, position: Point) -> Option<DockPanelId> {
1234        self.tabs
1235            .iter()
1236            .find(|tab| tab.bounds.contains(position))
1237            .map(|tab| tab.panel)
1238    }
1239
1240    fn close_at(&self, position: Point) -> Option<DockPanelId> {
1241        self.tabs
1242            .iter()
1243            .find(|tab| tab.close.is_some_and(|close| close.contains(position)))
1244            .map(|tab| tab.panel)
1245    }
1246
1247    /// The slot a tab dragged over this group's header would be inserted at.
1248    fn tab_insert_at(&self, position: Point, dragged: DockPanelId) -> Option<DockTabInsert> {
1249        if !self.header.contains(position) || self.tabs.iter().all(|tab| tab.panel == dragged) {
1250            return None;
1251        }
1252        let slot = |tab: &DockTabLayout, after: bool| {
1253            let x = if after {
1254                tab.bounds.max_x() - TAB_INSERT_INDICATOR
1255            } else {
1256                tab.bounds.x()
1257            };
1258            DockTabInsert {
1259                anchor: tab.panel,
1260                after,
1261                indicator: Rect::new(
1262                    x.max(self.header.x()),
1263                    self.header.y(),
1264                    TAB_INSERT_INDICATOR,
1265                    self.header.height(),
1266                ),
1267            }
1268        };
1269        self.tabs
1270            .iter()
1271            .find(|tab| position.x < tab.bounds.x() + tab.bounds.width() * 0.5)
1272            .map(|tab| slot(tab, false))
1273            .or_else(|| self.tabs.last().map(|tab| slot(tab, true)))
1274    }
1275}
1276
1277#[derive(Debug, Clone)]
1278struct DockSplitterLayout {
1279    path: Vec<DockBranch>,
1280    axis: Axis,
1281    fraction: f32,
1282    bounds: Rect,
1283    split_bounds: Rect,
1284}
1285
1286#[derive(Debug, Clone, Default)]
1287struct DockLayoutCache {
1288    bounds: Rect,
1289    groups: Vec<DockGroupLayout>,
1290    splitters: Vec<DockSplitterLayout>,
1291}
1292
1293impl DockLayoutCache {
1294    /// Moves every cached rectangle by `delta`.
1295    fn translate(&mut self, delta: Vector) {
1296        let shift = |rect: &mut Rect| *rect = rect.translate(delta);
1297        shift(&mut self.bounds);
1298        for group in &mut self.groups {
1299            shift(&mut group.bounds);
1300            shift(&mut group.header);
1301            shift(&mut group.content);
1302            for tab in &mut group.tabs {
1303                shift(&mut tab.bounds);
1304                shift(&mut tab.label);
1305                for part in [&mut tab.icon, &mut tab.dirty, &mut tab.close]
1306                    .into_iter()
1307                    .flatten()
1308                {
1309                    shift(part);
1310                }
1311            }
1312        }
1313        for splitter in &mut self.splitters {
1314            shift(&mut splitter.bounds);
1315            shift(&mut splitter.split_bounds);
1316        }
1317    }
1318
1319    fn visible_panel_ids(&self) -> impl Iterator<Item = DockPanelId> + '_ {
1320        self.groups.iter().map(|group| group.active)
1321    }
1322
1323    fn floating_groups_front_to_back(&self) -> impl Iterator<Item = &DockGroupLayout> {
1324        self.groups.iter().rev().filter(|group| group.is_floating())
1325    }
1326}
1327
1328enum DockWorkspaceGesture {
1329    ClosePress {
1330        pointer_id: u64,
1331        panel: DockPanelId,
1332    },
1333    TabPress {
1334        pointer_id: u64,
1335        panel: DockPanelId,
1336        start_position: Point,
1337        floating_size: Size,
1338    },
1339    TabDrag {
1340        pointer_id: u64,
1341        panel: DockPanelId,
1342        position: Point,
1343        floating_size: Size,
1344        candidate: Option<DockDropCandidate>,
1345    },
1346    Split {
1347        pointer_id: u64,
1348        path: Vec<DockBranch>,
1349        axis: Axis,
1350        split_bounds: Rect,
1351    },
1352    FloatingMove {
1353        pointer_id: u64,
1354        group_id: u64,
1355        pointer_origin: Point,
1356        initial_bounds: Rect,
1357    },
1358    FloatingResize {
1359        pointer_id: u64,
1360        group_id: u64,
1361        pointer_origin: Point,
1362        initial_bounds: Rect,
1363    },
1364}
1365
1366impl DockWorkspaceGesture {
1367    fn pointer_id(&self) -> u64 {
1368        match self {
1369            Self::ClosePress { pointer_id, .. }
1370            | Self::TabPress { pointer_id, .. }
1371            | Self::TabDrag { pointer_id, .. }
1372            | Self::Split { pointer_id, .. }
1373            | Self::FloatingMove { pointer_id, .. }
1374            | Self::FloatingResize { pointer_id, .. } => *pointer_id,
1375        }
1376    }
1377}
1378
1379#[derive(Debug, Clone)]
1380struct DockDropCandidate {
1381    target: Option<DockPanelId>,
1382    zone: DockZone,
1383    host_bounds: Rect,
1384    zone_bounds: Rect,
1385    center_only: bool,
1386    insert: Option<DockTabInsert>,
1387}
1388
1389impl DockDropCandidate {
1390    fn insert(host_bounds: Rect, insert: DockTabInsert) -> Self {
1391        Self {
1392            target: Some(insert.anchor),
1393            zone: DockZone::Center,
1394            host_bounds,
1395            zone_bounds: insert.indicator,
1396            center_only: true,
1397            insert: Some(insert),
1398        }
1399    }
1400}
1401
1402type DockCloseRequest = Box<dyn FnMut(DockPanelId) -> DockCloseAction>;
1403type DockPanelBuilder = Box<dyn FnMut(DockPanelId) -> Box<dyn Widget>>;
1404
1405type ThemeReader = std::rc::Rc<dyn Fn() -> DefaultTheme>;
1406
1407/// Retained editor workspace with a split/tab dock graph and same-window
1408/// floating panels.
1409///
1410/// Every panel widget remains owned by this workspace until it is removed
1411/// through [`DockWorkspaceState::remove_panel`]. Layout changes only alter
1412/// which registered panel is measured, arranged, and visited at each logical
1413/// location.
1414pub struct DockWorkspace {
1415    theme: Box<DefaultTheme>,
1416    theme_reader: Option<ThemeReader>,
1417    name: String,
1418    state: DockWorkspaceState,
1419    panels: Vec<DockPanelEntry>,
1420    layout: DockLayoutCache,
1421    gesture: Option<DockWorkspaceGesture>,
1422    focused_group: Option<DockGroupLocation>,
1423    hovered_close: Option<DockPanelId>,
1424    on_close_request: Option<DockCloseRequest>,
1425    panel_builder: Option<DockPanelBuilder>,
1426}
1427
1428impl DockWorkspace {
1429    pub fn new(state: DockWorkspaceState) -> Self {
1430        Self {
1431            theme: Box::new(DefaultTheme::default()),
1432            theme_reader: None,
1433            name: "Dock workspace".to_string(),
1434            state,
1435            panels: Vec::new(),
1436            layout: DockLayoutCache::default(),
1437            gesture: None,
1438            focused_group: None,
1439            hovered_close: None,
1440            on_close_request: None,
1441            panel_builder: None,
1442        }
1443    }
1444
1445    /// Creates the widget for a panel added through
1446    /// [`DockWorkspaceState::add_panel`].
1447    ///
1448    /// The builder runs once per added panel, on the UI thread. Without a
1449    /// builder an added panel has a tab and empty content.
1450    pub fn panel_builder<F>(mut self, panel_builder: F) -> Self
1451    where
1452        F: FnMut(DockPanelId) -> Box<dyn Widget> + 'static,
1453    {
1454        self.panel_builder = Some(Box::new(panel_builder));
1455        self
1456    }
1457
1458    /// Decides what a press on a tab's close button does.
1459    ///
1460    /// Without a handler a closed panel is hidden, which keeps its widget and
1461    /// lets [`DockWorkspaceState::show`] bring it back.
1462    pub fn on_close_request<F>(mut self, on_close_request: F) -> Self
1463    where
1464        F: FnMut(DockPanelId) -> DockCloseAction + 'static,
1465    {
1466        self.on_close_request = Some(Box::new(on_close_request));
1467        self
1468    }
1469
1470    pub fn name(mut self, name: impl Into<String>) -> Self {
1471        self.name = name.into();
1472        self
1473    }
1474
1475    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1476        self.theme = Box::new(theme);
1477        self.theme_reader = None;
1478        self
1479    }
1480
1481    pub fn theme_when<F>(mut self, theme: F) -> Self
1482    where
1483        F: Fn() -> DefaultTheme + 'static,
1484    {
1485        self.theme_reader = Some(std::rc::Rc::new(theme));
1486        self
1487    }
1488
1489    /// Registers a panel. `options` is a title or a full [`DockPanelOptions`].
1490    pub fn with_panel<W>(
1491        mut self,
1492        id: DockPanelId,
1493        options: impl Into<DockPanelOptions>,
1494        child: W,
1495    ) -> Self
1496    where
1497        W: Widget + 'static,
1498    {
1499        self.push_panel(id, options, child)
1500            .expect("dock panel registration must be valid and unique");
1501        self
1502    }
1503
1504    pub fn push_panel<W>(
1505        &mut self,
1506        id: DockPanelId,
1507        options: impl Into<DockPanelOptions>,
1508        child: W,
1509    ) -> Result<(), DockLayoutError>
1510    where
1511        W: Widget + 'static,
1512    {
1513        validate_panel_id(id)?;
1514        if !self.state.registry().registered.insert(id) {
1515            return Err(DockLayoutError::new(format!(
1516                "dock panel {id} is already registered"
1517            )));
1518        }
1519        self.panels.push(DockPanelEntry {
1520            id,
1521            options: options.into(),
1522            child: WidgetPod::new(child),
1523        });
1524        Ok(())
1525    }
1526
1527    /// Applies registry changes queued through [`DockWorkspaceState`].
1528    fn apply_registry_ops(&mut self) {
1529        let ops = std::mem::take(&mut self.state.registry().ops);
1530        for op in ops {
1531            match op {
1532                DockRegistryOp::Add { id, options } => {
1533                    let child = match &mut self.panel_builder {
1534                        Some(build) => build(id),
1535                        None => Box::new(crate::SizedBox::new()),
1536                    };
1537                    self.panels.retain(|panel| panel.id != id);
1538                    self.panels.push(DockPanelEntry {
1539                        id,
1540                        options,
1541                        child: WidgetPod::new_boxed(child),
1542                    });
1543                }
1544                DockRegistryOp::Remove(id) => {
1545                    self.panels.retain(|panel| panel.id != id);
1546                    if self.hovered_close == Some(id) {
1547                        self.hovered_close = None;
1548                    }
1549                }
1550                DockRegistryOp::Update { id, update } => {
1551                    if let Some(panel) = self.panel_mut(id) {
1552                        update(&mut panel.options);
1553                    }
1554                }
1555            }
1556        }
1557    }
1558
1559    pub fn shared_state(&self) -> DockWorkspaceState {
1560        self.state.clone()
1561    }
1562
1563    pub fn panel_widget_id(&self, panel: DockPanelId) -> Option<WidgetId> {
1564        self.panel(panel).map(|entry| entry.child.id())
1565    }
1566
1567    pub fn validate_registered_panels(&self) -> Result<(), DockLayoutError> {
1568        self.validate_snapshot_panels(&self.state.snapshot())
1569    }
1570
1571    /// Validates that every panel referenced by `snapshot` has a widget in
1572    /// this workspace's stable registry.
1573    ///
1574    /// This complements the structural graph validation performed by
1575    /// [`DockWorkspaceState::apply_snapshot`].
1576    pub fn validate_snapshot_panels(
1577        &self,
1578        snapshot: &DockWorkspaceSnapshot,
1579    ) -> Result<(), DockLayoutError> {
1580        let registered = self.state.registry().registered.clone();
1581        let mut referenced = HashSet::new();
1582        collect_snapshot_panels(snapshot, &mut referenced);
1583        if let Some(missing) = referenced
1584            .into_iter()
1585            .find(|panel| !registered.contains(panel))
1586        {
1587            return Err(DockLayoutError::new(format!(
1588                "dock snapshot references unregistered panel {missing}"
1589            )));
1590        }
1591        Ok(())
1592    }
1593
1594    /// Applies a restored snapshot only after validating both its graph and
1595    /// all panel IDs against this workspace's registry.
1596    pub fn apply_snapshot(&self, snapshot: DockWorkspaceSnapshot) -> Result<bool, DockLayoutError> {
1597        validate_snapshot(&snapshot)?;
1598        self.validate_snapshot_panels(&snapshot)?;
1599        self.state.apply_snapshot(snapshot)
1600    }
1601
1602    fn panel(&self, id: DockPanelId) -> Option<&DockPanelEntry> {
1603        self.panels.iter().find(|panel| panel.id == id)
1604    }
1605
1606    fn panel_mut(&mut self, id: DockPanelId) -> Option<&mut DockPanelEntry> {
1607        self.panels.iter_mut().find(|panel| panel.id == id)
1608    }
1609
1610    fn resolved_theme(&self) -> DefaultTheme {
1611        self.theme_reader
1612            .as_ref()
1613            .map(|reader| reader())
1614            .unwrap_or_else(|| *self.theme)
1615    }
1616
1617    fn options_map(&self) -> HashMap<DockPanelId, DockPanelOptions> {
1618        self.panels
1619            .iter()
1620            .map(|panel| (panel.id, panel.options.clone()))
1621            .collect()
1622    }
1623
1624    fn header_height(&self) -> f32 {
1625        self.resolved_theme().metrics.tab_height.max(22.0)
1626    }
1627
1628    fn rebuild_layout(&self, snapshot: &DockWorkspaceSnapshot, bounds: Rect) -> DockLayoutCache {
1629        build_workspace_layout(
1630            snapshot,
1631            bounds,
1632            self.header_height(),
1633            DEFAULT_SPLITTER_THICKNESS,
1634            &self.options_map(),
1635        )
1636    }
1637
1638    /// The minimum bounds of the floating group `group_id`, from the panels
1639    /// it currently holds.
1640    fn floating_group_min_size(&self, group_id: u64) -> Size {
1641        let snapshot = self.state.snapshot();
1642        let members = snapshot
1643            .floating
1644            .iter()
1645            .find(|group| group.id == group_id)
1646            .map_or(&[][..], |group| group.panels.as_slice());
1647        floating_min_size(members, self.header_height(), &self.options_map())
1648    }
1649
1650    /// Moves the cached layout to where the workspace now is.
1651    ///
1652    /// An ancestor that scrolls or is moved translates this widget's bounds
1653    /// without arranging it again, which leaves the cache behind.
1654    fn sync_layout_origin(&mut self, bounds: Rect) {
1655        let delta = bounds.origin - self.layout.bounds.origin;
1656        if delta != Vector::ZERO {
1657            self.layout.translate(delta);
1658        }
1659    }
1660
1661    /// The cached layout at `bounds`, for passes that cannot update it.
1662    fn layout_at(&self, bounds: Rect) -> Cow<'_, DockLayoutCache> {
1663        let delta = bounds.origin - self.layout.bounds.origin;
1664        if delta == Vector::ZERO {
1665            Cow::Borrowed(&self.layout)
1666        } else {
1667            let mut layout = self.layout.clone();
1668            layout.translate(delta);
1669            Cow::Owned(layout)
1670        }
1671    }
1672
1673    fn close_rect(&self, panel: DockPanelId) -> Option<Rect> {
1674        self.layout
1675            .groups
1676            .iter()
1677            .flat_map(|group| group.tabs.iter())
1678            .find(|tab| tab.panel == panel)
1679            .and_then(|tab| tab.close)
1680    }
1681
1682    fn close_at(&self, position: Point) -> Option<DockPanelId> {
1683        for group in self.layout.floating_groups_front_to_back() {
1684            if group.bounds.contains(position) {
1685                return group.close_at(position);
1686            }
1687        }
1688        self.layout
1689            .groups
1690            .iter()
1691            .filter(|group| !group.is_floating())
1692            .find_map(|group| group.close_at(position))
1693    }
1694
1695    fn set_hovered_close(&mut self, ctx: &mut EventCtx, hovered: Option<DockPanelId>) {
1696        if self.hovered_close != hovered {
1697            self.hovered_close = hovered;
1698            ctx.request_paint();
1699        }
1700    }
1701
1702    fn request_close(&mut self, ctx: &mut EventCtx, panel: DockPanelId) {
1703        let action = self
1704            .on_close_request
1705            .as_mut()
1706            .map_or(DockCloseAction::Hide, |handler| handler(panel));
1707        let changed = match action {
1708            DockCloseAction::Hide => self.state.hide(panel).unwrap_or(false),
1709            DockCloseAction::Remove => self.state.remove_panel(panel).unwrap_or(false),
1710            DockCloseAction::Keep => false,
1711        };
1712        if changed {
1713            self.hovered_close = None;
1714            ctx.request_ordering();
1715            ctx.request_hit_test();
1716            ctx.request_measure();
1717            ctx.request_semantics();
1718        }
1719        ctx.request_paint();
1720    }
1721
1722    fn begin_pointer_gesture(
1723        &mut self,
1724        ctx: &mut EventCtx,
1725        pointer_id: u64,
1726        position: Point,
1727    ) -> bool {
1728        for group in self.layout.floating_groups_front_to_back() {
1729            let DockGroupLocation::Floating(group_id) = group.location else {
1730                continue;
1731            };
1732            if !group.bounds.contains(position) {
1733                continue;
1734            }
1735
1736            if self
1737                .state
1738                .bring_floating_to_front(group_id)
1739                .unwrap_or(false)
1740            {
1741                ctx.request_ordering();
1742                ctx.request_hit_test();
1743                ctx.request_measure();
1744                ctx.request_paint();
1745                ctx.request_semantics();
1746            }
1747            if floating_resize_rect(group.bounds).contains(position) {
1748                self.gesture = Some(DockWorkspaceGesture::FloatingResize {
1749                    pointer_id,
1750                    group_id,
1751                    pointer_origin: position,
1752                    initial_bounds: group.bounds,
1753                });
1754                ctx.request_pointer_capture(pointer_id);
1755                return true;
1756            }
1757
1758            if let Some(panel) = group.close_at(position) {
1759                self.gesture = Some(DockWorkspaceGesture::ClosePress { pointer_id, panel });
1760                ctx.request_pointer_capture(pointer_id);
1761                return true;
1762            }
1763
1764            if let Some(panel) = group.tab_at(position) {
1765                let _ = self.state.activate(panel);
1766                self.focused_group = Some(group.location.clone());
1767                self.gesture = Some(DockWorkspaceGesture::TabPress {
1768                    pointer_id,
1769                    panel,
1770                    start_position: position,
1771                    floating_size: group.bounds.size,
1772                });
1773                ctx.request_focus();
1774                ctx.request_pointer_capture(pointer_id);
1775                ctx.request_measure();
1776                ctx.request_paint();
1777                ctx.request_semantics();
1778                return true;
1779            }
1780
1781            if group.header.contains(position) {
1782                self.gesture = Some(DockWorkspaceGesture::FloatingMove {
1783                    pointer_id,
1784                    group_id,
1785                    pointer_origin: position,
1786                    initial_bounds: group.bounds,
1787                });
1788                self.focused_group = Some(group.location.clone());
1789                ctx.request_focus();
1790                ctx.request_pointer_capture(pointer_id);
1791                return true;
1792            }
1793
1794            // Body presses front the floating group but remain available to
1795            // the active panel child.
1796            ctx.request_paint();
1797            return false;
1798        }
1799
1800        if let Some(splitter) = self
1801            .layout
1802            .splitters
1803            .iter()
1804            .find(|splitter| splitter.bounds.contains(position))
1805            .cloned()
1806        {
1807            self.gesture = Some(DockWorkspaceGesture::Split {
1808                pointer_id,
1809                path: splitter.path,
1810                axis: splitter.axis,
1811                split_bounds: splitter.split_bounds,
1812            });
1813            ctx.request_pointer_capture(pointer_id);
1814            return true;
1815        }
1816
1817        if let Some(panel) = self
1818            .layout
1819            .groups
1820            .iter()
1821            .filter(|group| !group.is_floating())
1822            .find_map(|group| group.close_at(position))
1823        {
1824            self.gesture = Some(DockWorkspaceGesture::ClosePress { pointer_id, panel });
1825            ctx.request_pointer_capture(pointer_id);
1826            return true;
1827        }
1828
1829        if let Some(group) = self
1830            .layout
1831            .groups
1832            .iter()
1833            .filter(|group| !group.is_floating())
1834            .find(|group| group.header.contains(position))
1835            && let Some(panel) = group.tab_at(position)
1836        {
1837            let location = group.location.clone();
1838            let floating_size = Size::new(320.0, 260.0);
1839            let _ = self.state.activate(panel);
1840            self.focused_group = Some(location);
1841            self.gesture = Some(DockWorkspaceGesture::TabPress {
1842                pointer_id,
1843                panel,
1844                start_position: position,
1845                floating_size,
1846            });
1847            ctx.request_focus();
1848            ctx.request_pointer_capture(pointer_id);
1849            ctx.request_measure();
1850            ctx.request_paint();
1851            ctx.request_semantics();
1852            return true;
1853        }
1854
1855        false
1856    }
1857
1858    fn drop_candidate_at(
1859        &self,
1860        position: Point,
1861        dragged_panel: DockPanelId,
1862    ) -> Option<DockDropCandidate> {
1863        for group in self.layout.floating_groups_front_to_back() {
1864            if !group.bounds.contains(position) {
1865                continue;
1866            }
1867            if let Some(insert) = group.tab_insert_at(position, dragged_panel) {
1868                return Some(DockDropCandidate::insert(group.bounds, insert));
1869            }
1870            let target = group
1871                .panels
1872                .iter()
1873                .copied()
1874                .find(|panel| *panel != dragged_panel)
1875                .unwrap_or(group.active);
1876            let zone_bounds = inset_rect_evenly(group.bounds, DROP_ZONE_INSET);
1877            return Some(DockDropCandidate {
1878                target: Some(target),
1879                zone: DockZone::Center,
1880                host_bounds: group.bounds,
1881                zone_bounds,
1882                center_only: true,
1883                insert: None,
1884            });
1885        }
1886
1887        for group in self
1888            .layout
1889            .groups
1890            .iter()
1891            .filter(|group| !group.is_floating())
1892        {
1893            if !group.bounds.contains(position) {
1894                continue;
1895            }
1896            if let Some(insert) = group.tab_insert_at(position, dragged_panel) {
1897                return Some(DockDropCandidate::insert(group.bounds, insert));
1898            }
1899            let target = group
1900                .panels
1901                .iter()
1902                .copied()
1903                .find(|panel| *panel != dragged_panel)
1904                .unwrap_or(group.active);
1905            let zone = drop_zone_at(group.bounds, position);
1906            return Some(DockDropCandidate {
1907                target: Some(target),
1908                zone,
1909                host_bounds: group.bounds,
1910                zone_bounds: drop_zone_rect(group.bounds, zone),
1911                center_only: false,
1912                insert: None,
1913            });
1914        }
1915
1916        if self.state.snapshot().root.is_empty()
1917            && !self.layout.groups.iter().any(|group| !group.is_floating())
1918        {
1919            let bounds = self.layout.bounds;
1920            if bounds.contains(position) {
1921                return Some(DockDropCandidate {
1922                    target: None,
1923                    zone: DockZone::Center,
1924                    host_bounds: bounds,
1925                    zone_bounds: inset_rect_evenly(bounds, DROP_ZONE_INSET),
1926                    center_only: true,
1927                    insert: None,
1928                });
1929            }
1930        }
1931        None
1932    }
1933
1934    fn update_pointer_gesture(&mut self, ctx: &mut EventCtx, position: Point) {
1935        let host_bounds = ctx.bounds();
1936        if let Some(DockWorkspaceGesture::TabPress {
1937            pointer_id,
1938            panel,
1939            start_position,
1940            floating_size,
1941        }) = &self.gesture
1942        {
1943            let distance = position - *start_position;
1944            if (distance.x * distance.x) + (distance.y * distance.y)
1945                >= TAB_DRAG_THRESHOLD * TAB_DRAG_THRESHOLD
1946            {
1947                let pointer_id = *pointer_id;
1948                let panel = *panel;
1949                let floating_size = *floating_size;
1950                let candidate = self.drop_candidate_at(position, panel);
1951                self.gesture = Some(DockWorkspaceGesture::TabDrag {
1952                    pointer_id,
1953                    panel,
1954                    position,
1955                    floating_size,
1956                    candidate,
1957                });
1958            }
1959        }
1960
1961        let dragged_panel = match &self.gesture {
1962            Some(DockWorkspaceGesture::TabDrag { panel, .. }) => Some(*panel),
1963            _ => None,
1964        };
1965        let next_candidate =
1966            dragged_panel.and_then(|panel| self.drop_candidate_at(position, panel));
1967        if let Some(DockWorkspaceGesture::TabDrag {
1968            position: current,
1969            candidate,
1970            ..
1971        }) = &mut self.gesture
1972        {
1973            *current = position;
1974            *candidate = next_candidate;
1975            ctx.request_paint();
1976            return;
1977        }
1978
1979        let Some(gesture) = &self.gesture else {
1980            return;
1981        };
1982        match gesture {
1983            DockWorkspaceGesture::ClosePress { .. } => return,
1984            DockWorkspaceGesture::TabPress { .. } | DockWorkspaceGesture::TabDrag { .. } => {}
1985            DockWorkspaceGesture::Split {
1986                path,
1987                axis,
1988                split_bounds,
1989                ..
1990            } => {
1991                let total = axis_extent(*axis, split_bounds.size);
1992                let available = (total - DEFAULT_SPLITTER_THICKNESS.min(total)).max(1.0);
1993                let offset = match axis {
1994                    Axis::Horizontal => position.x - split_bounds.x(),
1995                    Axis::Vertical => position.y - split_bounds.y(),
1996                };
1997                let snapshot = self.state.snapshot();
1998                let (first_minimum, second_minimum) = match node_at_path(&snapshot.root, path) {
1999                    Some(DockNode::Split { first, second, .. }) => split_minimums(
2000                        first,
2001                        second,
2002                        *axis,
2003                        available,
2004                        self.header_height(),
2005                        DEFAULT_SPLITTER_THICKNESS,
2006                        &self.options_map(),
2007                    ),
2008                    _ => (0.0, 0.0),
2009                };
2010                let min_fraction =
2011                    (first_minimum / available).clamp(MIN_SPLIT_FRACTION, MAX_SPLIT_FRACTION);
2012                let max_fraction =
2013                    (1.0 - second_minimum / available).clamp(min_fraction, MAX_SPLIT_FRACTION);
2014                let fraction = (offset / available).clamp(min_fraction, max_fraction);
2015                let _ = self.state.set_split_fraction(path, fraction);
2016            }
2017            DockWorkspaceGesture::FloatingMove {
2018                group_id,
2019                pointer_origin,
2020                initial_bounds,
2021                ..
2022            } => {
2023                let delta = position - *pointer_origin;
2024                let proposed = initial_bounds.translate(delta);
2025                let minimum = self.floating_group_min_size(*group_id);
2026                let _ = self.state.set_floating_bounds(
2027                    *group_id,
2028                    floating_bounds_from_host(host_bounds, proposed, minimum),
2029                );
2030            }
2031            DockWorkspaceGesture::FloatingResize {
2032                group_id,
2033                pointer_origin,
2034                initial_bounds,
2035                ..
2036            } => {
2037                let delta = position - *pointer_origin;
2038                let proposed = Rect::new(
2039                    initial_bounds.x(),
2040                    initial_bounds.y(),
2041                    initial_bounds.width() + delta.x,
2042                    initial_bounds.height() + delta.y,
2043                );
2044                let minimum = self.floating_group_min_size(*group_id);
2045                let _ = self.state.set_floating_bounds(
2046                    *group_id,
2047                    floating_bounds_from_host(host_bounds, proposed, minimum),
2048                );
2049            }
2050        }
2051        ctx.request_measure();
2052        ctx.request_paint();
2053        ctx.request_semantics();
2054    }
2055
2056    fn finish_pointer_gesture(&mut self, ctx: &mut EventCtx, release: Point, cancelled: bool) {
2057        let Some(gesture) = self.gesture.take() else {
2058            return;
2059        };
2060        if cancelled {
2061            ctx.request_paint();
2062            return;
2063        }
2064
2065        if let DockWorkspaceGesture::ClosePress { panel, .. } = gesture {
2066            if self
2067                .close_rect(panel)
2068                .is_some_and(|close| close.contains(release))
2069            {
2070                self.request_close(ctx, panel);
2071            }
2072            return;
2073        }
2074
2075        if let DockWorkspaceGesture::TabDrag {
2076            panel,
2077            position,
2078            floating_size,
2079            candidate,
2080            ..
2081        } = gesture
2082        {
2083            if let Some(insert) = candidate.as_ref().and_then(|candidate| candidate.insert) {
2084                let _ = self.state.dock_tab(panel, insert.anchor, insert.after);
2085            } else if let Some(candidate) = candidate {
2086                match candidate.target {
2087                    Some(target) if target != panel => {
2088                        let _ = self.state.dock(panel, target, candidate.zone);
2089                    }
2090                    Some(_) => {
2091                        let _ = self.state.activate(panel);
2092                    }
2093                    None => {
2094                        let _ = self.state.dock_to_root(panel, DockZone::Center);
2095                    }
2096                }
2097            } else {
2098                let bounds = floating_bounds_from_host(
2099                    ctx.bounds(),
2100                    Rect::new(
2101                        position.x - floating_size.width * 0.5,
2102                        position.y - 18.0,
2103                        floating_size.width,
2104                        floating_size.height,
2105                    ),
2106                    floating_min_size(&[panel], self.header_height(), &self.options_map()),
2107                );
2108                let _ = self.state.float_panel(panel, bounds);
2109            }
2110            self.focused_group = panel_location(&self.state.snapshot(), panel);
2111            ctx.request_ordering();
2112            ctx.request_hit_test();
2113            ctx.request_measure();
2114            ctx.request_semantics();
2115        }
2116        ctx.request_paint();
2117    }
2118
2119    fn activate_adjacent_tab(&mut self, delta: isize) -> bool {
2120        let Some(location) = self.focused_group.clone() else {
2121            return false;
2122        };
2123        let snapshot = self.state.snapshot();
2124        let Some((panels, active)) = group_members(&snapshot, &location) else {
2125            return false;
2126        };
2127        if panels.is_empty() {
2128            return false;
2129        }
2130        let current = panels
2131            .iter()
2132            .position(|panel| *panel == active)
2133            .unwrap_or(0) as isize;
2134        let next = (current + delta).rem_euclid(panels.len() as isize) as usize;
2135        self.state.activate(panels[next]).unwrap_or(false)
2136    }
2137}
2138
2139impl Widget for DockWorkspace {
2140    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2141        self.sync_layout_origin(ctx.bounds());
2142        match event {
2143            Event::Pointer(pointer)
2144                if pointer.kind == PointerEventKind::Down
2145                    && pointer.button == Some(PointerButton::Primary) =>
2146            {
2147                if self.begin_pointer_gesture(ctx, pointer.pointer_id, pointer.position) {
2148                    ctx.set_handled();
2149                }
2150            }
2151            Event::Pointer(pointer)
2152                if pointer.kind == PointerEventKind::Move
2153                    && self
2154                        .gesture
2155                        .as_ref()
2156                        .is_some_and(|gesture| gesture.pointer_id() == pointer.pointer_id) =>
2157            {
2158                self.update_pointer_gesture(ctx, pointer.position);
2159                ctx.set_handled();
2160            }
2161            Event::Pointer(pointer)
2162                if matches!(
2163                    pointer.kind,
2164                    PointerEventKind::Up | PointerEventKind::Cancel
2165                ) && self
2166                    .gesture
2167                    .as_ref()
2168                    .is_some_and(|gesture| gesture.pointer_id() == pointer.pointer_id) =>
2169            {
2170                self.finish_pointer_gesture(
2171                    ctx,
2172                    pointer.position,
2173                    pointer.kind == PointerEventKind::Cancel,
2174                );
2175                ctx.release_pointer_capture(pointer.pointer_id);
2176                ctx.set_handled();
2177            }
2178            Event::Pointer(pointer)
2179                if matches!(
2180                    pointer.kind,
2181                    PointerEventKind::Move | PointerEventKind::Enter
2182                ) =>
2183            {
2184                let hovered = self.close_at(pointer.position);
2185                self.set_hovered_close(ctx, hovered);
2186            }
2187            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
2188                self.set_hovered_close(ctx, None);
2189            }
2190            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
2191                let handled = match key.key.as_str() {
2192                    "ArrowLeft" | "ArrowUp" => self.activate_adjacent_tab(-1),
2193                    "ArrowRight" | "ArrowDown" => self.activate_adjacent_tab(1),
2194                    _ => false,
2195                };
2196                if handled {
2197                    ctx.request_measure();
2198                    ctx.request_paint();
2199                    ctx.request_semantics();
2200                    ctx.set_handled();
2201                }
2202            }
2203            Event::Semantics(semantics) => {
2204                if matches!(semantics.action, SemanticsActionRequest::Activate) {
2205                    let closing = self
2206                        .layout
2207                        .groups
2208                        .iter()
2209                        .flat_map(|group| group.tabs.iter())
2210                        .find(|tab| {
2211                            tab.close.is_some()
2212                                && dock_close_semantics_id(ctx.widget_id(), tab.panel)
2213                                    == semantics.target
2214                        })
2215                        .map(|tab| tab.panel);
2216                    if let Some(panel) = closing {
2217                        self.request_close(ctx, panel);
2218                        ctx.set_handled();
2219                        return;
2220                    }
2221                }
2222                if matches!(
2223                    semantics.action,
2224                    SemanticsActionRequest::Activate | SemanticsActionRequest::Focus
2225                ) {
2226                    let panel = self.layout.groups.iter().find_map(|group| {
2227                        group.tabs.iter().find_map(|tab| {
2228                            (dock_tab_semantics_id(ctx.widget_id(), tab.panel) == semantics.target)
2229                                .then_some((tab.panel, group.location.clone()))
2230                        })
2231                    });
2232                    if let Some((panel, location)) = panel {
2233                        let _ = self.state.activate(panel);
2234                        self.focused_group = Some(location);
2235                        ctx.request_focus();
2236                        ctx.request_measure();
2237                        ctx.request_paint();
2238                        ctx.request_semantics();
2239                        ctx.set_handled();
2240                        return;
2241                    }
2242                }
2243
2244                let splitter_path = self.layout.splitters.iter().find_map(|splitter| {
2245                    (dock_splitter_semantics_id(ctx.widget_id(), &splitter.path)
2246                        == semantics.target)
2247                        .then(|| splitter.path.clone())
2248                });
2249                let Some(path) = splitter_path else {
2250                    return;
2251                };
2252                if matches!(semantics.action, SemanticsActionRequest::Focus) {
2253                    self.focused_group = None;
2254                    ctx.request_focus();
2255                    ctx.request_semantics();
2256                    ctx.set_handled();
2257                    return;
2258                }
2259
2260                let snapshot = self.state.snapshot();
2261                let Some(DockNode::Split { fraction, .. }) = node_at_path(&snapshot.root, &path)
2262                else {
2263                    return;
2264                };
2265                let current = f64::from(*fraction);
2266                let next = match &semantics.action {
2267                    SemanticsActionRequest::Increment => {
2268                        Some(current + f64::from(SEMANTIC_SPLIT_STEP))
2269                    }
2270                    SemanticsActionRequest::Decrement => {
2271                        Some(current - f64::from(SEMANTIC_SPLIT_STEP))
2272                    }
2273                    SemanticsActionRequest::SetValue(SemanticsValue::Number(value)) => Some(*value),
2274                    SemanticsActionRequest::SetValue(SemanticsValue::Range { value, .. }) => {
2275                        Some(*value)
2276                    }
2277                    _ => None,
2278                };
2279                let Some(next) = next.filter(|value| value.is_finite()) else {
2280                    return;
2281                };
2282                let next = next as f32;
2283                if !next.is_finite() {
2284                    return;
2285                }
2286                let _ = self.state.set_split_fraction(&path, next);
2287                ctx.request_measure();
2288                ctx.request_paint();
2289                ctx.request_semantics();
2290                ctx.set_handled();
2291            }
2292            _ => {}
2293        }
2294    }
2295
2296    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2297        let _registry_revision = ctx.observe(&self.state.registry_revision);
2298        self.apply_registry_ops();
2299        let snapshot = ctx.observe(&self.state.snapshot);
2300        let width = if constraints.max.width.is_finite() {
2301            constraints.max.width
2302        } else {
2303            constraints.min.width.max(1_024.0)
2304        };
2305        let height = if constraints.max.height.is_finite() {
2306            constraints.max.height
2307        } else {
2308            constraints.min.height.max(720.0)
2309        };
2310        let size = constraints.clamp(Size::new(width, height));
2311        self.layout = self.rebuild_layout(&snapshot, Rect::from_origin_size(Point::ZERO, size));
2312
2313        let active = self.layout.visible_panel_ids().collect::<Vec<_>>();
2314        for panel_id in active {
2315            let bounds = self
2316                .layout
2317                .groups
2318                .iter()
2319                .find(|group| group.active == panel_id)
2320                .map(|group| group.content)
2321                .unwrap_or(Rect::ZERO);
2322            if let Some(panel) = self.panel_mut(panel_id) {
2323                panel.child.measure(ctx, Constraints::tight(bounds.size));
2324            }
2325        }
2326        size
2327    }
2328
2329    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2330        self.layout = self.rebuild_layout(&self.state.snapshot(), bounds);
2331        let placements = self
2332            .layout
2333            .groups
2334            .iter()
2335            .map(|group| (group.active, group.content))
2336            .collect::<Vec<_>>();
2337        for (panel_id, panel_bounds) in placements {
2338            if let Some(panel) = self.panel_mut(panel_id) {
2339                panel.child.arrange(ctx, panel_bounds);
2340            }
2341        }
2342    }
2343
2344    fn paint(&self, ctx: &mut PaintCtx) {
2345        let theme = self.resolved_theme();
2346        ctx.fill_bounds(theme.palette.surface);
2347
2348        let layout = self.layout_at(ctx.bounds());
2349        for group in layout.groups.iter().filter(|group| !group.is_floating()) {
2350            self.paint_group(ctx, group, &theme);
2351        }
2352        for splitter in &layout.splitters {
2353            ctx.fill_rect(splitter.bounds, theme.palette.border.with_alpha(0.88));
2354        }
2355        for group in layout.groups.iter().filter(|group| group.is_floating()) {
2356            self.paint_group(ctx, group, &theme);
2357        }
2358        if let Some(DockWorkspaceGesture::TabDrag {
2359            panel,
2360            position,
2361            candidate,
2362            ..
2363        }) = &self.gesture
2364        {
2365            match candidate {
2366                Some(DockDropCandidate {
2367                    insert: Some(insert),
2368                    ..
2369                }) => ctx.fill_rect(insert.indicator, theme.palette.accent),
2370                Some(candidate) => paint_drop_targets(ctx, candidate, &theme),
2371                None => {}
2372            }
2373            self.paint_drag_preview(ctx, *panel, *position, &theme);
2374        }
2375    }
2376
2377    fn semantics(&self, ctx: &mut SemanticsCtx) {
2378        let mut workspace = SemanticsNode::new(
2379            ctx.widget_id(),
2380            SemanticsRole::GenericContainer,
2381            ctx.bounds(),
2382        );
2383        workspace.name = Some(self.name.clone());
2384        workspace.state.focused = ctx.is_focused();
2385        workspace.actions = vec![SemanticsAction::Focus];
2386        ctx.push(workspace);
2387
2388        let layout = self.layout_at(ctx.bounds());
2389        for group in &layout.groups {
2390            let group_id = dock_group_semantics_id(ctx.widget_id(), &group.location);
2391            let mut tabs = SemanticsNode::new(group_id, SemanticsRole::TabBar, group.header);
2392            tabs.parent = Some(ctx.widget_id());
2393            tabs.name = Some(if group.is_floating() {
2394                "Floating panel tabs".to_string()
2395            } else {
2396                "Docked panel tabs".to_string()
2397            });
2398            tabs.value = self
2399                .panel(group.active)
2400                .map(|panel| SemanticsValue::Text(panel.options.title.clone()));
2401            ctx.push(tabs);
2402            for tab in &group.tabs {
2403                let mut node = SemanticsNode::new(
2404                    dock_tab_semantics_id(ctx.widget_id(), tab.panel),
2405                    SemanticsRole::Button,
2406                    tab.bounds,
2407                );
2408                let options = self.panel(tab.panel).map(|panel| &panel.options);
2409                node.parent = Some(group_id);
2410                node.name = options.map(|options| options.title.clone());
2411                node.description = options
2412                    .filter(|options| options.dirty)
2413                    .map(|_| "Unsaved changes".to_string());
2414                node.state.selected = tab.panel == group.active;
2415                node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
2416                ctx.push(node);
2417
2418                if let Some(close) = tab.close {
2419                    let mut node = SemanticsNode::new(
2420                        dock_close_semantics_id(ctx.widget_id(), tab.panel),
2421                        SemanticsRole::Button,
2422                        close,
2423                    );
2424                    node.parent = Some(group_id);
2425                    node.name = Some(match options {
2426                        Some(options) => format!("Close {}", options.title),
2427                        None => "Close panel".to_string(),
2428                    });
2429                    node.actions = vec![SemanticsAction::Activate];
2430                    ctx.push(node);
2431                }
2432            }
2433            if let Some(panel) = self.panel(group.active) {
2434                panel.child.semantics(ctx);
2435            }
2436        }
2437
2438        for splitter in &layout.splitters {
2439            let mut node = SemanticsNode::new(
2440                dock_splitter_semantics_id(ctx.widget_id(), &splitter.path),
2441                SemanticsRole::Splitter,
2442                splitter.bounds,
2443            );
2444            node.parent = Some(ctx.widget_id());
2445            node.name = Some("Dock divider".to_string());
2446            node.value = Some(SemanticsValue::Range {
2447                value: f64::from(splitter.fraction),
2448                min: f64::from(MIN_SPLIT_FRACTION),
2449                max: f64::from(MAX_SPLIT_FRACTION),
2450            });
2451            node.actions = vec![
2452                SemanticsAction::Focus,
2453                SemanticsAction::Increment,
2454                SemanticsAction::Decrement,
2455                SemanticsAction::SetValue,
2456            ];
2457            ctx.push(node);
2458        }
2459    }
2460
2461    fn accepts_focus(&self) -> bool {
2462        true
2463    }
2464
2465    fn stack_host_options(&self) -> Option<StackHostOptions> {
2466        Some(StackHostOptions {
2467            order_policy: StackOrderPolicy::FocusFronted,
2468        })
2469    }
2470
2471    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2472        for panel_id in self.layout.visible_panel_ids() {
2473            if let Some(panel) = self.panel(panel_id) {
2474                visitor.visit(&panel.child);
2475            }
2476        }
2477    }
2478
2479    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2480        let visible = self.layout.visible_panel_ids().collect::<Vec<_>>();
2481        for panel_id in visible {
2482            if let Some(panel) = self.panel_mut(panel_id) {
2483                visitor.visit(&mut panel.child);
2484            }
2485        }
2486    }
2487}
2488
2489impl DockWorkspace {
2490    fn paint_group(&self, ctx: &mut PaintCtx, group: &DockGroupLayout, theme: &DefaultTheme) {
2491        let palette = theme.palette;
2492        ctx.fill_rect(group.bounds, palette.surface_raised);
2493        ctx.push_clip_rect(group.content);
2494        if let Some(panel) = self.panel(group.active) {
2495            panel.child.paint(ctx);
2496        }
2497        ctx.pop_clip();
2498
2499        ctx.fill_rect(group.header, palette.control);
2500        for tab in &group.tabs {
2501            let selected = tab.panel == group.active;
2502            if selected {
2503                ctx.fill_rect(tab.bounds, palette.control_active);
2504                ctx.fill_rect(
2505                    Rect::new(
2506                        tab.bounds.x(),
2507                        tab.bounds.max_y() - 2.0,
2508                        tab.bounds.width(),
2509                        2.0,
2510                    ),
2511                    palette.accent,
2512                );
2513            }
2514            let options = self.panel(tab.panel).map(|panel| &panel.options);
2515            let label = options
2516                .map(|options| options.title.as_str())
2517                .unwrap_or("Missing panel");
2518            let ink = if selected {
2519                palette.text
2520            } else {
2521                palette.text_muted
2522            };
2523            if let (Some(icon), Some(glyph)) = (tab.icon, options.and_then(|options| options.icon))
2524            {
2525                draw_icon_glyph(ctx, glyph, icon, ink);
2526            }
2527            let style = theme.text_style(ink);
2528            ctx.push_clip_rect(tab.label);
2529            paint_text_line(ctx, tab.label, label, &style, TextAlign::Start);
2530            ctx.pop_clip();
2531            if let Some(dirty) = tab.dirty {
2532                ctx.fill_rrect(dirty, [dirty.width() * 0.5; 4], ink);
2533            }
2534            if let Some(close) = tab.close {
2535                if self.hovered_close == Some(tab.panel) {
2536                    ctx.fill_rrect(close, [3.0; 4], palette.control_hover);
2537                }
2538                draw_icon_glyph(ctx, IconGlyph::Close, close.inflate(-3.0, -3.0), ink);
2539            }
2540        }
2541
2542        if group.is_floating() {
2543            stroke_border(ctx, group.bounds, 0.0, 1.0, palette.border);
2544            let handle = floating_resize_rect(group.bounds);
2545            ctx.fill_rect(handle, palette.border.with_alpha(0.72));
2546            ctx.fill_rect(
2547                Rect::new(
2548                    group.header.max_x() - FLOATING_GRIP_WIDTH,
2549                    group.header.y(),
2550                    FLOATING_GRIP_WIDTH,
2551                    group.header.height(),
2552                ),
2553                palette.control_hover.with_alpha(0.34),
2554            );
2555        }
2556    }
2557
2558    fn paint_drag_preview(
2559        &self,
2560        ctx: &mut PaintCtx,
2561        panel: DockPanelId,
2562        position: Point,
2563        theme: &DefaultTheme,
2564    ) {
2565        let width = 168.0;
2566        let height = theme.metrics.tab_height.max(26.0);
2567        let max_x = (ctx.bounds().max_x() - width).max(ctx.bounds().x());
2568        let max_y = (ctx.bounds().max_y() - height).max(ctx.bounds().y());
2569        let bounds = Rect::new(
2570            (position.x + 12.0).clamp(ctx.bounds().x(), max_x),
2571            (position.y + 12.0).clamp(ctx.bounds().y(), max_y),
2572            width,
2573            height,
2574        );
2575        let bounds = snap_to_pixels(ctx, bounds);
2576        ctx.fill_rect(bounds, theme.palette.surface_raised.with_alpha(0.96));
2577        stroke_border(ctx, bounds, 0.0, 1.5, theme.palette.accent);
2578        let text = self
2579            .panel(panel)
2580            .map(|entry| entry.options.title.as_str())
2581            .unwrap_or("Panel");
2582        let style = theme.text_style(theme.palette.text);
2583        let text_bounds = inset_rect_evenly(bounds, 8.0);
2584        ctx.push_clip_rect(text_bounds);
2585        paint_text_line(ctx, text_bounds, text, &style, TextAlign::Start);
2586        ctx.pop_clip();
2587    }
2588}
2589
2590fn drop_zone_at(bounds: Rect, position: Point) -> DockZone {
2591    let edge_x = bounds.width() * DROP_EDGE_FRACTION;
2592    let edge_y = bounds.height() * DROP_EDGE_FRACTION;
2593    let horizontal_distance = (position.x - bounds.x()).min(bounds.max_x() - position.x);
2594    let vertical_distance = (position.y - bounds.y()).min(bounds.max_y() - position.y);
2595    let center_x = bounds.x() + bounds.width() * 0.5;
2596    let center_y = bounds.y() + bounds.height() * 0.5;
2597
2598    if horizontal_distance < edge_x && horizontal_distance <= vertical_distance {
2599        if position.x < center_x {
2600            DockZone::Left
2601        } else {
2602            DockZone::Right
2603        }
2604    } else if vertical_distance < edge_y {
2605        if position.y < center_y {
2606            DockZone::Top
2607        } else {
2608            DockZone::Bottom
2609        }
2610    } else {
2611        DockZone::Center
2612    }
2613}
2614
2615fn drop_zone_rect(bounds: Rect, zone: DockZone) -> Rect {
2616    let bounds = inset_rect_evenly(bounds, DROP_ZONE_INSET);
2617    let edge_width = bounds.width() * DROP_EDGE_FRACTION;
2618    let edge_height = bounds.height() * DROP_EDGE_FRACTION;
2619
2620    match zone {
2621        DockZone::Left => Rect::new(bounds.x(), bounds.y(), edge_width, bounds.height()),
2622        DockZone::Right => Rect::new(
2623            bounds.max_x() - edge_width,
2624            bounds.y(),
2625            edge_width,
2626            bounds.height(),
2627        ),
2628        DockZone::Top => Rect::new(bounds.x(), bounds.y(), bounds.width(), edge_height),
2629        DockZone::Bottom => Rect::new(
2630            bounds.x(),
2631            bounds.max_y() - edge_height,
2632            bounds.width(),
2633            edge_height,
2634        ),
2635        DockZone::Center => Rect::new(
2636            bounds.x() + edge_width,
2637            bounds.y() + edge_height,
2638            (bounds.width() - edge_width * 2.0).max(0.0),
2639            (bounds.height() - edge_height * 2.0).max(0.0),
2640        ),
2641    }
2642}
2643
2644fn paint_drop_targets(ctx: &mut PaintCtx, candidate: &DockDropCandidate, theme: &DefaultTheme) {
2645    const ALL_ZONES: [DockZone; 5] = [
2646        DockZone::Left,
2647        DockZone::Right,
2648        DockZone::Top,
2649        DockZone::Bottom,
2650        DockZone::Center,
2651    ];
2652    const CENTER_ZONE: [DockZone; 1] = [DockZone::Center];
2653    let zones = if candidate.center_only {
2654        &CENTER_ZONE[..]
2655    } else {
2656        &ALL_ZONES[..]
2657    };
2658
2659    for zone in zones {
2660        let bounds = if *zone == candidate.zone {
2661            candidate.zone_bounds
2662        } else {
2663            drop_zone_rect(candidate.host_bounds, *zone)
2664        };
2665        let selected = *zone == candidate.zone;
2666        ctx.fill_rect(
2667            bounds,
2668            if selected {
2669                theme.palette.accent.with_alpha(0.30)
2670            } else {
2671                theme.palette.control_active.with_alpha(0.20)
2672            },
2673        );
2674        stroke_border(
2675            ctx,
2676            bounds,
2677            0.0,
2678            if selected { 2.0 } else { 1.0 },
2679            if selected {
2680                theme.palette.accent
2681            } else {
2682                theme.palette.border_focus.with_alpha(0.72)
2683            },
2684        );
2685    }
2686}
2687
2688fn collect_snapshot_panels(snapshot: &DockWorkspaceSnapshot, output: &mut HashSet<DockPanelId>) {
2689    collect_node_panels(&snapshot.root, output);
2690    for group in &snapshot.floating {
2691        output.extend(group.panels.iter().copied());
2692    }
2693    output.extend(snapshot.hidden.iter().copied());
2694}
2695
2696fn collect_node_panels(node: &DockNode, output: &mut HashSet<DockPanelId>) {
2697    match node {
2698        DockNode::Empty => {}
2699        DockNode::Tabs { panels, .. } => output.extend(panels.iter().copied()),
2700        DockNode::Split { first, second, .. } => {
2701            collect_node_panels(first, output);
2702            collect_node_panels(second, output);
2703        }
2704    }
2705}
2706
2707fn build_workspace_layout(
2708    snapshot: &DockWorkspaceSnapshot,
2709    bounds: Rect,
2710    header_height: f32,
2711    splitter_thickness: f32,
2712    panels: &HashMap<DockPanelId, DockPanelOptions>,
2713) -> DockLayoutCache {
2714    let mut layout = DockLayoutCache {
2715        bounds,
2716        ..DockLayoutCache::default()
2717    };
2718    let mut path = Vec::new();
2719    layout_dock_node(
2720        &snapshot.root,
2721        bounds,
2722        header_height,
2723        splitter_thickness,
2724        panels,
2725        &mut path,
2726        &mut layout,
2727    );
2728
2729    for floating in &snapshot.floating {
2730        let resolved = floating_bounds_in_host(
2731            bounds,
2732            floating.bounds,
2733            floating_min_size(&floating.panels, header_height, panels),
2734        );
2735        layout.groups.push(make_group_layout(
2736            DockGroupLocation::Floating(floating.id),
2737            resolved,
2738            header_height,
2739            &floating.panels,
2740            floating.active,
2741            panels,
2742            true,
2743        ));
2744    }
2745    layout
2746}
2747
2748#[allow(clippy::too_many_arguments)]
2749fn layout_dock_node(
2750    node: &DockNode,
2751    bounds: Rect,
2752    header_height: f32,
2753    splitter_thickness: f32,
2754    panels: &HashMap<DockPanelId, DockPanelOptions>,
2755    path: &mut Vec<DockBranch>,
2756    layout: &mut DockLayoutCache,
2757) {
2758    match node {
2759        DockNode::Empty => {}
2760        DockNode::Tabs {
2761            panels: members,
2762            active,
2763        } => layout.groups.push(make_group_layout(
2764            DockGroupLocation::Docked(path.clone()),
2765            bounds,
2766            header_height,
2767            members,
2768            *active,
2769            panels,
2770            false,
2771        )),
2772        DockNode::Split {
2773            axis,
2774            fraction,
2775            first,
2776            second,
2777        } => {
2778            let total = axis_extent(*axis, bounds.size);
2779            let divider = splitter_thickness.min(total).max(0.0);
2780            let available = (total - divider).max(0.0);
2781            let (first_minimum, second_minimum) = split_minimums(
2782                first,
2783                second,
2784                *axis,
2785                available,
2786                header_height,
2787                splitter_thickness,
2788                panels,
2789            );
2790            let first_extent = (available * *fraction).clamp(
2791                first_minimum,
2792                (available - second_minimum).max(first_minimum),
2793            );
2794            let second_extent = (available - first_extent).max(0.0);
2795            let first_bounds = axis_rect(*axis, bounds, 0.0, first_extent);
2796            let splitter_bounds = axis_rect(*axis, bounds, first_extent, divider);
2797            let second_bounds = axis_rect(*axis, bounds, first_extent + divider, second_extent);
2798            layout.splitters.push(DockSplitterLayout {
2799                path: path.clone(),
2800                axis: *axis,
2801                fraction: *fraction,
2802                bounds: splitter_bounds,
2803                split_bounds: bounds,
2804            });
2805            path.push(DockBranch::First);
2806            layout_dock_node(
2807                first,
2808                first_bounds,
2809                header_height,
2810                splitter_thickness,
2811                panels,
2812                path,
2813                layout,
2814            );
2815            path.pop();
2816            path.push(DockBranch::Second);
2817            layout_dock_node(
2818                second,
2819                second_bounds,
2820                header_height,
2821                splitter_thickness,
2822                panels,
2823                path,
2824                layout,
2825            );
2826            path.pop();
2827        }
2828    }
2829}
2830
2831fn make_group_layout(
2832    location: DockGroupLocation,
2833    bounds: Rect,
2834    header_height: f32,
2835    members: &[DockPanelId],
2836    active: DockPanelId,
2837    panels: &HashMap<DockPanelId, DockPanelOptions>,
2838    floating: bool,
2839) -> DockGroupLayout {
2840    let header_height = header_height.min(bounds.height()).max(0.0);
2841    let header = Rect::new(bounds.x(), bounds.y(), bounds.width(), header_height);
2842    let content = Rect::new(
2843        bounds.x(),
2844        bounds.y() + header_height,
2845        bounds.width(),
2846        (bounds.height() - header_height).max(0.0),
2847    );
2848    let tab_area = if floating {
2849        Rect::new(
2850            header.x(),
2851            header.y(),
2852            (header.width() - FLOATING_GRIP_WIDTH).max(0.0),
2853            header.height(),
2854        )
2855    } else {
2856        header
2857    };
2858    let tabs = tab_rects(tab_area, members, panels);
2859    DockGroupLayout {
2860        location,
2861        bounds,
2862        header,
2863        content,
2864        panels: members.to_vec(),
2865        active,
2866        tabs,
2867    }
2868}
2869
2870/// The largest minimum content extent along `axis` among a tab group's
2871/// panels, any of which may become the active one.
2872fn members_min_content_extent(
2873    members: &[DockPanelId],
2874    axis: Axis,
2875    panels: &HashMap<DockPanelId, DockPanelOptions>,
2876) -> f32 {
2877    members
2878        .iter()
2879        .filter_map(|panel| panels.get(panel))
2880        .map(|options| axis_extent(axis, options.min_size))
2881        .filter(|extent| extent.is_finite())
2882        .fold(0.0, f32::max)
2883}
2884
2885/// The smallest bounds a floating group needs so that every panel in it
2886/// keeps its minimum content size below the tab header.
2887fn floating_min_size(
2888    members: &[DockPanelId],
2889    header_height: f32,
2890    panels: &HashMap<DockPanelId, DockPanelOptions>,
2891) -> Size {
2892    Size::new(
2893        members_min_content_extent(members, Axis::Horizontal, panels).max(MIN_FLOATING_WIDTH),
2894        (members_min_content_extent(members, Axis::Vertical, panels) + header_height)
2895            .max(MIN_FLOATING_HEIGHT),
2896    )
2897}
2898
2899/// The smallest extent a dock node needs along `axis` so that every panel
2900/// in it keeps its minimum content size.
2901fn node_min_extent(
2902    node: &DockNode,
2903    axis: Axis,
2904    header_height: f32,
2905    splitter_thickness: f32,
2906    panels: &HashMap<DockPanelId, DockPanelOptions>,
2907) -> f32 {
2908    match node {
2909        DockNode::Empty => 0.0,
2910        DockNode::Tabs {
2911            panels: members, ..
2912        } => {
2913            let content = members_min_content_extent(members, axis, panels);
2914            let chrome = match axis {
2915                Axis::Horizontal => 0.0,
2916                Axis::Vertical => header_height,
2917            };
2918            (content + chrome).max(MIN_DOCK_PANE_EXTENT)
2919        }
2920        DockNode::Split {
2921            axis: split_axis,
2922            first,
2923            second,
2924            ..
2925        } => {
2926            let first = node_min_extent(first, axis, header_height, splitter_thickness, panels);
2927            let second = node_min_extent(second, axis, header_height, splitter_thickness, panels);
2928            if *split_axis == axis {
2929                first + second + splitter_thickness
2930            } else {
2931                first.max(second)
2932            }
2933        }
2934    }
2935}
2936
2937/// Minimum extents for the two branches of a split with `available` room.
2938///
2939/// When both minimums cannot be met they shrink in proportion, leaving the
2940/// divider a little travel so the user can still trade space between them.
2941fn split_minimums(
2942    first: &DockNode,
2943    second: &DockNode,
2944    axis: Axis,
2945    available: f32,
2946    header_height: f32,
2947    splitter_thickness: f32,
2948    panels: &HashMap<DockPanelId, DockPanelOptions>,
2949) -> (f32, f32) {
2950    let first = node_min_extent(first, axis, header_height, splitter_thickness, panels);
2951    let second = node_min_extent(second, axis, header_height, splitter_thickness, panels);
2952    let budget = (available * 0.9).max(0.0);
2953    if first + second > budget {
2954        let scale = budget / (first + second);
2955        (first * scale, second * scale)
2956    } else {
2957        (first, second)
2958    }
2959}
2960
2961fn tab_rects(
2962    bounds: Rect,
2963    members: &[DockPanelId],
2964    panels: &HashMap<DockPanelId, DockPanelOptions>,
2965) -> Vec<DockTabLayout> {
2966    if members.is_empty() || bounds.width() <= 0.0 {
2967        return Vec::new();
2968    }
2969    let natural = members
2970        .iter()
2971        .map(|panel| {
2972            let options = panels.get(panel);
2973            let characters = options.map_or(12, |options| options.title.chars().count());
2974            let mut width =
2975                (characters as f32 * 7.0 + 28.0).clamp(TAB_MIN_WIDTH, TAB_MAX_TITLE_WIDTH);
2976            if options.is_some_and(|options| options.icon.is_some()) {
2977                width += TAB_ICON_EXTENT + TAB_PART_GAP;
2978            }
2979            if options.is_some_and(|options| options.dirty) {
2980                width += TAB_DIRTY_EXTENT + TAB_PART_GAP;
2981            }
2982            if options.is_some_and(|options| options.closable) {
2983                width += TAB_CLOSE_EXTENT + TAB_PART_GAP;
2984            }
2985            width
2986        })
2987        .collect::<Vec<_>>();
2988    let total = natural.iter().sum::<f32>();
2989    let scale = if total > bounds.width() {
2990        bounds.width() / total
2991    } else {
2992        1.0
2993    };
2994    let mut x = bounds.x();
2995    natural
2996        .into_iter()
2997        .zip(members.iter().copied())
2998        .map(|(width, panel)| {
2999            let width = (width * scale).max(0.0).min(bounds.max_x() - x);
3000            let tab_bounds = Rect::new(x, bounds.y(), width, bounds.height());
3001            x += width;
3002            tab_layout(panel, tab_bounds, panels.get(&panel))
3003        })
3004        .collect()
3005}
3006
3007/// Places a tab's icon, title, unsaved marker, and close button. Parts that
3008/// do not fit a squeezed tab are dropped, the title last.
3009fn tab_layout(
3010    panel: DockPanelId,
3011    bounds: Rect,
3012    options: Option<&DockPanelOptions>,
3013) -> DockTabLayout {
3014    let center_y = bounds.y() + bounds.height() * 0.5;
3015    let mut left = bounds.x() + TAB_TEXT_INSET;
3016    let mut right = bounds.max_x() - TAB_TEXT_INSET;
3017
3018    let close = options
3019        .filter(|options| options.closable && bounds.width() >= TAB_MIN_CLOSE_WIDTH)
3020        .map(|_| {
3021            let extent = TAB_CLOSE_EXTENT.min(bounds.height());
3022            let rect = Rect::new(
3023                bounds.max_x() - TAB_TEXT_INSET * 0.5 - extent,
3024                center_y - extent * 0.5,
3025                extent,
3026                extent,
3027            );
3028            right = rect.x() - TAB_PART_GAP;
3029            rect
3030        });
3031    let icon = options
3032        .filter(|options| options.icon.is_some() && bounds.width() >= TAB_MIN_ICON_WIDTH)
3033        .map(|_| {
3034            let extent = TAB_ICON_EXTENT.min(bounds.height());
3035            let rect = Rect::new(left, center_y - extent * 0.5, extent, extent);
3036            left = rect.max_x() + TAB_PART_GAP;
3037            rect
3038        });
3039    let dirty = options
3040        .filter(|options| options.dirty && right - left >= TAB_DIRTY_EXTENT + TAB_PART_GAP)
3041        .map(|_| {
3042            let rect = Rect::new(
3043                right - TAB_DIRTY_EXTENT,
3044                center_y - TAB_DIRTY_EXTENT * 0.5,
3045                TAB_DIRTY_EXTENT,
3046                TAB_DIRTY_EXTENT,
3047            );
3048            right = rect.x() - TAB_PART_GAP;
3049            rect
3050        });
3051    let label = Rect::new(
3052        left,
3053        bounds.y() + 2.0,
3054        (right - left).max(0.0),
3055        (bounds.height() - 4.0).max(0.0),
3056    );
3057    DockTabLayout {
3058        panel,
3059        bounds,
3060        label,
3061        icon,
3062        dirty,
3063        close,
3064    }
3065}
3066
3067fn axis_extent(axis: Axis, size: Size) -> f32 {
3068    match axis {
3069        Axis::Horizontal => size.width,
3070        Axis::Vertical => size.height,
3071    }
3072}
3073
3074fn axis_rect(axis: Axis, bounds: Rect, offset: f32, extent: f32) -> Rect {
3075    match axis {
3076        Axis::Horizontal => Rect::new(
3077            bounds.x() + offset,
3078            bounds.y(),
3079            extent.max(0.0),
3080            bounds.height(),
3081        ),
3082        Axis::Vertical => Rect::new(
3083            bounds.x(),
3084            bounds.y() + offset,
3085            bounds.width(),
3086            extent.max(0.0),
3087        ),
3088    }
3089}
3090
3091fn floating_resize_rect(bounds: Rect) -> Rect {
3092    Rect::new(
3093        bounds.max_x() - FLOATING_RESIZE_HANDLE,
3094        bounds.max_y() - FLOATING_RESIZE_HANDLE,
3095        FLOATING_RESIZE_HANDLE,
3096        FLOATING_RESIZE_HANDLE,
3097    )
3098}
3099
3100/// Fits a floating group inside `host` at no less than `minimum`, which gives
3101/// way only when the host itself is smaller.
3102fn clamp_floating_bounds(host: Rect, proposed: Rect, minimum: Size) -> Rect {
3103    let host_width = host.width().max(0.0);
3104    let host_height = host.height().max(0.0);
3105    let width = proposed
3106        .width()
3107        .max(minimum.width.min(host_width))
3108        .min(host_width);
3109    let height = proposed
3110        .height()
3111        .max(minimum.height.min(host_height))
3112        .min(host_height);
3113    let min_x = host.x();
3114    let min_y = host.y();
3115    let max_x = (host.max_x() - width).max(min_x);
3116    let max_y = (host.max_y() - height).max(min_y);
3117    Rect::new(
3118        proposed.x().clamp(min_x, max_x),
3119        proposed.y().clamp(min_y, max_y),
3120        width,
3121        height,
3122    )
3123}
3124
3125/// Where a floating group with workspace-relative `bounds` is laid out in a
3126/// workspace arranged at `host`.
3127fn floating_bounds_in_host(host: Rect, bounds: Rect, minimum: Size) -> Rect {
3128    let local_host = Rect::from_origin_size(Point::ZERO, host.size);
3129    clamp_floating_bounds(local_host, bounds, minimum).translate(host.origin - Point::ZERO)
3130}
3131
3132/// The workspace-relative bounds to persist for a floating group that a
3133/// gesture placed at `proposed`, in the coordinates `host` is arranged in.
3134fn floating_bounds_from_host(host: Rect, proposed: Rect, minimum: Size) -> Rect {
3135    clamp_floating_bounds(host, proposed, minimum).translate(Point::ZERO - host.origin)
3136}
3137
3138fn group_members(
3139    snapshot: &DockWorkspaceSnapshot,
3140    location: &DockGroupLocation,
3141) -> Option<(Vec<DockPanelId>, DockPanelId)> {
3142    match location {
3143        DockGroupLocation::Docked(path) => {
3144            let DockNode::Tabs { panels, active } = node_at_path(&snapshot.root, path)? else {
3145                return None;
3146            };
3147            Some((panels.clone(), *active))
3148        }
3149        DockGroupLocation::Floating(id) => snapshot
3150            .floating
3151            .iter()
3152            .find(|group| group.id == *id)
3153            .map(|group| (group.panels.clone(), group.active)),
3154    }
3155}
3156
3157fn panel_location(
3158    snapshot: &DockWorkspaceSnapshot,
3159    panel: DockPanelId,
3160) -> Option<DockGroupLocation> {
3161    let mut path = Vec::new();
3162    if find_panel_path(&snapshot.root, panel, &mut path) {
3163        return Some(DockGroupLocation::Docked(path));
3164    }
3165    snapshot
3166        .floating
3167        .iter()
3168        .find(|group| group.panels.contains(&panel))
3169        .map(|group| DockGroupLocation::Floating(group.id))
3170}
3171
3172fn find_panel_path(node: &DockNode, panel: DockPanelId, path: &mut Vec<DockBranch>) -> bool {
3173    match node {
3174        DockNode::Empty => false,
3175        DockNode::Tabs { panels, .. } => panels.contains(&panel),
3176        DockNode::Split { first, second, .. } => {
3177            path.push(DockBranch::First);
3178            if find_panel_path(first, panel, path) {
3179                return true;
3180            }
3181            path.pop();
3182            path.push(DockBranch::Second);
3183            if find_panel_path(second, panel, path) {
3184                return true;
3185            }
3186            path.pop();
3187            false
3188        }
3189    }
3190}
3191
3192fn dock_tab_semantics_id(parent: WidgetId, panel: DockPanelId) -> WidgetId {
3193    const TAG: u64 = 5_u64 << 50;
3194    const LOW_MASK: u64 = (1_u64 << 50) - 1;
3195    WidgetId::new(
3196        TAG | (parent
3197            .get()
3198            .wrapping_mul(421)
3199            .wrapping_add(panel.get().wrapping_mul(17))
3200            & LOW_MASK),
3201    )
3202}
3203
3204fn dock_close_semantics_id(parent: WidgetId, panel: DockPanelId) -> WidgetId {
3205    const TAG: u64 = 9_u64 << 50;
3206    const LOW_MASK: u64 = (1_u64 << 50) - 1;
3207    WidgetId::new(
3208        TAG | (parent
3209            .get()
3210            .wrapping_mul(443)
3211            .wrapping_add(panel.get().wrapping_mul(19))
3212            & LOW_MASK),
3213    )
3214}
3215
3216fn dock_group_semantics_id(parent: WidgetId, location: &DockGroupLocation) -> WidgetId {
3217    const TAG: u64 = 6_u64 << 50;
3218    const LOW_MASK: u64 = (1_u64 << 50) - 1;
3219    let location_hash = match location {
3220        DockGroupLocation::Docked(path) => path.iter().fold(1_u64, |hash, branch| {
3221            hash.wrapping_mul(31).wrapping_add(match branch {
3222                DockBranch::First => 1,
3223                DockBranch::Second => 2,
3224            })
3225        }),
3226        DockGroupLocation::Floating(id) => id.wrapping_mul(97).wrapping_add(3),
3227    };
3228    WidgetId::new(TAG | (parent.get().wrapping_mul(433).wrapping_add(location_hash) & LOW_MASK))
3229}
3230
3231fn dock_splitter_semantics_id(parent: WidgetId, path: &[DockBranch]) -> WidgetId {
3232    const TAG: u64 = 7_u64 << 50;
3233    const LOW_MASK: u64 = (1_u64 << 50) - 1;
3234    let path_hash = path.iter().fold(1_u64, |hash, branch| {
3235        hash.wrapping_mul(37).wrapping_add(match branch {
3236            DockBranch::First => 1,
3237            DockBranch::Second => 2,
3238        })
3239    });
3240    WidgetId::new(TAG | (parent.get().wrapping_mul(439).wrapping_add(path_hash) & LOW_MASK))
3241}
3242
3243#[cfg(test)]
3244mod tests {
3245    use super::*;
3246    use crate::{Label, SizedBox};
3247    use sui_core::{
3248        Event, KeyboardEvent, Modifiers, PointerButtons, PointerEvent, PointerKind, Vector,
3249        WindowEvent,
3250    };
3251    use sui_runtime::{Application, Runtime, WindowBuilder};
3252    use sui_scene::SceneCommand;
3253
3254    const SCENE: DockPanelId = DockPanelId::new(1);
3255    const VIEWPORT: DockPanelId = DockPanelId::new(2);
3256    const DETAILS: DockPanelId = DockPanelId::new(3);
3257
3258    fn root_snapshot() -> DockWorkspaceSnapshot {
3259        DockWorkspaceSnapshot::new(DockNode::split(
3260            Axis::Horizontal,
3261            0.25,
3262            DockNode::tabs([SCENE], SCENE),
3263            DockNode::split(
3264                Axis::Horizontal,
3265                0.72,
3266                DockNode::tabs([VIEWPORT], VIEWPORT),
3267                DockNode::tabs([DETAILS], DETAILS),
3268            ),
3269        ))
3270    }
3271
3272    fn panel(title: &str) -> SizedBox {
3273        SizedBox::new()
3274            .width(200.0)
3275            .height(160.0)
3276            .child(Label::new(title))
3277    }
3278
3279    fn build_runtime(root: impl Widget + 'static) -> (Runtime, sui_core::WindowId) {
3280        let runtime = Application::new()
3281            .window(WindowBuilder::new().title("Docking").root(root))
3282            .build()
3283            .expect("runtime builds");
3284        let window_id = runtime.window_ids()[0];
3285        (runtime, window_id)
3286    }
3287
3288    fn resize(runtime: &mut Runtime, window_id: sui_core::WindowId, width: f32, height: f32) {
3289        runtime
3290            .handle_event(
3291                window_id,
3292                Event::Window(WindowEvent::Resized(Size::new(width, height))),
3293            )
3294            .expect("window resizes");
3295    }
3296
3297    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
3298        let mut buttons = PointerButtons::NONE;
3299        if pressed {
3300            buttons.insert(PointerButton::Primary);
3301        }
3302        Event::Pointer(PointerEvent {
3303            pointer_id: 1,
3304            kind,
3305            position,
3306            delta: Vector::ZERO,
3307            scroll_delta: None,
3308            button: Some(PointerButton::Primary),
3309            buttons,
3310            modifiers: Modifiers::NONE,
3311            pointer_kind: PointerKind::Mouse,
3312            is_primary: true,
3313        })
3314    }
3315
3316    #[test]
3317    fn snapshot_rejects_duplicate_panels_and_invalid_splits() {
3318        let duplicate = DockWorkspaceSnapshot::new(DockNode::split(
3319            Axis::Horizontal,
3320            0.5,
3321            DockNode::tabs([SCENE], SCENE),
3322            DockNode::tabs([SCENE], SCENE),
3323        ));
3324        assert!(DockWorkspaceState::new(duplicate).is_err());
3325
3326        let invalid = DockWorkspaceSnapshot::new(DockNode::Split {
3327            axis: Axis::Horizontal,
3328            fraction: f32::NAN,
3329            first: Box::new(DockNode::tabs([SCENE], SCENE)),
3330            second: Box::new(DockNode::tabs([VIEWPORT], VIEWPORT)),
3331        });
3332        assert!(DockWorkspaceState::new(invalid).is_err());
3333
3334        let empty_branch = DockWorkspaceSnapshot::new(DockNode::Split {
3335            axis: Axis::Horizontal,
3336            fraction: 0.5,
3337            first: Box::new(DockNode::Empty),
3338            second: Box::new(DockNode::tabs([VIEWPORT], VIEWPORT)),
3339        });
3340        assert!(DockWorkspaceState::new(empty_branch).is_err());
3341    }
3342
3343    #[test]
3344    fn state_round_trips_hide_float_and_dock_without_duplicates() {
3345        let state = DockWorkspaceState::new(root_snapshot()).expect("valid root");
3346        let floating = state
3347            .float_panel(DETAILS, Rect::new(80.0, 60.0, 300.0, 240.0))
3348            .expect("details floats");
3349        assert_eq!(floating, 1);
3350        assert_eq!(state.snapshot().floating[0].panels, vec![DETAILS]);
3351
3352        assert!(state.hide(SCENE).expect("scene hides"));
3353        assert!(state.snapshot().hidden.contains(&SCENE));
3354        assert!(state.show(SCENE).expect("scene shows"));
3355        assert!(!state.snapshot().hidden.contains(&SCENE));
3356
3357        assert!(
3358            state
3359                .dock(DETAILS, VIEWPORT, DockZone::Center)
3360                .expect("details docks")
3361        );
3362        let snapshot = state.snapshot();
3363        assert!(snapshot.floating.is_empty());
3364        validate_snapshot(&snapshot).expect("mutated snapshot stays canonical");
3365    }
3366
3367    #[test]
3368    fn docking_and_floating_preserve_panel_widget_identity() {
3369        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3370            [VIEWPORT, DETAILS],
3371            VIEWPORT,
3372        )))
3373        .expect("valid tabs");
3374        let workspace = DockWorkspace::new(state.clone())
3375            .with_panel(VIEWPORT, "Viewport", panel("Viewport content"))
3376            .with_panel(DETAILS, "Details", panel("Details content"));
3377        let details_widget = workspace
3378            .panel_widget_id(DETAILS)
3379            .expect("details widget registered");
3380        let (mut runtime, window_id) = build_runtime(workspace);
3381        resize(&mut runtime, window_id, 800.0, 600.0);
3382        runtime.render(window_id).expect("initial frame");
3383
3384        state
3385            .float_panel(DETAILS, Rect::new(400.0, 80.0, 280.0, 320.0))
3386            .expect("details floats");
3387        runtime.render(window_id).expect("floating frame");
3388        assert!(
3389            runtime
3390                .widget_graph(window_id)
3391                .expect("floating graph")
3392                .nodes
3393                .iter()
3394                .any(|node| node.id == details_widget)
3395        );
3396
3397        state
3398            .dock(DETAILS, VIEWPORT, DockZone::Center)
3399            .expect("details docks again");
3400        state.activate(DETAILS).expect("details activates");
3401        runtime.render(window_id).expect("redocked frame");
3402        assert!(
3403            runtime
3404                .widget_graph(window_id)
3405                .expect("redocked graph")
3406                .nodes
3407                .iter()
3408                .any(|node| node.id == details_widget),
3409            "the original retained details widget must be reused"
3410        );
3411    }
3412
3413    #[test]
3414    fn dock_tab_titles_are_shaped_as_one_line() {
3415        const WORKFLOW: DockPanelId = DockPanelId::new(10);
3416        const MODELS: DockPanelId = DockPanelId::new(11);
3417        const WORKFLOW_TITLE: &str = "Image-to-3D Workflow";
3418        const MODELS_TITLE: &str = "Model Manager";
3419
3420        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3421            [WORKFLOW, MODELS],
3422            WORKFLOW,
3423        )))
3424        .expect("valid tabs");
3425        let workspace = DockWorkspace::new(state)
3426            .with_panel(WORKFLOW, WORKFLOW_TITLE, panel("Workflow body"))
3427            .with_panel(MODELS, MODELS_TITLE, panel("Models body"));
3428        let (mut runtime, window_id) = build_runtime(workspace);
3429        resize(&mut runtime, window_id, 340.0, 240.0);
3430        let output = runtime.render(window_id).expect("dock tabs render");
3431
3432        for title in [WORKFLOW_TITLE, MODELS_TITLE] {
3433            let mut line_counts = Vec::new();
3434            output.frame.scene.visit_commands(&mut |command| {
3435                let SceneCommand::DrawShapedText(run) = command else {
3436                    return;
3437                };
3438                if let Some(layout) = run
3439                    .resolve(output.frame.text_layout_registry.as_ref())
3440                    .filter(|layout| layout.text() == title)
3441                {
3442                    line_counts.push(layout.lines().len());
3443                }
3444            });
3445            assert_eq!(
3446                line_counts,
3447                vec![1],
3448                "dock tab title {title:?} must remain a single line"
3449            );
3450        }
3451    }
3452
3453    #[test]
3454    fn splitter_pointer_drag_updates_persisted_fraction() {
3455        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
3456            Axis::Horizontal,
3457            0.5,
3458            DockNode::tabs([SCENE], SCENE),
3459            DockNode::tabs([VIEWPORT], VIEWPORT),
3460        )))
3461        .expect("valid split");
3462        let root = DockWorkspace::new(state.clone())
3463            .with_panel(SCENE, "Scene", panel("Scene"))
3464            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
3465        let (mut runtime, window_id) = build_runtime(root);
3466        resize(&mut runtime, window_id, 800.0, 600.0);
3467        runtime.render(window_id).expect("initial frame");
3468
3469        runtime
3470            .handle_event(
3471                window_id,
3472                primary_pointer(PointerEventKind::Down, Point::new(400.0, 300.0), true),
3473            )
3474            .expect("split press");
3475        runtime
3476            .handle_event(
3477                window_id,
3478                primary_pointer(PointerEventKind::Move, Point::new(600.0, 300.0), true),
3479            )
3480            .expect("split move");
3481        runtime
3482            .handle_event(
3483                window_id,
3484                primary_pointer(PointerEventKind::Up, Point::new(600.0, 300.0), false),
3485            )
3486            .expect("split release");
3487
3488        let DockNode::Split { fraction, .. } = state.snapshot().root else {
3489            panic!("root remains split");
3490        };
3491        assert!(fraction > 0.7, "dragged fraction was {fraction}");
3492    }
3493
3494    #[test]
3495    fn pointer_tab_drag_floats_redocks_and_preserves_widget_identity() {
3496        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3497            [SCENE, VIEWPORT],
3498            SCENE,
3499        )))
3500        .expect("valid tabs");
3501        let workspace = DockWorkspace::new(state.clone())
3502            .with_panel(SCENE, "Scene", panel("Scene"))
3503            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
3504        let scene_widget = workspace
3505            .panel_widget_id(SCENE)
3506            .expect("scene widget registered");
3507        let (mut runtime, window_id) = build_runtime(workspace);
3508        resize(&mut runtime, window_id, 800.0, 600.0);
3509        runtime.render(window_id).expect("initial frame");
3510
3511        runtime
3512            .handle_event(
3513                window_id,
3514                primary_pointer(PointerEventKind::Down, Point::new(20.0, 10.0), true),
3515            )
3516            .expect("scene tab press");
3517        runtime
3518            .handle_event(
3519                window_id,
3520                primary_pointer(PointerEventKind::Move, Point::new(840.0, 40.0), true),
3521            )
3522            .expect("scene tab drag outside");
3523        runtime
3524            .handle_event(
3525                window_id,
3526                primary_pointer(PointerEventKind::Up, Point::new(840.0, 40.0), false),
3527            )
3528            .expect("scene tab float drop");
3529
3530        let floated = state.snapshot();
3531        assert_eq!(floated.floating.len(), 1);
3532        assert_eq!(floated.floating[0].panels, vec![SCENE]);
3533        assert!(node_contains_panel(&floated.root, VIEWPORT));
3534        let floating_bounds = floated.floating[0].bounds;
3535
3536        runtime.render(window_id).expect("floating frame");
3537        assert!(
3538            runtime
3539                .widget_graph(window_id)
3540                .expect("floating graph")
3541                .nodes
3542                .iter()
3543                .any(|node| node.id == scene_widget)
3544        );
3545
3546        let floating_tab = Point::new(floating_bounds.x() + 20.0, floating_bounds.y() + 10.0);
3547        runtime
3548            .handle_event(
3549                window_id,
3550                primary_pointer(PointerEventKind::Down, floating_tab, true),
3551            )
3552            .expect("floating scene tab press");
3553        runtime
3554            .handle_event(
3555                window_id,
3556                primary_pointer(PointerEventKind::Move, Point::new(8.0, 300.0), true),
3557            )
3558            .expect("floating scene tab drag to dock edge");
3559        runtime
3560            .handle_event(
3561                window_id,
3562                primary_pointer(PointerEventKind::Up, Point::new(8.0, 300.0), false),
3563            )
3564            .expect("floating scene tab dock drop");
3565
3566        let redocked = state.snapshot();
3567        assert!(redocked.floating.is_empty());
3568        assert!(matches!(
3569            redocked.root,
3570            DockNode::Split {
3571                axis: Axis::Horizontal,
3572                ..
3573            }
3574        ));
3575        validate_snapshot(&redocked).expect("pointer-mutated snapshot stays canonical");
3576
3577        runtime.render(window_id).expect("redocked frame");
3578        assert!(
3579            runtime
3580                .widget_graph(window_id)
3581                .expect("redocked graph")
3582                .nodes
3583                .iter()
3584                .any(|node| node.id == scene_widget),
3585            "the same retained scene widget must survive float and dock gestures"
3586        );
3587    }
3588
3589    #[test]
3590    fn tab_drag_updates_keyboard_navigation_to_the_destination_group() {
3591        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
3592            Axis::Horizontal,
3593            0.5,
3594            DockNode::tabs([SCENE, DETAILS], SCENE),
3595            DockNode::tabs([VIEWPORT], VIEWPORT),
3596        )))
3597        .expect("valid split tabs");
3598        let workspace = DockWorkspace::new(state.clone())
3599            .with_panel(SCENE, "Scene", panel("Scene"))
3600            .with_panel(VIEWPORT, "Viewport", panel("Viewport"))
3601            .with_panel(DETAILS, "Details", panel("Details"));
3602        let (mut runtime, window_id) = build_runtime(workspace);
3603        resize(&mut runtime, window_id, 800.0, 600.0);
3604        runtime.render(window_id).expect("initial frame");
3605
3606        runtime
3607            .handle_event(
3608                window_id,
3609                primary_pointer(PointerEventKind::Down, Point::new(20.0, 10.0), true),
3610            )
3611            .expect("source tab press");
3612        runtime
3613            .handle_event(
3614                window_id,
3615                primary_pointer(PointerEventKind::Move, Point::new(600.0, 300.0), true),
3616            )
3617            .expect("drag to destination center");
3618        runtime
3619            .handle_event(
3620                window_id,
3621                primary_pointer(PointerEventKind::Up, Point::new(600.0, 300.0), false),
3622            )
3623            .expect("drop into destination tabs");
3624        runtime
3625            .handle_event(
3626                window_id,
3627                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
3628            )
3629            .expect("cycle destination tabs");
3630
3631        let DockNode::Split { first, second, .. } = state.snapshot().root else {
3632            panic!("workspace remains split");
3633        };
3634        let DockNode::Tabs {
3635            active: source_active,
3636            ..
3637        } = *first
3638        else {
3639            panic!("source remains a tab group");
3640        };
3641        let DockNode::Tabs {
3642            panels,
3643            active: destination_active,
3644        } = *second
3645        else {
3646            panic!("destination remains a tab group");
3647        };
3648        assert_eq!(source_active, DETAILS);
3649        assert_eq!(panels, vec![VIEWPORT, SCENE]);
3650        assert_eq!(
3651            destination_active, VIEWPORT,
3652            "ArrowRight must cycle the destination group after the drag"
3653        );
3654    }
3655
3656    #[test]
3657    fn splitter_semantics_expose_and_mutate_the_persisted_fraction() {
3658        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
3659            Axis::Horizontal,
3660            0.5,
3661            DockNode::tabs([SCENE], SCENE),
3662            DockNode::tabs([VIEWPORT], VIEWPORT),
3663        )))
3664        .expect("valid split");
3665        let workspace = DockWorkspace::new(state.clone())
3666            .with_panel(SCENE, "Scene", panel("Scene"))
3667            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
3668        let (mut runtime, window_id) = build_runtime(workspace);
3669        resize(&mut runtime, window_id, 800.0, 600.0);
3670        let frame = runtime.render(window_id).expect("initial frame");
3671        let splitter = frame
3672            .semantics
3673            .iter()
3674            .find(|node| node.role == SemanticsRole::Splitter)
3675            .expect("dock splitter semantics");
3676        assert_eq!(
3677            splitter.value,
3678            Some(SemanticsValue::Range {
3679                value: 0.5,
3680                min: f64::from(MIN_SPLIT_FRACTION),
3681                max: f64::from(MAX_SPLIT_FRACTION),
3682            })
3683        );
3684        for action in [
3685            SemanticsAction::Increment,
3686            SemanticsAction::Decrement,
3687            SemanticsAction::SetValue,
3688        ] {
3689            assert!(splitter.actions.contains(&action));
3690        }
3691        let splitter_id = splitter.id;
3692
3693        assert!(
3694            runtime
3695                .handle_semantics_action(window_id, splitter_id, SemanticsActionRequest::Increment,)
3696                .expect("increment semantics routes")
3697        );
3698        let DockNode::Split { fraction, .. } = state.snapshot().root else {
3699            panic!("root remains split");
3700        };
3701        assert!((fraction - 0.55).abs() < f32::EPSILON);
3702
3703        runtime.render(window_id).expect("incremented frame");
3704        assert!(
3705            runtime
3706                .handle_semantics_action(
3707                    window_id,
3708                    splitter_id,
3709                    SemanticsActionRequest::SetValue(SemanticsValue::Number(0.8)),
3710                )
3711                .expect("set-value semantics routes")
3712        );
3713        let DockNode::Split { fraction, .. } = state.snapshot().root else {
3714            panic!("root remains split");
3715        };
3716        assert!((fraction - 0.8).abs() < f32::EPSILON);
3717    }
3718
3719    fn click(runtime: &mut Runtime, window_id: sui_core::WindowId, position: Point) {
3720        runtime
3721            .handle_event(
3722                window_id,
3723                primary_pointer(PointerEventKind::Down, position, true),
3724            )
3725            .expect("press");
3726        runtime
3727            .handle_event(
3728                window_id,
3729                primary_pointer(PointerEventKind::Up, position, false),
3730            )
3731            .expect("release");
3732    }
3733
3734    fn named<'a>(semantics: &'a [SemanticsNode], name: &str) -> Option<&'a SemanticsNode> {
3735        semantics
3736            .iter()
3737            .find(|node| node.name.as_deref() == Some(name))
3738    }
3739
3740    fn center(rect: Rect) -> Point {
3741        Point::new(
3742            rect.x() + rect.width() * 0.5,
3743            rect.y() + rect.height() * 0.5,
3744        )
3745    }
3746
3747    #[test]
3748    fn panels_can_be_added_and_removed_while_mounted() {
3749        let state =
3750            DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)))
3751                .expect("valid tabs");
3752        let mut builds = 0;
3753        let workspace = DockWorkspace::new(state.clone())
3754            .with_panel(SCENE, "Scene", panel("Scene body"))
3755            .panel_builder(move |id| {
3756                assert_eq!(id, DETAILS);
3757                builds += 1;
3758                Box::new(panel(&format!("Details build {builds}")))
3759            });
3760        let (mut runtime, window_id) = build_runtime(workspace);
3761        resize(&mut runtime, window_id, 800.0, 600.0);
3762        runtime.render(window_id).expect("initial frame");
3763
3764        state
3765            .add_panel(
3766                DETAILS,
3767                "Details",
3768                DockPlacement::Beside {
3769                    target: SCENE,
3770                    zone: DockZone::Right,
3771                },
3772            )
3773            .expect("details registers while mounted");
3774        assert!(state.is_registered(DETAILS));
3775        assert!(
3776            state
3777                .add_panel(DETAILS, "Again", DockPlacement::Hidden)
3778                .is_err(),
3779            "a registered ID cannot be registered twice"
3780        );
3781        assert!(
3782            state
3783                .add_panel(SCENE, "Scene", DockPlacement::Hidden)
3784                .is_err(),
3785            "builder-registered IDs are known to the state"
3786        );
3787
3788        let frame = runtime.render(window_id).expect("frame with added panel");
3789        assert!(named(&frame.semantics, "Details").is_some());
3790        assert!(named(&frame.semantics, "Details build 1").is_some());
3791
3792        assert!(state.remove_panel(DETAILS).expect("details removes"));
3793        assert!(!state.is_registered(DETAILS));
3794        assert!(
3795            !state
3796                .remove_panel(DETAILS)
3797                .expect("second removal is a no-op")
3798        );
3799        let frame = runtime.render(window_id).expect("frame without panel");
3800        assert!(named(&frame.semantics, "Details").is_none());
3801        assert!(named(&frame.semantics, "Details build 1").is_none());
3802        assert_eq!(state.snapshot().root, DockNode::tabs([SCENE], SCENE));
3803
3804        state
3805            .add_panel(DETAILS, "Details", DockPlacement::Root(DockZone::Bottom))
3806            .expect("a removed ID can be reused");
3807        let frame = runtime.render(window_id).expect("frame with reused ID");
3808        assert!(named(&frame.semantics, "Details build 2").is_some());
3809    }
3810
3811    #[test]
3812    fn state_stays_shareable_across_threads() {
3813        fn assert_send_sync<T: Send + Sync>() {}
3814        assert_send_sync::<DockWorkspaceState>();
3815
3816        let state =
3817            DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)))
3818                .expect("valid tabs");
3819        let workspace =
3820            DockWorkspace::new(state.clone()).with_panel(SCENE, "Scene", panel("Scene"));
3821        let (mut runtime, window_id) = build_runtime(workspace);
3822        resize(&mut runtime, window_id, 800.0, 600.0);
3823        runtime.render(window_id).expect("initial frame");
3824
3825        let worker_state = state.clone();
3826        std::thread::spawn(move || {
3827            worker_state
3828                .add_panel(DETAILS, "Details", DockPlacement::Root(DockZone::Right))
3829                .expect("a worker thread may queue a panel");
3830        })
3831        .join()
3832        .expect("worker finishes");
3833
3834        let frame = runtime.render(window_id).expect("frame with queued panel");
3835        assert!(
3836            named(&frame.semantics, "Details").is_some(),
3837            "a panel without a builder still gets its tab"
3838        );
3839    }
3840
3841    #[test]
3842    fn dock_tab_reorders_within_a_group_and_inserts_into_another() {
3843        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
3844            Axis::Horizontal,
3845            0.5,
3846            DockNode::tabs([SCENE, VIEWPORT], SCENE),
3847            DockNode::tabs([DETAILS], DETAILS),
3848        )))
3849        .expect("valid split");
3850
3851        assert!(state.dock_tab(VIEWPORT, SCENE, false).expect("reorders"));
3852        let DockNode::Split { first, .. } = state.snapshot().root else {
3853            panic!("root remains split");
3854        };
3855        assert_eq!(*first, DockNode::tabs([VIEWPORT, SCENE], VIEWPORT));
3856
3857        assert!(state.dock_tab(DETAILS, VIEWPORT, true).expect("inserts"));
3858        assert_eq!(
3859            state.snapshot().root,
3860            DockNode::tabs([VIEWPORT, DETAILS, SCENE], DETAILS),
3861            "the emptied group collapses and the tab lands after its anchor"
3862        );
3863        assert!(state.dock_tab(SCENE, DockPanelId::new(99), true).is_err());
3864    }
3865
3866    #[test]
3867    fn dragging_a_tab_along_its_header_reorders_the_group() {
3868        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3869            [SCENE, VIEWPORT],
3870            SCENE,
3871        )))
3872        .expect("valid tabs");
3873        let workspace = DockWorkspace::new(state.clone())
3874            .with_panel(SCENE, "Scene", panel("Scene"))
3875            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
3876        let (mut runtime, window_id) = build_runtime(workspace);
3877        resize(&mut runtime, window_id, 800.0, 600.0);
3878        let frame = runtime.render(window_id).expect("initial frame");
3879        let scene_tab = named(&frame.semantics, "Scene").expect("scene tab").bounds;
3880        let viewport_tab = named(&frame.semantics, "Viewport")
3881            .expect("viewport tab")
3882            .bounds;
3883        let drop = Point::new(viewport_tab.max_x() - 4.0, center(viewport_tab).y);
3884
3885        runtime
3886            .handle_event(
3887                window_id,
3888                primary_pointer(PointerEventKind::Down, center(scene_tab), true),
3889            )
3890            .expect("scene tab press");
3891        runtime
3892            .handle_event(
3893                window_id,
3894                primary_pointer(PointerEventKind::Move, drop, true),
3895            )
3896            .expect("drag past the viewport tab");
3897        runtime
3898            .handle_event(
3899                window_id,
3900                primary_pointer(PointerEventKind::Up, drop, false),
3901            )
3902            .expect("drop");
3903
3904        assert_eq!(
3905            state.snapshot().root,
3906            DockNode::tabs([VIEWPORT, SCENE], SCENE)
3907        );
3908        assert!(state.snapshot().floating.is_empty());
3909    }
3910
3911    #[test]
3912    fn close_button_hides_by_default_and_follows_the_close_handler() {
3913        let closable = |title: &str| DockPanelOptions::new(title).closable(true);
3914        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3915            [SCENE, VIEWPORT, DETAILS],
3916            SCENE,
3917        )))
3918        .expect("valid tabs");
3919        let workspace = DockWorkspace::new(state.clone())
3920            .with_panel(SCENE, closable("Scene"), panel("Scene"))
3921            .with_panel(VIEWPORT, "Viewport", panel("Viewport"))
3922            .with_panel(DETAILS, closable("Details"), panel("Details"));
3923        let (mut runtime, window_id) = build_runtime(workspace);
3924        resize(&mut runtime, window_id, 800.0, 600.0);
3925        let frame = runtime.render(window_id).expect("initial frame");
3926        assert!(
3927            named(&frame.semantics, "Close Viewport").is_none(),
3928            "only closable panels expose a close button"
3929        );
3930        let close = named(&frame.semantics, "Close Scene").expect("scene close button");
3931        assert_eq!(close.role, SemanticsRole::Button);
3932        click(&mut runtime, window_id, center(close.bounds));
3933        assert!(state.snapshot().hidden.contains(&SCENE));
3934        assert!(state.is_registered(SCENE), "hiding keeps the panel widget");
3935
3936        let frame = runtime.render(window_id).expect("frame after hide");
3937        let close_id = named(&frame.semantics, "Close Details")
3938            .expect("details close button")
3939            .id;
3940        assert!(
3941            runtime
3942                .handle_semantics_action(window_id, close_id, SemanticsActionRequest::Activate)
3943                .expect("close semantics routes")
3944        );
3945        assert!(state.snapshot().hidden.contains(&DETAILS));
3946    }
3947
3948    #[test]
3949    fn close_handler_can_keep_or_remove_a_panel() {
3950        let action = std::rc::Rc::new(std::cell::Cell::new(DockCloseAction::Keep));
3951        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
3952            [SCENE, VIEWPORT],
3953            SCENE,
3954        )))
3955        .expect("valid tabs");
3956        let handler_action = std::rc::Rc::clone(&action);
3957        let workspace = DockWorkspace::new(state.clone())
3958            .with_panel(
3959                SCENE,
3960                DockPanelOptions::new("Scene").closable(true).dirty(true),
3961                panel("Scene"),
3962            )
3963            .with_panel(VIEWPORT, "Viewport", panel("Viewport"))
3964            .on_close_request(move |panel| {
3965                assert_eq!(panel, SCENE);
3966                handler_action.get()
3967            });
3968        let (mut runtime, window_id) = build_runtime(workspace);
3969        resize(&mut runtime, window_id, 800.0, 600.0);
3970        let frame = runtime.render(window_id).expect("initial frame");
3971        let close = center(
3972            named(&frame.semantics, "Close Scene")
3973                .expect("scene close button")
3974                .bounds,
3975        );
3976
3977        click(&mut runtime, window_id, close);
3978        assert_eq!(
3979            state.snapshot().root,
3980            DockNode::tabs([SCENE, VIEWPORT], SCENE),
3981            "a vetoed close leaves the layout untouched"
3982        );
3983
3984        action.set(DockCloseAction::Remove);
3985        click(&mut runtime, window_id, close);
3986        assert_eq!(state.snapshot().root, DockNode::tabs([VIEWPORT], VIEWPORT));
3987        assert!(state.snapshot().hidden.is_empty());
3988        assert!(!state.is_registered(SCENE));
3989        let frame = runtime.render(window_id).expect("frame after removal");
3990        assert!(named(&frame.semantics, "Scene").is_none());
3991    }
3992
3993    #[test]
3994    fn update_panel_changes_the_tab_title_and_unsaved_marker() {
3995        let state =
3996            DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)))
3997                .expect("valid tabs");
3998        let workspace = DockWorkspace::new(state.clone()).with_panel(SCENE, "Scene", panel("Body"));
3999        let (mut runtime, window_id) = build_runtime(workspace);
4000        resize(&mut runtime, window_id, 800.0, 600.0);
4001        let frame = runtime.render(window_id).expect("initial frame");
4002        assert_eq!(
4003            named(&frame.semantics, "Scene")
4004                .expect("scene tab")
4005                .description,
4006            None
4007        );
4008
4009        state
4010            .update_panel(SCENE, |options| {
4011                options.title = "Renamed".to_string();
4012                options.dirty = true;
4013            })
4014            .expect("registered panel updates");
4015        let frame = runtime.render(window_id).expect("updated frame");
4016        assert!(named(&frame.semantics, "Scene").is_none());
4017        assert_eq!(
4018            named(&frame.semantics, "Renamed")
4019                .expect("renamed tab")
4020                .description
4021                .as_deref(),
4022            Some("Unsaved changes")
4023        );
4024        assert!(state.update_panel(VIEWPORT, |_| {}).is_err());
4025    }
4026
4027    #[test]
4028    fn splits_keep_panels_at_their_minimum_size() {
4029        let snapshot = DockWorkspaceSnapshot::new(DockNode::split(
4030            Axis::Horizontal,
4031            0.2,
4032            DockNode::tabs([SCENE], SCENE),
4033            DockNode::tabs([VIEWPORT], VIEWPORT),
4034        ));
4035        let width_of = |layout: &DockLayoutCache, panel: DockPanelId| {
4036            layout
4037                .groups
4038                .iter()
4039                .find(|group| group.active == panel)
4040                .expect("group is laid out")
4041                .bounds
4042                .width()
4043        };
4044        let mut panels = HashMap::new();
4045        panels.insert(
4046            SCENE,
4047            DockPanelOptions::new("Scene").min_size(Size::new(420.0, 0.0)),
4048        );
4049        panels.insert(VIEWPORT, DockPanelOptions::new("Viewport"));
4050        let bounds = Rect::new(0.0, 0.0, 804.0, 600.0);
4051
4052        let layout = build_workspace_layout(&snapshot, bounds, 28.0, 4.0, &panels);
4053        assert!((width_of(&layout, SCENE) - 420.0).abs() < 0.5);
4054        assert!((width_of(&layout, VIEWPORT) - 380.0).abs() < 0.5);
4055
4056        panels.insert(
4057            VIEWPORT,
4058            DockPanelOptions::new("Viewport").min_size(Size::new(1_260.0, 0.0)),
4059        );
4060        let layout = build_workspace_layout(&snapshot, bounds, 28.0, 4.0, &panels);
4061        let scene = width_of(&layout, SCENE);
4062        let viewport = width_of(&layout, VIEWPORT);
4063        assert!((scene + viewport - 800.0).abs() < 0.5);
4064        assert!(
4065            scene >= 150.0 && viewport > scene * 2.5,
4066            "minimums that cannot both fit shrink in proportion: {scene} / {viewport}"
4067        );
4068    }
4069
4070    #[test]
4071    fn retain_panels_prunes_missing_panels_and_stays_valid() {
4072        let mut snapshot = root_snapshot().with_floating(DockFloatingGroup::new(
4073            1,
4074            [DockPanelId::new(7)],
4075            DockPanelId::new(7),
4076            Rect::new(40.0, 40.0, 300.0, 240.0),
4077        ));
4078        snapshot.hidden.push(DockPanelId::new(8));
4079
4080        snapshot.retain_panels(|panel| panel == SCENE || panel == DETAILS);
4081
4082        validate_snapshot(&snapshot).expect("pruned snapshot stays canonical");
4083        assert!(snapshot.floating.is_empty());
4084        assert!(snapshot.hidden.is_empty());
4085        assert_eq!(
4086            snapshot.root,
4087            DockNode::split(
4088                Axis::Horizontal,
4089                0.25,
4090                DockNode::tabs([SCENE], SCENE),
4091                DockNode::tabs([DETAILS], DETAILS),
4092            )
4093        );
4094    }
4095
4096    #[test]
4097    fn floating_layout_collapses_minimum_size_to_a_tiny_host() {
4098        let host = Rect::new(10.0, 20.0, 100.0, 80.0);
4099        let resolved = clamp_floating_bounds(
4100            host,
4101            Rect::new(-400.0, 500.0, 320.0, 260.0),
4102            Size::new(MIN_FLOATING_WIDTH, MIN_FLOATING_HEIGHT),
4103        );
4104        assert_eq!(resolved, host);
4105    }
4106
4107    #[test]
4108    fn floating_groups_keep_panels_at_their_minimum_size() {
4109        let snapshot = DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)).with_floating(
4110            DockFloatingGroup::new(
4111                1,
4112                [VIEWPORT, DETAILS],
4113                VIEWPORT,
4114                Rect::new(40.0, 40.0, 200.0, 140.0),
4115            ),
4116        );
4117        let mut panels = HashMap::new();
4118        panels.insert(
4119            VIEWPORT,
4120            DockPanelOptions::new("Viewport").min_size(Size::new(360.0, 0.0)),
4121        );
4122        panels.insert(
4123            DETAILS,
4124            DockPanelOptions::new("Details").min_size(Size::new(0.0, 300.0)),
4125        );
4126        let floating = |host: Rect| {
4127            build_workspace_layout(&snapshot, host, 28.0, 4.0, &panels)
4128                .groups
4129                .into_iter()
4130                .find(DockGroupLayout::is_floating)
4131                .expect("floating group is laid out")
4132        };
4133
4134        // The group fits its widest and its tallest tab, not only the active
4135        // one, so switching tabs never leaves a panel below its minimum.
4136        let group = floating(Rect::new(0.0, 0.0, 1_000.0, 800.0));
4137        assert_eq!(group.bounds, Rect::new(40.0, 40.0, 360.0, 328.0));
4138        assert_eq!(group.content.size, Size::new(360.0, 300.0));
4139
4140        // A host smaller than the minimum still wins.
4141        let group = floating(Rect::new(0.0, 0.0, 300.0, 200.0));
4142        assert_eq!(group.bounds, Rect::new(0.0, 0.0, 300.0, 200.0));
4143    }
4144
4145    #[test]
4146    fn floating_bounds_are_relative_to_the_workspace() {
4147        let state = DockWorkspaceState::new(
4148            DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)).with_floating(
4149                DockFloatingGroup::new(
4150                    1,
4151                    [VIEWPORT],
4152                    VIEWPORT,
4153                    Rect::new(40.0, 40.0, 300.0, 200.0),
4154                ),
4155            ),
4156        )
4157        .expect("valid floating layout");
4158        let workspace = DockWorkspace::new(state.clone())
4159            .with_panel(SCENE, "Scene", panel("Scene"))
4160            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
4161        let (mut runtime, window_id) = build_runtime(crate::Padding::all(100.0, workspace));
4162        resize(&mut runtime, window_id, 900.0, 700.0);
4163        let frame = runtime.render(window_id).expect("initial frame");
4164        let tabs = named(&frame.semantics, "Floating panel tabs").expect("floating tab bar");
4165        assert_eq!(tabs.bounds.origin, Point::new(140.0, 140.0));
4166
4167        // Drag the header's grip, right of the tab, by (10, 20).
4168        let grip = Point::new(430.0, 150.0);
4169        let dropped = Point::new(440.0, 170.0);
4170        for (kind, position, pressed) in [
4171            (PointerEventKind::Down, grip, true),
4172            (PointerEventKind::Move, dropped, true),
4173            (PointerEventKind::Up, dropped, false),
4174        ] {
4175            runtime
4176                .handle_event(window_id, primary_pointer(kind, position, pressed))
4177                .expect("move gesture");
4178        }
4179        assert_eq!(
4180            state.snapshot().floating[0].bounds,
4181            Rect::new(50.0, 60.0, 300.0, 200.0)
4182        );
4183    }
4184
4185    #[test]
4186    fn scrolling_an_ancestor_moves_the_tabs_with_the_panels() {
4187        let state = DockWorkspaceState::new(
4188            DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)).with_floating(
4189                DockFloatingGroup::new(
4190                    1,
4191                    [VIEWPORT],
4192                    VIEWPORT,
4193                    Rect::new(40.0, 80.0, 300.0, 200.0),
4194                ),
4195            ),
4196        )
4197        .expect("valid layout");
4198        let workspace = DockWorkspace::new(state.clone())
4199            .with_panel(
4200                SCENE,
4201                DockPanelOptions::new("Scene").closable(true),
4202                panel("Scene body"),
4203            )
4204            .with_panel(VIEWPORT, "Viewport", panel("Viewport body"));
4205        let page = crate::Stack::vertical()
4206            .with_child(SizedBox::new().width(600.0).height(300.0))
4207            .with_child(SizedBox::new().width(600.0).height(500.0).child(workspace));
4208        let (mut runtime, window_id) = build_runtime(crate::ScrollView::vertical(page));
4209        resize(&mut runtime, window_id, 640.0, 400.0);
4210        let before = runtime.render(window_id).expect("initial frame");
4211
4212        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(300.0, 50.0));
4213        scroll.scroll_delta = Some(sui_core::ScrollDelta::Pixels(Vector::new(0.0, -120.0)));
4214        runtime
4215            .handle_event(window_id, Event::Pointer(scroll))
4216            .expect("page scrolls");
4217        let after = runtime.render(window_id).expect("scrolled frame");
4218
4219        let y = |frame: &sui_runtime::RenderOutput, name: &str| {
4220            named(&frame.semantics, name)
4221                .unwrap_or_else(|| panic!("{name} is present"))
4222                .bounds
4223                .y()
4224        };
4225        let scrolled = y(&after, "Scene body") - y(&before, "Scene body");
4226        assert!(scrolled < -50.0, "the page scrolled: {scrolled}");
4227        for name in [
4228            "Scene",
4229            "Close Scene",
4230            "Docked panel tabs",
4231            "Floating panel tabs",
4232            "Viewport body",
4233        ] {
4234            assert_eq!(
4235                y(&after, name) - y(&before, name),
4236                scrolled,
4237                "{name} moves with the page"
4238            );
4239        }
4240
4241        // The close button is hit where it is now shown.
4242        let close = named(&after.semantics, "Close Scene")
4243            .expect("close button")
4244            .bounds;
4245        for (kind, pressed) in [
4246            (PointerEventKind::Down, true),
4247            (PointerEventKind::Up, false),
4248        ] {
4249            runtime
4250                .handle_event(window_id, primary_pointer(kind, center(close), pressed))
4251                .expect("close press");
4252        }
4253        assert_eq!(state.snapshot().hidden, vec![SCENE]);
4254    }
4255
4256    #[test]
4257    fn floating_resize_drag_stops_at_the_panel_minimum_size() {
4258        let state = DockWorkspaceState::new(
4259            DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)).with_floating(
4260                DockFloatingGroup::new(
4261                    1,
4262                    [VIEWPORT],
4263                    VIEWPORT,
4264                    Rect::new(100.0, 100.0, 400.0, 400.0),
4265                ),
4266            ),
4267        )
4268        .expect("valid floating layout");
4269        let root = DockWorkspace::new(state.clone())
4270            .with_panel(SCENE, "Scene", panel("Scene"))
4271            .with_panel(
4272                VIEWPORT,
4273                DockPanelOptions::new("Viewport").min_size(Size::new(300.0, 200.0)),
4274                panel("Viewport"),
4275            );
4276        let header_height = root.header_height();
4277        let (mut runtime, window_id) = build_runtime(root);
4278        resize(&mut runtime, window_id, 800.0, 600.0);
4279        runtime.render(window_id).expect("initial frame");
4280
4281        let handle = Point::new(495.0, 495.0);
4282        let inward = Point::new(150.0, 150.0);
4283        for (kind, position, pressed) in [
4284            (PointerEventKind::Down, handle, true),
4285            (PointerEventKind::Move, inward, true),
4286            (PointerEventKind::Up, inward, false),
4287        ] {
4288            runtime
4289                .handle_event(window_id, primary_pointer(kind, position, pressed))
4290                .expect("resize gesture");
4291        }
4292
4293        assert_eq!(
4294            state.snapshot().floating[0].bounds,
4295            Rect::new(100.0, 100.0, 300.0, 200.0 + header_height)
4296        );
4297    }
4298
4299    #[test]
4300    fn registered_panel_validation_reports_unknown_snapshot_ids() {
4301        let state =
4302            DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)))
4303                .expect("valid state");
4304        let workspace =
4305            DockWorkspace::new(state.clone()).with_panel(SCENE, "Scene", panel("Scene"));
4306        let restored = DockWorkspaceSnapshot::new(DockNode::tabs([SCENE, VIEWPORT], SCENE));
4307        let error = workspace
4308            .apply_snapshot(restored.clone())
4309            .expect_err("viewport is not registered");
4310        assert!(error.to_string().contains("panel 2"));
4311        assert!(!node_contains_panel(&state.snapshot().root, VIEWPORT));
4312
4313        state
4314            .apply_snapshot(restored)
4315            .expect("state-only restore validates graph structure");
4316        assert!(workspace.validate_registered_panels().is_err());
4317    }
4318}