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 std::{
10    collections::{HashMap, HashSet},
11    fmt,
12};
13
14use sui_core::{
15    Event, KeyState, Point, PointerButton, PointerEventKind, Rect, SemanticsAction,
16    SemanticsActionRequest, SemanticsNode, SemanticsRole, SemanticsValue, Size, WidgetId,
17};
18use sui_layout::{Axis, Constraints};
19use sui_reactive::Signal;
20use sui_runtime::{
21    ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, SemanticsCtx, StackHostOptions, StackOrderPolicy,
22    Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
23};
24use sui_scene::StrokeStyle;
25
26use crate::{DefaultTheme, text_align::paint_single_line_aligned_text};
27
28const MAX_DOCK_DEPTH: usize = 64;
29const MAX_DOCK_NODES: usize = 4_096;
30const MAX_FLOATING_GROUPS: usize = 256;
31const MIN_SPLIT_FRACTION: f32 = 0.05;
32const MAX_SPLIT_FRACTION: f32 = 0.95;
33const DEFAULT_SPLITTER_THICKNESS: f32 = 4.0;
34const MIN_DOCK_PANE_EXTENT: f32 = 96.0;
35const MIN_FLOATING_WIDTH: f32 = 180.0;
36const MIN_FLOATING_HEIGHT: f32 = 120.0;
37const FLOATING_RESIZE_HANDLE: f32 = 16.0;
38const FLOATING_GRIP_WIDTH: f32 = 32.0;
39const TAB_DRAG_THRESHOLD: f32 = 5.0;
40const DROP_EDGE_FRACTION: f32 = 0.24;
41const DROP_ZONE_INSET: f32 = 6.0;
42const SEMANTIC_SPLIT_STEP: f32 = 0.05;
43
44/// Stable application-defined identity for one dockable panel.
45///
46/// Persist this value in application settings. It is deliberately independent
47/// from the runtime-generated [`WidgetId`]. Zero is reserved as an invalid ID.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub struct DockPanelId(u64);
50
51impl DockPanelId {
52    pub const fn new(raw: u64) -> Self {
53        Self(raw)
54    }
55
56    pub const fn get(self) -> u64 {
57        self.0
58    }
59
60    const fn is_valid(self) -> bool {
61        self.0 != 0
62    }
63}
64
65impl From<u64> for DockPanelId {
66    fn from(value: u64) -> Self {
67        Self::new(value)
68    }
69}
70
71impl From<DockPanelId> for u64 {
72    fn from(value: DockPanelId) -> Self {
73        value.get()
74    }
75}
76
77impl fmt::Display for DockPanelId {
78    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79        write!(formatter, "{}", self.0)
80    }
81}
82
83/// One node in the persisted docking graph.
84#[derive(Debug, Clone, PartialEq, Default)]
85pub enum DockNode {
86    #[default]
87    Empty,
88    Tabs {
89        panels: Vec<DockPanelId>,
90        active: DockPanelId,
91    },
92    Split {
93        axis: Axis,
94        fraction: f32,
95        first: Box<DockNode>,
96        second: Box<DockNode>,
97    },
98}
99
100impl DockNode {
101    pub const fn empty() -> Self {
102        Self::Empty
103    }
104
105    pub fn tabs(panels: impl IntoIterator<Item = DockPanelId>, active: DockPanelId) -> Self {
106        Self::Tabs {
107            panels: panels.into_iter().collect(),
108            active,
109        }
110    }
111
112    pub fn split(axis: Axis, fraction: f32, first: Self, second: Self) -> Self {
113        Self::Split {
114            axis,
115            fraction: normalize_fraction(fraction),
116            first: Box::new(first),
117            second: Box::new(second),
118        }
119    }
120
121    pub const fn is_empty(&self) -> bool {
122        matches!(self, Self::Empty)
123    }
124}
125
126/// A tab group floating above the docked graph inside the same SUI window.
127#[derive(Debug, Clone, PartialEq)]
128pub struct DockFloatingGroup {
129    pub id: u64,
130    pub panels: Vec<DockPanelId>,
131    pub active: DockPanelId,
132    pub bounds: Rect,
133}
134
135impl DockFloatingGroup {
136    pub fn new(
137        id: u64,
138        panels: impl IntoIterator<Item = DockPanelId>,
139        active: DockPanelId,
140        bounds: Rect,
141    ) -> Self {
142        Self {
143            id,
144            panels: panels.into_iter().collect(),
145            active,
146            bounds,
147        }
148    }
149}
150
151/// Plain persistence boundary for a docking workspace.
152///
153/// SUI does not prescribe a serializer or settings location. Applications may
154/// map this value into their own versioned settings format and later restore it
155/// through [`DockWorkspaceState::apply_snapshot`]. Floating groups are ordered
156/// back-to-front.
157#[derive(Debug, Clone, PartialEq, Default)]
158pub struct DockWorkspaceSnapshot {
159    pub root: DockNode,
160    pub floating: Vec<DockFloatingGroup>,
161    pub hidden: Vec<DockPanelId>,
162}
163
164impl DockWorkspaceSnapshot {
165    pub fn new(root: DockNode) -> Self {
166        Self {
167            root,
168            floating: Vec::new(),
169            hidden: Vec::new(),
170        }
171    }
172
173    pub fn with_floating(mut self, group: DockFloatingGroup) -> Self {
174        self.floating.push(group);
175        self
176    }
177
178    pub fn with_hidden(mut self, panel: DockPanelId) -> Self {
179        self.hidden.push(panel);
180        self
181    }
182}
183
184/// Destination zone used when docking a panel relative to a tab group or the
185/// workspace root.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum DockZone {
188    Center,
189    Left,
190    Right,
191    Top,
192    Bottom,
193}
194
195/// Validation or mutation failure for a docking layout.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct DockLayoutError {
198    message: String,
199}
200
201impl DockLayoutError {
202    fn new(message: impl Into<String>) -> Self {
203        Self {
204            message: message.into(),
205        }
206    }
207}
208
209impl fmt::Display for DockLayoutError {
210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211        formatter.write_str(&self.message)
212    }
213}
214
215impl std::error::Error for DockLayoutError {}
216
217/// Cloneable observable state for [`DockWorkspace`].
218#[derive(Clone, Debug)]
219pub struct DockWorkspaceState {
220    snapshot: Signal<DockWorkspaceSnapshot>,
221}
222
223impl DockWorkspaceState {
224    pub fn new(snapshot: DockWorkspaceSnapshot) -> Result<Self, DockLayoutError> {
225        validate_snapshot(&snapshot)?;
226        Ok(Self {
227            snapshot: Signal::named("Dock workspace state", snapshot),
228        })
229    }
230
231    pub fn empty() -> Self {
232        Self::new(DockWorkspaceSnapshot::default())
233            .expect("the empty dock workspace snapshot is valid")
234    }
235
236    pub fn snapshot(&self) -> DockWorkspaceSnapshot {
237        self.snapshot.get()
238    }
239
240    /// Applies a structurally valid dock graph.
241    ///
242    /// Panel widgets are registered by [`DockWorkspace`], not by this state
243    /// object, so this method cannot reject otherwise-valid snapshots that
244    /// reference an unregistered panel ID. Prefer
245    /// [`DockWorkspace::apply_snapshot`] when restoring application-owned
246    /// settings after the panel registry has been assembled.
247    pub fn apply_snapshot(&self, snapshot: DockWorkspaceSnapshot) -> Result<bool, DockLayoutError> {
248        validate_snapshot(&snapshot)?;
249        Ok(self.snapshot.set(snapshot))
250    }
251
252    pub fn dock(
253        &self,
254        panel: DockPanelId,
255        target: DockPanelId,
256        zone: DockZone,
257    ) -> Result<bool, DockLayoutError> {
258        validate_panel_id(panel)?;
259        validate_panel_id(target)?;
260        if panel == target {
261            return self.activate(panel);
262        }
263
264        self.mutate(|snapshot| {
265            if !visible_snapshot_contains_panel(snapshot, target) {
266                return Err(DockLayoutError::new(format!(
267                    "dock target panel {target} is not visible in the workspace"
268                )));
269            }
270            remove_panel_from_snapshot(snapshot, panel);
271
272            if dock_into_root_node(&mut snapshot.root, panel, target, zone) {
273                return Ok(());
274            }
275
276            let Some(group) = snapshot
277                .floating
278                .iter_mut()
279                .find(|group| group.panels.contains(&target))
280            else {
281                return Err(DockLayoutError::new(format!(
282                    "dock target panel {target} disappeared during mutation"
283                )));
284            };
285            if zone != DockZone::Center {
286                return Err(DockLayoutError::new(
287                    "floating tab groups accept center docking only",
288                ));
289            }
290            insert_tab(&mut group.panels, &mut group.active, panel);
291            Ok(())
292        })
293    }
294
295    pub fn dock_to_root(
296        &self,
297        panel: DockPanelId,
298        zone: DockZone,
299    ) -> Result<bool, DockLayoutError> {
300        validate_panel_id(panel)?;
301        self.mutate(|snapshot| {
302            remove_panel_from_snapshot(snapshot, panel);
303            let incoming = DockNode::tabs([panel], panel);
304            if snapshot.root.is_empty() {
305                snapshot.root = incoming;
306                return Ok(());
307            }
308
309            if zone == DockZone::Center {
310                if insert_into_first_tab_group(&mut snapshot.root, panel) {
311                    return Ok(());
312                }
313                snapshot.root = incoming;
314                return Ok(());
315            }
316
317            let previous = std::mem::take(&mut snapshot.root);
318            snapshot.root = split_for_zone(previous, incoming, zone);
319            Ok(())
320        })
321    }
322
323    pub fn float_panel(&self, panel: DockPanelId, bounds: Rect) -> Result<u64, DockLayoutError> {
324        validate_panel_id(panel)?;
325        validate_floating_bounds(bounds)?;
326        let mut assigned = 0;
327        self.mutate(|snapshot| {
328            remove_panel_from_snapshot(snapshot, panel);
329            assigned = next_floating_group_id(snapshot)?;
330            snapshot.floating.push(DockFloatingGroup::new(
331                assigned,
332                [panel],
333                panel,
334                normalized_floating_bounds(bounds),
335            ));
336            Ok(())
337        })?;
338        Ok(assigned)
339    }
340
341    pub fn hide(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
342        validate_panel_id(panel)?;
343        self.mutate(|snapshot| {
344            remove_panel_from_snapshot(snapshot, panel);
345            if !snapshot.hidden.contains(&panel) {
346                snapshot.hidden.push(panel);
347            }
348            Ok(())
349        })
350    }
351
352    pub fn show(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
353        validate_panel_id(panel)?;
354        self.mutate(|snapshot| {
355            snapshot.hidden.retain(|candidate| *candidate != panel);
356            if snapshot_contains_panel(snapshot, panel) {
357                activate_panel(snapshot, panel);
358            } else if !insert_into_first_tab_group(&mut snapshot.root, panel) {
359                snapshot.root = DockNode::tabs([panel], panel);
360            }
361            Ok(())
362        })
363    }
364
365    pub fn activate(&self, panel: DockPanelId) -> Result<bool, DockLayoutError> {
366        validate_panel_id(panel)?;
367        self.mutate(|snapshot| {
368            if !activate_panel(snapshot, panel) {
369                return Err(DockLayoutError::new(format!(
370                    "panel {panel} is not visible in the workspace"
371                )));
372            }
373            Ok(())
374        })
375    }
376
377    pub fn set_floating_bounds(
378        &self,
379        group_id: u64,
380        bounds: Rect,
381    ) -> Result<bool, DockLayoutError> {
382        validate_floating_bounds(bounds)?;
383        self.mutate(|snapshot| {
384            let Some(group) = snapshot
385                .floating
386                .iter_mut()
387                .find(|group| group.id == group_id)
388            else {
389                return Err(DockLayoutError::new(format!(
390                    "floating group {group_id} does not exist"
391                )));
392            };
393            group.bounds = normalized_floating_bounds(bounds);
394            Ok(())
395        })
396    }
397
398    pub fn bring_floating_to_front(&self, group_id: u64) -> Result<bool, DockLayoutError> {
399        self.mutate(|snapshot| {
400            let Some(index) = snapshot
401                .floating
402                .iter()
403                .position(|group| group.id == group_id)
404            else {
405                return Err(DockLayoutError::new(format!(
406                    "floating group {group_id} does not exist"
407                )));
408            };
409            if index + 1 != snapshot.floating.len() {
410                let group = snapshot.floating.remove(index);
411                snapshot.floating.push(group);
412            }
413            Ok(())
414        })
415    }
416
417    fn mutate(
418        &self,
419        mutate: impl FnOnce(&mut DockWorkspaceSnapshot) -> Result<(), DockLayoutError>,
420    ) -> Result<bool, DockLayoutError> {
421        let mut snapshot = self.snapshot();
422        let previous = snapshot.clone();
423        mutate(&mut snapshot)?;
424        validate_snapshot(&snapshot)?;
425        if snapshot == previous {
426            return Ok(false);
427        }
428        Ok(self.snapshot.set(snapshot))
429    }
430
431    fn set_split_fraction(
432        &self,
433        path: &[DockBranch],
434        fraction: f32,
435    ) -> Result<bool, DockLayoutError> {
436        self.mutate(|snapshot| {
437            let Some(node) = node_at_path_mut(&mut snapshot.root, path) else {
438                return Err(DockLayoutError::new("split path is no longer valid"));
439            };
440            let DockNode::Split {
441                fraction: current, ..
442            } = node
443            else {
444                return Err(DockLayoutError::new(
445                    "split path does not identify a split node",
446                ));
447            };
448            *current = normalize_fraction(fraction);
449            Ok(())
450        })
451    }
452}
453
454impl Default for DockWorkspaceState {
455    fn default() -> Self {
456        Self::empty()
457    }
458}
459
460fn validate_panel_id(panel: DockPanelId) -> Result<(), DockLayoutError> {
461    if panel.is_valid() {
462        Ok(())
463    } else {
464        Err(DockLayoutError::new("dock panel ID zero is reserved"))
465    }
466}
467
468fn validate_snapshot(snapshot: &DockWorkspaceSnapshot) -> Result<(), DockLayoutError> {
469    if snapshot.floating.len() > MAX_FLOATING_GROUPS {
470        return Err(DockLayoutError::new(format!(
471            "dock snapshot contains more than {MAX_FLOATING_GROUPS} floating groups"
472        )));
473    }
474
475    let mut panels = HashSet::new();
476    let mut node_count = 0;
477    validate_node(&snapshot.root, 0, &mut node_count, &mut panels)?;
478
479    let mut floating_ids = HashSet::new();
480    for group in &snapshot.floating {
481        if group.id == 0 || !floating_ids.insert(group.id) {
482            return Err(DockLayoutError::new(format!(
483                "floating group ID {} is zero or duplicated",
484                group.id
485            )));
486        }
487        if group.panels.is_empty() {
488            return Err(DockLayoutError::new(format!(
489                "floating group {} has no panels",
490                group.id
491            )));
492        }
493        if !group.panels.contains(&group.active) {
494            return Err(DockLayoutError::new(format!(
495                "floating group {} active panel {} is not a member",
496                group.id, group.active
497            )));
498        }
499        validate_floating_bounds(group.bounds)?;
500        for panel in &group.panels {
501            validate_panel_id(*panel)?;
502            if !panels.insert(*panel) {
503                return Err(DockLayoutError::new(format!(
504                    "panel {panel} appears more than once in the dock snapshot"
505                )));
506            }
507        }
508    }
509
510    for panel in &snapshot.hidden {
511        validate_panel_id(*panel)?;
512        if !panels.insert(*panel) {
513            return Err(DockLayoutError::new(format!(
514                "panel {panel} appears more than once in the dock snapshot"
515            )));
516        }
517    }
518    Ok(())
519}
520
521fn validate_node(
522    node: &DockNode,
523    depth: usize,
524    node_count: &mut usize,
525    panels: &mut HashSet<DockPanelId>,
526) -> Result<(), DockLayoutError> {
527    if depth > MAX_DOCK_DEPTH {
528        return Err(DockLayoutError::new(format!(
529            "dock graph exceeds maximum depth {MAX_DOCK_DEPTH}"
530        )));
531    }
532    *node_count += 1;
533    if *node_count > MAX_DOCK_NODES {
534        return Err(DockLayoutError::new(format!(
535            "dock graph exceeds maximum node count {MAX_DOCK_NODES}"
536        )));
537    }
538
539    match node {
540        DockNode::Empty => Ok(()),
541        DockNode::Tabs {
542            panels: members,
543            active,
544        } => {
545            if members.is_empty() {
546                return Err(DockLayoutError::new(
547                    "dock tab nodes must contain at least one panel",
548                ));
549            }
550            if !members.contains(active) {
551                return Err(DockLayoutError::new(format!(
552                    "active panel {active} is not a member of its dock tab node"
553                )));
554            }
555            for panel in members {
556                validate_panel_id(*panel)?;
557                if !panels.insert(*panel) {
558                    return Err(DockLayoutError::new(format!(
559                        "panel {panel} appears more than once in the dock snapshot"
560                    )));
561                }
562            }
563            Ok(())
564        }
565        DockNode::Split {
566            fraction,
567            first,
568            second,
569            ..
570        } => {
571            if !fraction.is_finite()
572                || *fraction < MIN_SPLIT_FRACTION
573                || *fraction > MAX_SPLIT_FRACTION
574            {
575                return Err(DockLayoutError::new(format!(
576                    "dock split fraction {fraction} is outside {MIN_SPLIT_FRACTION}..={MAX_SPLIT_FRACTION}"
577                )));
578            }
579            if first.is_empty() || second.is_empty() {
580                return Err(DockLayoutError::new(
581                    "dock split nodes cannot contain an empty branch",
582                ));
583            }
584            validate_node(first, depth + 1, node_count, panels)?;
585            validate_node(second, depth + 1, node_count, panels)
586        }
587    }
588}
589
590fn validate_floating_bounds(bounds: Rect) -> Result<(), DockLayoutError> {
591    if !bounds.x().is_finite()
592        || !bounds.y().is_finite()
593        || !bounds.width().is_finite()
594        || !bounds.height().is_finite()
595        || bounds.width() <= 0.0
596        || bounds.height() <= 0.0
597    {
598        return Err(DockLayoutError::new(
599            "floating bounds must have finite coordinates and positive finite size",
600        ));
601    }
602    Ok(())
603}
604
605fn normalized_floating_bounds(bounds: Rect) -> Rect {
606    Rect::new(
607        bounds.x(),
608        bounds.y(),
609        bounds.width().max(MIN_FLOATING_WIDTH),
610        bounds.height().max(MIN_FLOATING_HEIGHT),
611    )
612}
613
614fn normalize_fraction(fraction: f32) -> f32 {
615    if fraction.is_finite() {
616        fraction.clamp(MIN_SPLIT_FRACTION, MAX_SPLIT_FRACTION)
617    } else {
618        0.5
619    }
620}
621
622fn snapshot_contains_panel(snapshot: &DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
623    visible_snapshot_contains_panel(snapshot, panel) || snapshot.hidden.contains(&panel)
624}
625
626fn visible_snapshot_contains_panel(snapshot: &DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
627    node_contains_panel(&snapshot.root, panel)
628        || snapshot
629            .floating
630            .iter()
631            .any(|group| group.panels.contains(&panel))
632}
633
634fn node_contains_panel(node: &DockNode, panel: DockPanelId) -> bool {
635    match node {
636        DockNode::Empty => false,
637        DockNode::Tabs { panels, .. } => panels.contains(&panel),
638        DockNode::Split { first, second, .. } => {
639            node_contains_panel(first, panel) || node_contains_panel(second, panel)
640        }
641    }
642}
643
644fn remove_panel_from_snapshot(snapshot: &mut DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
645    let mut removed = remove_panel_from_node(&mut snapshot.root, panel);
646    for group in &mut snapshot.floating {
647        if let Some(index) = group
648            .panels
649            .iter()
650            .position(|candidate| *candidate == panel)
651        {
652            group.panels.remove(index);
653            if group.active == panel
654                && let Some(next) = group.panels.first().copied()
655            {
656                group.active = next;
657            }
658            removed = true;
659        }
660    }
661    snapshot.floating.retain(|group| !group.panels.is_empty());
662    let hidden_len = snapshot.hidden.len();
663    snapshot.hidden.retain(|candidate| *candidate != panel);
664    removed || snapshot.hidden.len() != hidden_len
665}
666
667fn remove_panel_from_node(node: &mut DockNode, panel: DockPanelId) -> bool {
668    match node {
669        DockNode::Empty => false,
670        DockNode::Tabs { panels, active } => {
671            let Some(index) = panels.iter().position(|candidate| *candidate == panel) else {
672                return false;
673            };
674            panels.remove(index);
675            if panels.is_empty() {
676                *node = DockNode::Empty;
677            } else if *active == panel {
678                *active = panels[index.min(panels.len() - 1)];
679            }
680            true
681        }
682        DockNode::Split { first, second, .. } => {
683            let removed =
684                remove_panel_from_node(first, panel) || remove_panel_from_node(second, panel);
685            if removed {
686                compact_split(node);
687            }
688            removed
689        }
690    }
691}
692
693fn compact_split(node: &mut DockNode) {
694    let replacement = match node {
695        DockNode::Split { first, second, .. } if first.is_empty() => {
696            Some(std::mem::take(second.as_mut()))
697        }
698        DockNode::Split { first, second, .. } if second.is_empty() => {
699            Some(std::mem::take(first.as_mut()))
700        }
701        _ => None,
702    };
703    if let Some(replacement) = replacement {
704        *node = replacement;
705    }
706}
707
708fn insert_tab(panels: &mut Vec<DockPanelId>, active: &mut DockPanelId, panel: DockPanelId) {
709    if !panels.contains(&panel) {
710        panels.push(panel);
711    }
712    *active = panel;
713}
714
715fn insert_into_first_tab_group(node: &mut DockNode, panel: DockPanelId) -> bool {
716    match node {
717        DockNode::Empty => false,
718        DockNode::Tabs { panels, active } => {
719            insert_tab(panels, active, panel);
720            true
721        }
722        DockNode::Split { first, second, .. } => {
723            insert_into_first_tab_group(first, panel) || insert_into_first_tab_group(second, panel)
724        }
725    }
726}
727
728fn dock_into_root_node(
729    node: &mut DockNode,
730    panel: DockPanelId,
731    target: DockPanelId,
732    zone: DockZone,
733) -> bool {
734    match node {
735        DockNode::Empty => false,
736        DockNode::Tabs { panels, active } if panels.contains(&target) => {
737            if zone == DockZone::Center {
738                insert_tab(panels, active, panel);
739            } else {
740                let previous = std::mem::take(node);
741                *node = split_for_zone(previous, DockNode::tabs([panel], panel), zone);
742            }
743            true
744        }
745        DockNode::Tabs { .. } => false,
746        DockNode::Split { first, second, .. } => {
747            dock_into_root_node(first, panel, target, zone)
748                || dock_into_root_node(second, panel, target, zone)
749        }
750    }
751}
752
753fn split_for_zone(existing: DockNode, incoming: DockNode, zone: DockZone) -> DockNode {
754    match zone {
755        DockZone::Left => DockNode::split(Axis::Horizontal, 0.28, incoming, existing),
756        DockZone::Right => DockNode::split(Axis::Horizontal, 0.72, existing, incoming),
757        DockZone::Top => DockNode::split(Axis::Vertical, 0.28, incoming, existing),
758        DockZone::Bottom => DockNode::split(Axis::Vertical, 0.72, existing, incoming),
759        DockZone::Center => existing,
760    }
761}
762
763fn activate_panel(snapshot: &mut DockWorkspaceSnapshot, panel: DockPanelId) -> bool {
764    if activate_in_node(&mut snapshot.root, panel) {
765        return true;
766    }
767    let Some(index) = snapshot
768        .floating
769        .iter()
770        .position(|group| group.panels.contains(&panel))
771    else {
772        return false;
773    };
774    snapshot.floating[index].active = panel;
775    if index + 1 != snapshot.floating.len() {
776        let group = snapshot.floating.remove(index);
777        snapshot.floating.push(group);
778    }
779    true
780}
781
782fn activate_in_node(node: &mut DockNode, panel: DockPanelId) -> bool {
783    match node {
784        DockNode::Empty => false,
785        DockNode::Tabs { panels, active } if panels.contains(&panel) => {
786            *active = panel;
787            true
788        }
789        DockNode::Tabs { .. } => false,
790        DockNode::Split { first, second, .. } => {
791            activate_in_node(first, panel) || activate_in_node(second, panel)
792        }
793    }
794}
795
796fn next_floating_group_id(snapshot: &DockWorkspaceSnapshot) -> Result<u64, DockLayoutError> {
797    snapshot
798        .floating
799        .iter()
800        .map(|group| group.id)
801        .max()
802        .unwrap_or(0)
803        .checked_add(1)
804        .filter(|id| *id != 0)
805        .ok_or_else(|| DockLayoutError::new("floating group ID space is exhausted"))
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809enum DockBranch {
810    First,
811    Second,
812}
813
814fn node_at_path_mut<'a>(
815    mut node: &'a mut DockNode,
816    path: &[DockBranch],
817) -> Option<&'a mut DockNode> {
818    for branch in path {
819        let DockNode::Split { first, second, .. } = node else {
820            return None;
821        };
822        node = match branch {
823            DockBranch::First => first,
824            DockBranch::Second => second,
825        };
826    }
827    Some(node)
828}
829
830fn node_at_path<'a>(mut node: &'a DockNode, path: &[DockBranch]) -> Option<&'a DockNode> {
831    for branch in path {
832        let DockNode::Split { first, second, .. } = node else {
833            return None;
834        };
835        node = match branch {
836            DockBranch::First => first,
837            DockBranch::Second => second,
838        };
839    }
840    Some(node)
841}
842
843struct DockPanelEntry {
844    id: DockPanelId,
845    title: String,
846    child: WidgetPod,
847}
848
849#[derive(Debug, Clone, PartialEq, Eq)]
850enum DockGroupLocation {
851    Docked(Vec<DockBranch>),
852    Floating(u64),
853}
854
855#[derive(Debug, Clone)]
856struct DockTabLayout {
857    panel: DockPanelId,
858    bounds: Rect,
859}
860
861#[derive(Debug, Clone)]
862struct DockGroupLayout {
863    location: DockGroupLocation,
864    bounds: Rect,
865    header: Rect,
866    content: Rect,
867    panels: Vec<DockPanelId>,
868    active: DockPanelId,
869    tabs: Vec<DockTabLayout>,
870}
871
872impl DockGroupLayout {
873    fn is_floating(&self) -> bool {
874        matches!(self.location, DockGroupLocation::Floating(_))
875    }
876
877    fn tab_at(&self, position: Point) -> Option<DockPanelId> {
878        self.tabs
879            .iter()
880            .find(|tab| tab.bounds.contains(position))
881            .map(|tab| tab.panel)
882    }
883}
884
885#[derive(Debug, Clone)]
886struct DockSplitterLayout {
887    path: Vec<DockBranch>,
888    axis: Axis,
889    fraction: f32,
890    bounds: Rect,
891    split_bounds: Rect,
892}
893
894#[derive(Debug, Clone, Default)]
895struct DockLayoutCache {
896    bounds: Rect,
897    groups: Vec<DockGroupLayout>,
898    splitters: Vec<DockSplitterLayout>,
899}
900
901impl DockLayoutCache {
902    fn visible_panel_ids(&self) -> impl Iterator<Item = DockPanelId> + '_ {
903        self.groups.iter().map(|group| group.active)
904    }
905
906    fn floating_groups_front_to_back(&self) -> impl Iterator<Item = &DockGroupLayout> {
907        self.groups.iter().rev().filter(|group| group.is_floating())
908    }
909}
910
911enum DockWorkspaceGesture {
912    TabPress {
913        pointer_id: u64,
914        panel: DockPanelId,
915        start_position: Point,
916        floating_size: Size,
917    },
918    TabDrag {
919        pointer_id: u64,
920        panel: DockPanelId,
921        position: Point,
922        floating_size: Size,
923        candidate: Option<DockDropCandidate>,
924    },
925    Split {
926        pointer_id: u64,
927        path: Vec<DockBranch>,
928        axis: Axis,
929        split_bounds: Rect,
930    },
931    FloatingMove {
932        pointer_id: u64,
933        group_id: u64,
934        pointer_origin: Point,
935        initial_bounds: Rect,
936    },
937    FloatingResize {
938        pointer_id: u64,
939        group_id: u64,
940        pointer_origin: Point,
941        initial_bounds: Rect,
942    },
943}
944
945impl DockWorkspaceGesture {
946    fn pointer_id(&self) -> u64 {
947        match self {
948            Self::TabPress { pointer_id, .. }
949            | Self::TabDrag { pointer_id, .. }
950            | Self::Split { pointer_id, .. }
951            | Self::FloatingMove { pointer_id, .. }
952            | Self::FloatingResize { pointer_id, .. } => *pointer_id,
953        }
954    }
955}
956
957#[derive(Debug, Clone)]
958struct DockDropCandidate {
959    target: Option<DockPanelId>,
960    zone: DockZone,
961    host_bounds: Rect,
962    zone_bounds: Rect,
963    center_only: bool,
964}
965
966type ThemeReader = std::rc::Rc<dyn Fn() -> DefaultTheme>;
967
968/// Retained editor workspace with a split/tab dock graph and same-window
969/// floating panels.
970///
971/// Every panel widget remains owned by this workspace for its full lifetime.
972/// State changes only alter which registered panel is measured, arranged, and
973/// visited at each logical location.
974pub struct DockWorkspace {
975    theme: Box<DefaultTheme>,
976    theme_reader: Option<ThemeReader>,
977    name: String,
978    state: DockWorkspaceState,
979    panels: Vec<DockPanelEntry>,
980    layout: DockLayoutCache,
981    gesture: Option<DockWorkspaceGesture>,
982    focused_group: Option<DockGroupLocation>,
983}
984
985impl DockWorkspace {
986    pub fn new(state: DockWorkspaceState) -> Self {
987        Self {
988            theme: Box::new(DefaultTheme::default()),
989            theme_reader: None,
990            name: "Dock workspace".to_string(),
991            state,
992            panels: Vec::new(),
993            layout: DockLayoutCache::default(),
994            gesture: None,
995            focused_group: None,
996        }
997    }
998
999    pub fn name(mut self, name: impl Into<String>) -> Self {
1000        self.name = name.into();
1001        self
1002    }
1003
1004    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1005        self.theme = Box::new(theme);
1006        self.theme_reader = None;
1007        self
1008    }
1009
1010    pub fn theme_when<F>(mut self, theme: F) -> Self
1011    where
1012        F: Fn() -> DefaultTheme + 'static,
1013    {
1014        self.theme_reader = Some(std::rc::Rc::new(theme));
1015        self
1016    }
1017
1018    pub fn with_panel<W>(mut self, id: DockPanelId, title: impl Into<String>, child: W) -> Self
1019    where
1020        W: Widget + 'static,
1021    {
1022        self.push_panel(id, title, child)
1023            .expect("dock panel registration must be valid and unique");
1024        self
1025    }
1026
1027    pub fn push_panel<W>(
1028        &mut self,
1029        id: DockPanelId,
1030        title: impl Into<String>,
1031        child: W,
1032    ) -> Result<(), DockLayoutError>
1033    where
1034        W: Widget + 'static,
1035    {
1036        validate_panel_id(id)?;
1037        if self.panels.iter().any(|panel| panel.id == id) {
1038            return Err(DockLayoutError::new(format!(
1039                "dock panel {id} is already registered"
1040            )));
1041        }
1042        self.panels.push(DockPanelEntry {
1043            id,
1044            title: title.into(),
1045            child: WidgetPod::new(child),
1046        });
1047        Ok(())
1048    }
1049
1050    pub fn state(&self) -> DockWorkspaceState {
1051        self.state.clone()
1052    }
1053
1054    pub fn panel_widget_id(&self, panel: DockPanelId) -> Option<WidgetId> {
1055        self.panel(panel).map(|entry| entry.child.id())
1056    }
1057
1058    pub fn validate_registered_panels(&self) -> Result<(), DockLayoutError> {
1059        self.validate_snapshot_panels(&self.state.snapshot())
1060    }
1061
1062    /// Validates that every panel referenced by `snapshot` has a widget in
1063    /// this workspace's stable registry.
1064    ///
1065    /// This complements the structural graph validation performed by
1066    /// [`DockWorkspaceState::apply_snapshot`].
1067    pub fn validate_snapshot_panels(
1068        &self,
1069        snapshot: &DockWorkspaceSnapshot,
1070    ) -> Result<(), DockLayoutError> {
1071        let registered = self
1072            .panels
1073            .iter()
1074            .map(|panel| panel.id)
1075            .collect::<HashSet<_>>();
1076        let mut referenced = HashSet::new();
1077        collect_snapshot_panels(snapshot, &mut referenced);
1078        if let Some(missing) = referenced
1079            .into_iter()
1080            .find(|panel| !registered.contains(panel))
1081        {
1082            return Err(DockLayoutError::new(format!(
1083                "dock snapshot references unregistered panel {missing}"
1084            )));
1085        }
1086        Ok(())
1087    }
1088
1089    /// Applies a restored snapshot only after validating both its graph and
1090    /// all panel IDs against this workspace's registry.
1091    pub fn apply_snapshot(&self, snapshot: DockWorkspaceSnapshot) -> Result<bool, DockLayoutError> {
1092        validate_snapshot(&snapshot)?;
1093        self.validate_snapshot_panels(&snapshot)?;
1094        self.state.apply_snapshot(snapshot)
1095    }
1096
1097    fn panel(&self, id: DockPanelId) -> Option<&DockPanelEntry> {
1098        self.panels.iter().find(|panel| panel.id == id)
1099    }
1100
1101    fn panel_mut(&mut self, id: DockPanelId) -> Option<&mut DockPanelEntry> {
1102        self.panels.iter_mut().find(|panel| panel.id == id)
1103    }
1104
1105    fn resolved_theme(&self) -> DefaultTheme {
1106        self.theme_reader
1107            .as_ref()
1108            .map(|reader| reader())
1109            .unwrap_or(*self.theme)
1110    }
1111
1112    fn title_map(&self) -> HashMap<DockPanelId, String> {
1113        self.panels
1114            .iter()
1115            .map(|panel| (panel.id, panel.title.clone()))
1116            .collect()
1117    }
1118
1119    fn rebuild_layout(&self, snapshot: &DockWorkspaceSnapshot, bounds: Rect) -> DockLayoutCache {
1120        build_workspace_layout(
1121            snapshot,
1122            bounds,
1123            self.resolved_theme().metrics.tab_height.max(22.0),
1124            DEFAULT_SPLITTER_THICKNESS,
1125            &self.title_map(),
1126        )
1127    }
1128
1129    fn begin_pointer_gesture(
1130        &mut self,
1131        ctx: &mut EventCtx,
1132        pointer_id: u64,
1133        position: Point,
1134    ) -> bool {
1135        for group in self.layout.floating_groups_front_to_back() {
1136            let DockGroupLocation::Floating(group_id) = group.location else {
1137                continue;
1138            };
1139            if !group.bounds.contains(position) {
1140                continue;
1141            }
1142
1143            if self
1144                .state
1145                .bring_floating_to_front(group_id)
1146                .unwrap_or(false)
1147            {
1148                ctx.request_ordering();
1149                ctx.request_hit_test();
1150                ctx.request_measure();
1151                ctx.request_paint();
1152                ctx.request_semantics();
1153            }
1154            if floating_resize_rect(group.bounds).contains(position) {
1155                self.gesture = Some(DockWorkspaceGesture::FloatingResize {
1156                    pointer_id,
1157                    group_id,
1158                    pointer_origin: position,
1159                    initial_bounds: group.bounds,
1160                });
1161                ctx.request_pointer_capture(pointer_id);
1162                return true;
1163            }
1164
1165            if let Some(panel) = group.tab_at(position) {
1166                let _ = self.state.activate(panel);
1167                self.focused_group = Some(group.location.clone());
1168                self.gesture = Some(DockWorkspaceGesture::TabPress {
1169                    pointer_id,
1170                    panel,
1171                    start_position: position,
1172                    floating_size: group.bounds.size,
1173                });
1174                ctx.request_focus();
1175                ctx.request_pointer_capture(pointer_id);
1176                ctx.request_measure();
1177                ctx.request_paint();
1178                ctx.request_semantics();
1179                return true;
1180            }
1181
1182            if group.header.contains(position) {
1183                self.gesture = Some(DockWorkspaceGesture::FloatingMove {
1184                    pointer_id,
1185                    group_id,
1186                    pointer_origin: position,
1187                    initial_bounds: group.bounds,
1188                });
1189                self.focused_group = Some(group.location.clone());
1190                ctx.request_focus();
1191                ctx.request_pointer_capture(pointer_id);
1192                return true;
1193            }
1194
1195            // Body presses front the floating group but remain available to
1196            // the active panel child.
1197            ctx.request_paint();
1198            return false;
1199        }
1200
1201        if let Some(splitter) = self
1202            .layout
1203            .splitters
1204            .iter()
1205            .find(|splitter| splitter.bounds.contains(position))
1206            .cloned()
1207        {
1208            self.gesture = Some(DockWorkspaceGesture::Split {
1209                pointer_id,
1210                path: splitter.path,
1211                axis: splitter.axis,
1212                split_bounds: splitter.split_bounds,
1213            });
1214            ctx.request_pointer_capture(pointer_id);
1215            return true;
1216        }
1217
1218        if let Some(group) = self
1219            .layout
1220            .groups
1221            .iter()
1222            .filter(|group| !group.is_floating())
1223            .find(|group| group.header.contains(position))
1224            && let Some(panel) = group.tab_at(position)
1225        {
1226            let location = group.location.clone();
1227            let floating_size = Size::new(320.0, 260.0);
1228            let _ = self.state.activate(panel);
1229            self.focused_group = Some(location);
1230            self.gesture = Some(DockWorkspaceGesture::TabPress {
1231                pointer_id,
1232                panel,
1233                start_position: position,
1234                floating_size,
1235            });
1236            ctx.request_focus();
1237            ctx.request_pointer_capture(pointer_id);
1238            ctx.request_measure();
1239            ctx.request_paint();
1240            ctx.request_semantics();
1241            return true;
1242        }
1243
1244        false
1245    }
1246
1247    fn drop_candidate_at(
1248        &self,
1249        position: Point,
1250        dragged_panel: DockPanelId,
1251    ) -> Option<DockDropCandidate> {
1252        for group in self.layout.floating_groups_front_to_back() {
1253            if !group.bounds.contains(position) {
1254                continue;
1255            }
1256            let target = group
1257                .panels
1258                .iter()
1259                .copied()
1260                .find(|panel| *panel != dragged_panel)
1261                .unwrap_or(group.active);
1262            let zone_bounds = inset_rect(group.bounds, DROP_ZONE_INSET);
1263            return Some(DockDropCandidate {
1264                target: Some(target),
1265                zone: DockZone::Center,
1266                host_bounds: group.bounds,
1267                zone_bounds,
1268                center_only: true,
1269            });
1270        }
1271
1272        for group in self
1273            .layout
1274            .groups
1275            .iter()
1276            .filter(|group| !group.is_floating())
1277        {
1278            if !group.bounds.contains(position) {
1279                continue;
1280            }
1281            let target = group
1282                .panels
1283                .iter()
1284                .copied()
1285                .find(|panel| *panel != dragged_panel)
1286                .unwrap_or(group.active);
1287            let zone = drop_zone_at(group.bounds, position);
1288            return Some(DockDropCandidate {
1289                target: Some(target),
1290                zone,
1291                host_bounds: group.bounds,
1292                zone_bounds: drop_zone_rect(group.bounds, zone),
1293                center_only: false,
1294            });
1295        }
1296
1297        if self.state.snapshot().root.is_empty()
1298            && !self.layout.groups.iter().any(|group| !group.is_floating())
1299        {
1300            let bounds = self.layout.bounds;
1301            if bounds.contains(position) {
1302                return Some(DockDropCandidate {
1303                    target: None,
1304                    zone: DockZone::Center,
1305                    host_bounds: bounds,
1306                    zone_bounds: inset_rect(bounds, DROP_ZONE_INSET),
1307                    center_only: true,
1308                });
1309            }
1310        }
1311        None
1312    }
1313
1314    fn update_pointer_gesture(&mut self, ctx: &mut EventCtx, position: Point) {
1315        let host_bounds = ctx.bounds();
1316        if let Some(DockWorkspaceGesture::TabPress {
1317            pointer_id,
1318            panel,
1319            start_position,
1320            floating_size,
1321        }) = &self.gesture
1322        {
1323            let distance = position - *start_position;
1324            if (distance.x * distance.x) + (distance.y * distance.y)
1325                >= TAB_DRAG_THRESHOLD * TAB_DRAG_THRESHOLD
1326            {
1327                let pointer_id = *pointer_id;
1328                let panel = *panel;
1329                let floating_size = *floating_size;
1330                let candidate = self.drop_candidate_at(position, panel);
1331                self.gesture = Some(DockWorkspaceGesture::TabDrag {
1332                    pointer_id,
1333                    panel,
1334                    position,
1335                    floating_size,
1336                    candidate,
1337                });
1338            }
1339        }
1340
1341        let dragged_panel = match &self.gesture {
1342            Some(DockWorkspaceGesture::TabDrag { panel, .. }) => Some(*panel),
1343            _ => None,
1344        };
1345        let next_candidate =
1346            dragged_panel.and_then(|panel| self.drop_candidate_at(position, panel));
1347        if let Some(DockWorkspaceGesture::TabDrag {
1348            position: current,
1349            candidate,
1350            ..
1351        }) = &mut self.gesture
1352        {
1353            *current = position;
1354            *candidate = next_candidate;
1355            ctx.request_paint();
1356            return;
1357        }
1358
1359        let Some(gesture) = &self.gesture else {
1360            return;
1361        };
1362        match gesture {
1363            DockWorkspaceGesture::TabPress { .. } | DockWorkspaceGesture::TabDrag { .. } => {}
1364            DockWorkspaceGesture::Split {
1365                path,
1366                axis,
1367                split_bounds,
1368                ..
1369            } => {
1370                let available = match axis {
1371                    Axis::Horizontal => split_bounds.width(),
1372                    Axis::Vertical => split_bounds.height(),
1373                }
1374                .max(1.0);
1375                let offset = match axis {
1376                    Axis::Horizontal => position.x - split_bounds.x(),
1377                    Axis::Vertical => position.y - split_bounds.y(),
1378                };
1379                let min_fraction =
1380                    (MIN_DOCK_PANE_EXTENT / available).clamp(MIN_SPLIT_FRACTION, 0.45);
1381                let fraction = (offset / available).clamp(min_fraction, 1.0 - min_fraction);
1382                let _ = self.state.set_split_fraction(path, fraction);
1383            }
1384            DockWorkspaceGesture::FloatingMove {
1385                group_id,
1386                pointer_origin,
1387                initial_bounds,
1388                ..
1389            } => {
1390                let delta = position - *pointer_origin;
1391                let proposed = initial_bounds.translate(delta);
1392                let _ = self
1393                    .state
1394                    .set_floating_bounds(*group_id, clamp_floating_bounds(host_bounds, proposed));
1395            }
1396            DockWorkspaceGesture::FloatingResize {
1397                group_id,
1398                pointer_origin,
1399                initial_bounds,
1400                ..
1401            } => {
1402                let delta = position - *pointer_origin;
1403                let proposed = Rect::new(
1404                    initial_bounds.x(),
1405                    initial_bounds.y(),
1406                    initial_bounds.width() + delta.x,
1407                    initial_bounds.height() + delta.y,
1408                );
1409                let _ = self
1410                    .state
1411                    .set_floating_bounds(*group_id, clamp_floating_bounds(host_bounds, proposed));
1412            }
1413        }
1414        ctx.request_measure();
1415        ctx.request_paint();
1416        ctx.request_semantics();
1417    }
1418
1419    fn finish_pointer_gesture(&mut self, ctx: &mut EventCtx, cancelled: bool) {
1420        let Some(gesture) = self.gesture.take() else {
1421            return;
1422        };
1423        if cancelled {
1424            ctx.request_paint();
1425            return;
1426        }
1427
1428        if let DockWorkspaceGesture::TabDrag {
1429            panel,
1430            position,
1431            floating_size,
1432            candidate,
1433            ..
1434        } = gesture
1435        {
1436            if let Some(candidate) = candidate {
1437                match candidate.target {
1438                    Some(target) if target != panel => {
1439                        let _ = self.state.dock(panel, target, candidate.zone);
1440                    }
1441                    Some(_) => {
1442                        let _ = self.state.activate(panel);
1443                    }
1444                    None => {
1445                        let _ = self.state.dock_to_root(panel, DockZone::Center);
1446                    }
1447                }
1448            } else {
1449                let bounds = clamp_floating_bounds(
1450                    ctx.bounds(),
1451                    Rect::new(
1452                        position.x - floating_size.width * 0.5,
1453                        position.y - 18.0,
1454                        floating_size.width,
1455                        floating_size.height,
1456                    ),
1457                );
1458                let _ = self.state.float_panel(panel, bounds);
1459            }
1460            self.focused_group = panel_location(&self.state.snapshot(), panel);
1461            ctx.request_ordering();
1462            ctx.request_hit_test();
1463            ctx.request_measure();
1464            ctx.request_semantics();
1465        }
1466        ctx.request_paint();
1467    }
1468
1469    fn activate_adjacent_tab(&mut self, delta: isize) -> bool {
1470        let Some(location) = self.focused_group.clone() else {
1471            return false;
1472        };
1473        let snapshot = self.state.snapshot();
1474        let Some((panels, active)) = group_members(&snapshot, &location) else {
1475            return false;
1476        };
1477        if panels.is_empty() {
1478            return false;
1479        }
1480        let current = panels
1481            .iter()
1482            .position(|panel| *panel == active)
1483            .unwrap_or(0) as isize;
1484        let next = (current + delta).rem_euclid(panels.len() as isize) as usize;
1485        self.state.activate(panels[next]).unwrap_or(false)
1486    }
1487}
1488
1489impl Widget for DockWorkspace {
1490    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1491        match event {
1492            Event::Pointer(pointer)
1493                if pointer.kind == PointerEventKind::Down
1494                    && pointer.button == Some(PointerButton::Primary) =>
1495            {
1496                if self.begin_pointer_gesture(ctx, pointer.pointer_id, pointer.position) {
1497                    ctx.set_handled();
1498                }
1499            }
1500            Event::Pointer(pointer)
1501                if pointer.kind == PointerEventKind::Move
1502                    && self
1503                        .gesture
1504                        .as_ref()
1505                        .is_some_and(|gesture| gesture.pointer_id() == pointer.pointer_id) =>
1506            {
1507                self.update_pointer_gesture(ctx, pointer.position);
1508                ctx.set_handled();
1509            }
1510            Event::Pointer(pointer)
1511                if matches!(
1512                    pointer.kind,
1513                    PointerEventKind::Up | PointerEventKind::Cancel
1514                ) && self
1515                    .gesture
1516                    .as_ref()
1517                    .is_some_and(|gesture| gesture.pointer_id() == pointer.pointer_id) =>
1518            {
1519                self.finish_pointer_gesture(ctx, pointer.kind == PointerEventKind::Cancel);
1520                ctx.release_pointer_capture(pointer.pointer_id);
1521                ctx.set_handled();
1522            }
1523            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1524                let handled = match key.key.as_str() {
1525                    "ArrowLeft" | "ArrowUp" => self.activate_adjacent_tab(-1),
1526                    "ArrowRight" | "ArrowDown" => self.activate_adjacent_tab(1),
1527                    _ => false,
1528                };
1529                if handled {
1530                    ctx.request_measure();
1531                    ctx.request_paint();
1532                    ctx.request_semantics();
1533                    ctx.set_handled();
1534                }
1535            }
1536            Event::Semantics(semantics) => {
1537                if matches!(
1538                    semantics.action,
1539                    SemanticsActionRequest::Activate | SemanticsActionRequest::Focus
1540                ) {
1541                    let panel = self.layout.groups.iter().find_map(|group| {
1542                        group.tabs.iter().find_map(|tab| {
1543                            (dock_tab_semantics_id(ctx.widget_id(), tab.panel) == semantics.target)
1544                                .then_some((tab.panel, group.location.clone()))
1545                        })
1546                    });
1547                    if let Some((panel, location)) = panel {
1548                        let _ = self.state.activate(panel);
1549                        self.focused_group = Some(location);
1550                        ctx.request_focus();
1551                        ctx.request_measure();
1552                        ctx.request_paint();
1553                        ctx.request_semantics();
1554                        ctx.set_handled();
1555                        return;
1556                    }
1557                }
1558
1559                let splitter_path = self.layout.splitters.iter().find_map(|splitter| {
1560                    (dock_splitter_semantics_id(ctx.widget_id(), &splitter.path)
1561                        == semantics.target)
1562                        .then(|| splitter.path.clone())
1563                });
1564                let Some(path) = splitter_path else {
1565                    return;
1566                };
1567                if matches!(semantics.action, SemanticsActionRequest::Focus) {
1568                    self.focused_group = None;
1569                    ctx.request_focus();
1570                    ctx.request_semantics();
1571                    ctx.set_handled();
1572                    return;
1573                }
1574
1575                let snapshot = self.state.snapshot();
1576                let Some(DockNode::Split { fraction, .. }) = node_at_path(&snapshot.root, &path)
1577                else {
1578                    return;
1579                };
1580                let current = f64::from(*fraction);
1581                let next = match &semantics.action {
1582                    SemanticsActionRequest::Increment => {
1583                        Some(current + f64::from(SEMANTIC_SPLIT_STEP))
1584                    }
1585                    SemanticsActionRequest::Decrement => {
1586                        Some(current - f64::from(SEMANTIC_SPLIT_STEP))
1587                    }
1588                    SemanticsActionRequest::SetValue(SemanticsValue::Number(value)) => Some(*value),
1589                    SemanticsActionRequest::SetValue(SemanticsValue::Range { value, .. }) => {
1590                        Some(*value)
1591                    }
1592                    _ => None,
1593                };
1594                let Some(next) = next.filter(|value| value.is_finite()) else {
1595                    return;
1596                };
1597                let next = next as f32;
1598                if !next.is_finite() {
1599                    return;
1600                }
1601                let _ = self.state.set_split_fraction(&path, next);
1602                ctx.request_measure();
1603                ctx.request_paint();
1604                ctx.request_semantics();
1605                ctx.set_handled();
1606            }
1607            _ => {}
1608        }
1609    }
1610
1611    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1612        let snapshot = ctx.observe(&self.state.snapshot);
1613        let width = if constraints.max.width.is_finite() {
1614            constraints.max.width
1615        } else {
1616            constraints.min.width.max(1_024.0)
1617        };
1618        let height = if constraints.max.height.is_finite() {
1619            constraints.max.height
1620        } else {
1621            constraints.min.height.max(720.0)
1622        };
1623        let size = constraints.clamp(Size::new(width, height));
1624        self.layout = self.rebuild_layout(&snapshot, Rect::from_origin_size(Point::ZERO, size));
1625
1626        let active = self.layout.visible_panel_ids().collect::<Vec<_>>();
1627        for panel_id in active {
1628            let bounds = self
1629                .layout
1630                .groups
1631                .iter()
1632                .find(|group| group.active == panel_id)
1633                .map(|group| group.content)
1634                .unwrap_or(Rect::ZERO);
1635            if let Some(panel) = self.panel_mut(panel_id) {
1636                panel.child.measure(ctx, Constraints::tight(bounds.size));
1637            }
1638        }
1639        size
1640    }
1641
1642    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1643        self.layout = self.rebuild_layout(&self.state.snapshot(), bounds);
1644        let placements = self
1645            .layout
1646            .groups
1647            .iter()
1648            .map(|group| (group.active, group.content))
1649            .collect::<Vec<_>>();
1650        for (panel_id, panel_bounds) in placements {
1651            if let Some(panel) = self.panel_mut(panel_id) {
1652                panel.child.arrange(ctx, panel_bounds);
1653            }
1654        }
1655    }
1656
1657    fn paint(&self, ctx: &mut PaintCtx) {
1658        let theme = self.resolved_theme();
1659        ctx.fill_bounds(theme.palette.surface);
1660
1661        for group in self
1662            .layout
1663            .groups
1664            .iter()
1665            .filter(|group| !group.is_floating())
1666        {
1667            self.paint_group(ctx, group, &theme);
1668        }
1669        for splitter in &self.layout.splitters {
1670            ctx.fill_rect(splitter.bounds, theme.palette.border.with_alpha(0.88));
1671        }
1672        for group in self
1673            .layout
1674            .groups
1675            .iter()
1676            .filter(|group| group.is_floating())
1677        {
1678            self.paint_group(ctx, group, &theme);
1679        }
1680        if let Some(DockWorkspaceGesture::TabDrag {
1681            panel,
1682            position,
1683            candidate,
1684            ..
1685        }) = &self.gesture
1686        {
1687            if let Some(candidate) = candidate {
1688                paint_drop_targets(ctx, candidate, &theme);
1689            }
1690            self.paint_drag_preview(ctx, *panel, *position, &theme);
1691        }
1692    }
1693
1694    fn semantics(&self, ctx: &mut SemanticsCtx) {
1695        let mut workspace = SemanticsNode::new(
1696            ctx.widget_id(),
1697            SemanticsRole::GenericContainer,
1698            ctx.bounds(),
1699        );
1700        workspace.name = Some(self.name.clone());
1701        workspace.state.focused = ctx.is_focused();
1702        workspace.actions = vec![SemanticsAction::Focus];
1703        ctx.push(workspace);
1704
1705        for group in &self.layout.groups {
1706            let group_id = dock_group_semantics_id(ctx.widget_id(), &group.location);
1707            let mut tabs = SemanticsNode::new(group_id, SemanticsRole::TabBar, group.header);
1708            tabs.parent = Some(ctx.widget_id());
1709            tabs.name = Some(if group.is_floating() {
1710                "Floating panel tabs".to_string()
1711            } else {
1712                "Docked panel tabs".to_string()
1713            });
1714            tabs.value = self
1715                .panel(group.active)
1716                .map(|panel| SemanticsValue::Text(panel.title.clone()));
1717            ctx.push(tabs);
1718            for tab in &group.tabs {
1719                let mut node = SemanticsNode::new(
1720                    dock_tab_semantics_id(ctx.widget_id(), tab.panel),
1721                    SemanticsRole::Button,
1722                    tab.bounds,
1723                );
1724                node.parent = Some(group_id);
1725                node.name = self.panel(tab.panel).map(|panel| panel.title.clone());
1726                node.state.selected = tab.panel == group.active;
1727                node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
1728                ctx.push(node);
1729            }
1730            if let Some(panel) = self.panel(group.active) {
1731                panel.child.semantics(ctx);
1732            }
1733        }
1734
1735        for splitter in &self.layout.splitters {
1736            let mut node = SemanticsNode::new(
1737                dock_splitter_semantics_id(ctx.widget_id(), &splitter.path),
1738                SemanticsRole::Splitter,
1739                splitter.bounds,
1740            );
1741            node.parent = Some(ctx.widget_id());
1742            node.name = Some("Dock divider".to_string());
1743            node.value = Some(SemanticsValue::Range {
1744                value: f64::from(splitter.fraction),
1745                min: f64::from(MIN_SPLIT_FRACTION),
1746                max: f64::from(MAX_SPLIT_FRACTION),
1747            });
1748            node.actions = vec![
1749                SemanticsAction::Focus,
1750                SemanticsAction::Increment,
1751                SemanticsAction::Decrement,
1752                SemanticsAction::SetValue,
1753            ];
1754            ctx.push(node);
1755        }
1756    }
1757
1758    fn accepts_focus(&self) -> bool {
1759        true
1760    }
1761
1762    fn stack_host_options(&self) -> Option<StackHostOptions> {
1763        Some(StackHostOptions {
1764            order_policy: StackOrderPolicy::FocusFronted,
1765        })
1766    }
1767
1768    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1769        for panel_id in self.layout.visible_panel_ids() {
1770            if let Some(panel) = self.panel(panel_id) {
1771                visitor.visit(&panel.child);
1772            }
1773        }
1774    }
1775
1776    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1777        let visible = self.layout.visible_panel_ids().collect::<Vec<_>>();
1778        for panel_id in visible {
1779            if let Some(panel) = self.panel_mut(panel_id) {
1780                visitor.visit(&mut panel.child);
1781            }
1782        }
1783    }
1784}
1785
1786impl DockWorkspace {
1787    fn paint_group(&self, ctx: &mut PaintCtx, group: &DockGroupLayout, theme: &DefaultTheme) {
1788        let palette = theme.palette;
1789        ctx.fill_rect(group.bounds, palette.surface_raised);
1790        ctx.push_clip_rect(group.content);
1791        if let Some(panel) = self.panel(group.active) {
1792            panel.child.paint(ctx);
1793        }
1794        ctx.pop_clip();
1795
1796        ctx.fill_rect(group.header, palette.control);
1797        for tab in &group.tabs {
1798            let selected = tab.panel == group.active;
1799            if selected {
1800                ctx.fill_rect(tab.bounds, palette.control_active);
1801                ctx.fill_rect(
1802                    Rect::new(
1803                        tab.bounds.x(),
1804                        tab.bounds.max_y() - 2.0,
1805                        tab.bounds.width(),
1806                        2.0,
1807                    ),
1808                    palette.accent,
1809                );
1810            }
1811            let label = self
1812                .panel(tab.panel)
1813                .map(|panel| panel.title.as_str())
1814                .unwrap_or("Missing panel");
1815            let style = theme.text_style(if selected {
1816                palette.text
1817            } else {
1818                palette.text_muted
1819            });
1820            let text_rect = tab.bounds.inflate(-8.0, -2.0);
1821            ctx.push_clip_rect(text_rect);
1822            paint_single_line_aligned_text(ctx, text_rect, label, &style, style.line_height, 0.0);
1823            ctx.pop_clip();
1824        }
1825
1826        if group.is_floating() {
1827            ctx.stroke_rect(group.bounds, palette.border, StrokeStyle::new(1.0));
1828            let handle = floating_resize_rect(group.bounds);
1829            ctx.fill_rect(handle, palette.border.with_alpha(0.72));
1830            ctx.fill_rect(
1831                Rect::new(
1832                    group.header.max_x() - FLOATING_GRIP_WIDTH,
1833                    group.header.y(),
1834                    FLOATING_GRIP_WIDTH,
1835                    group.header.height(),
1836                ),
1837                palette.control_hover.with_alpha(0.34),
1838            );
1839        }
1840    }
1841
1842    fn paint_drag_preview(
1843        &self,
1844        ctx: &mut PaintCtx,
1845        panel: DockPanelId,
1846        position: Point,
1847        theme: &DefaultTheme,
1848    ) {
1849        let width = 168.0;
1850        let height = theme.metrics.tab_height.max(26.0);
1851        let max_x = (ctx.bounds().max_x() - width).max(ctx.bounds().x());
1852        let max_y = (ctx.bounds().max_y() - height).max(ctx.bounds().y());
1853        let bounds = Rect::new(
1854            (position.x + 12.0).clamp(ctx.bounds().x(), max_x),
1855            (position.y + 12.0).clamp(ctx.bounds().y(), max_y),
1856            width,
1857            height,
1858        );
1859        ctx.fill_rect(bounds, theme.palette.surface_raised.with_alpha(0.96));
1860        ctx.stroke_rect(bounds, theme.palette.accent, StrokeStyle::new(1.5));
1861        let text = self
1862            .panel(panel)
1863            .map(|entry| entry.title.as_str())
1864            .unwrap_or("Panel");
1865        let style = theme.text_style(theme.palette.text);
1866        let text_bounds = inset_rect(bounds, 8.0);
1867        ctx.push_clip_rect(text_bounds);
1868        paint_single_line_aligned_text(ctx, text_bounds, text, &style, style.line_height, 0.0);
1869        ctx.pop_clip();
1870    }
1871}
1872
1873fn inset_rect(bounds: Rect, amount: f32) -> Rect {
1874    let amount = amount.max(0.0);
1875    let horizontal = amount.min(bounds.width() * 0.5);
1876    let vertical = amount.min(bounds.height() * 0.5);
1877    Rect::new(
1878        bounds.x() + horizontal,
1879        bounds.y() + vertical,
1880        (bounds.width() - horizontal * 2.0).max(0.0),
1881        (bounds.height() - vertical * 2.0).max(0.0),
1882    )
1883}
1884
1885fn drop_zone_at(bounds: Rect, position: Point) -> DockZone {
1886    let edge_x = bounds.width() * DROP_EDGE_FRACTION;
1887    let edge_y = bounds.height() * DROP_EDGE_FRACTION;
1888    let horizontal_distance = (position.x - bounds.x()).min(bounds.max_x() - position.x);
1889    let vertical_distance = (position.y - bounds.y()).min(bounds.max_y() - position.y);
1890    let center_x = bounds.x() + bounds.width() * 0.5;
1891    let center_y = bounds.y() + bounds.height() * 0.5;
1892
1893    if horizontal_distance < edge_x && horizontal_distance <= vertical_distance {
1894        if position.x < center_x {
1895            DockZone::Left
1896        } else {
1897            DockZone::Right
1898        }
1899    } else if vertical_distance < edge_y {
1900        if position.y < center_y {
1901            DockZone::Top
1902        } else {
1903            DockZone::Bottom
1904        }
1905    } else {
1906        DockZone::Center
1907    }
1908}
1909
1910fn drop_zone_rect(bounds: Rect, zone: DockZone) -> Rect {
1911    let bounds = inset_rect(bounds, DROP_ZONE_INSET);
1912    let edge_width = bounds.width() * DROP_EDGE_FRACTION;
1913    let edge_height = bounds.height() * DROP_EDGE_FRACTION;
1914
1915    match zone {
1916        DockZone::Left => Rect::new(bounds.x(), bounds.y(), edge_width, bounds.height()),
1917        DockZone::Right => Rect::new(
1918            bounds.max_x() - edge_width,
1919            bounds.y(),
1920            edge_width,
1921            bounds.height(),
1922        ),
1923        DockZone::Top => Rect::new(bounds.x(), bounds.y(), bounds.width(), edge_height),
1924        DockZone::Bottom => Rect::new(
1925            bounds.x(),
1926            bounds.max_y() - edge_height,
1927            bounds.width(),
1928            edge_height,
1929        ),
1930        DockZone::Center => Rect::new(
1931            bounds.x() + edge_width,
1932            bounds.y() + edge_height,
1933            (bounds.width() - edge_width * 2.0).max(0.0),
1934            (bounds.height() - edge_height * 2.0).max(0.0),
1935        ),
1936    }
1937}
1938
1939fn paint_drop_targets(ctx: &mut PaintCtx, candidate: &DockDropCandidate, theme: &DefaultTheme) {
1940    const ALL_ZONES: [DockZone; 5] = [
1941        DockZone::Left,
1942        DockZone::Right,
1943        DockZone::Top,
1944        DockZone::Bottom,
1945        DockZone::Center,
1946    ];
1947    const CENTER_ZONE: [DockZone; 1] = [DockZone::Center];
1948    let zones = if candidate.center_only {
1949        &CENTER_ZONE[..]
1950    } else {
1951        &ALL_ZONES[..]
1952    };
1953
1954    for zone in zones {
1955        let bounds = if *zone == candidate.zone {
1956            candidate.zone_bounds
1957        } else {
1958            drop_zone_rect(candidate.host_bounds, *zone)
1959        };
1960        let selected = *zone == candidate.zone;
1961        ctx.fill_rect(
1962            bounds,
1963            if selected {
1964                theme.palette.accent.with_alpha(0.30)
1965            } else {
1966                theme.palette.control_active.with_alpha(0.20)
1967            },
1968        );
1969        ctx.stroke_rect(
1970            bounds,
1971            if selected {
1972                theme.palette.accent
1973            } else {
1974                theme.palette.border_focus.with_alpha(0.72)
1975            },
1976            StrokeStyle::new(if selected { 2.0 } else { 1.0 }),
1977        );
1978    }
1979}
1980
1981fn collect_snapshot_panels(snapshot: &DockWorkspaceSnapshot, output: &mut HashSet<DockPanelId>) {
1982    collect_node_panels(&snapshot.root, output);
1983    for group in &snapshot.floating {
1984        output.extend(group.panels.iter().copied());
1985    }
1986    output.extend(snapshot.hidden.iter().copied());
1987}
1988
1989fn collect_node_panels(node: &DockNode, output: &mut HashSet<DockPanelId>) {
1990    match node {
1991        DockNode::Empty => {}
1992        DockNode::Tabs { panels, .. } => output.extend(panels.iter().copied()),
1993        DockNode::Split { first, second, .. } => {
1994            collect_node_panels(first, output);
1995            collect_node_panels(second, output);
1996        }
1997    }
1998}
1999
2000fn build_workspace_layout(
2001    snapshot: &DockWorkspaceSnapshot,
2002    bounds: Rect,
2003    header_height: f32,
2004    splitter_thickness: f32,
2005    titles: &HashMap<DockPanelId, String>,
2006) -> DockLayoutCache {
2007    let mut layout = DockLayoutCache {
2008        bounds,
2009        ..DockLayoutCache::default()
2010    };
2011    let mut path = Vec::new();
2012    layout_dock_node(
2013        &snapshot.root,
2014        bounds,
2015        header_height,
2016        splitter_thickness,
2017        titles,
2018        &mut path,
2019        &mut layout,
2020    );
2021
2022    for floating in &snapshot.floating {
2023        let resolved = clamp_floating_bounds(bounds, floating.bounds);
2024        layout.groups.push(make_group_layout(
2025            DockGroupLocation::Floating(floating.id),
2026            resolved,
2027            header_height,
2028            &floating.panels,
2029            floating.active,
2030            titles,
2031            true,
2032        ));
2033    }
2034    layout
2035}
2036
2037#[allow(clippy::too_many_arguments)]
2038fn layout_dock_node(
2039    node: &DockNode,
2040    bounds: Rect,
2041    header_height: f32,
2042    splitter_thickness: f32,
2043    titles: &HashMap<DockPanelId, String>,
2044    path: &mut Vec<DockBranch>,
2045    layout: &mut DockLayoutCache,
2046) {
2047    match node {
2048        DockNode::Empty => {}
2049        DockNode::Tabs { panels, active } => layout.groups.push(make_group_layout(
2050            DockGroupLocation::Docked(path.clone()),
2051            bounds,
2052            header_height,
2053            panels,
2054            *active,
2055            titles,
2056            false,
2057        )),
2058        DockNode::Split {
2059            axis,
2060            fraction,
2061            first,
2062            second,
2063        } => {
2064            let total = axis_extent(*axis, bounds.size);
2065            let divider = splitter_thickness.min(total).max(0.0);
2066            let available = (total - divider).max(0.0);
2067            let minimum = MIN_DOCK_PANE_EXTENT.min(available * 0.45);
2068            let first_extent =
2069                (available * *fraction).clamp(minimum, (available - minimum).max(minimum));
2070            let second_extent = (available - first_extent).max(0.0);
2071            let first_bounds = axis_rect(*axis, bounds, 0.0, first_extent);
2072            let splitter_bounds = axis_rect(*axis, bounds, first_extent, divider);
2073            let second_bounds = axis_rect(*axis, bounds, first_extent + divider, second_extent);
2074            layout.splitters.push(DockSplitterLayout {
2075                path: path.clone(),
2076                axis: *axis,
2077                fraction: *fraction,
2078                bounds: splitter_bounds,
2079                split_bounds: bounds,
2080            });
2081            path.push(DockBranch::First);
2082            layout_dock_node(
2083                first,
2084                first_bounds,
2085                header_height,
2086                splitter_thickness,
2087                titles,
2088                path,
2089                layout,
2090            );
2091            path.pop();
2092            path.push(DockBranch::Second);
2093            layout_dock_node(
2094                second,
2095                second_bounds,
2096                header_height,
2097                splitter_thickness,
2098                titles,
2099                path,
2100                layout,
2101            );
2102            path.pop();
2103        }
2104    }
2105}
2106
2107fn make_group_layout(
2108    location: DockGroupLocation,
2109    bounds: Rect,
2110    header_height: f32,
2111    panels: &[DockPanelId],
2112    active: DockPanelId,
2113    titles: &HashMap<DockPanelId, String>,
2114    floating: bool,
2115) -> DockGroupLayout {
2116    let header_height = header_height.min(bounds.height()).max(0.0);
2117    let header = Rect::new(bounds.x(), bounds.y(), bounds.width(), header_height);
2118    let content = Rect::new(
2119        bounds.x(),
2120        bounds.y() + header_height,
2121        bounds.width(),
2122        (bounds.height() - header_height).max(0.0),
2123    );
2124    let tab_area = if floating {
2125        Rect::new(
2126            header.x(),
2127            header.y(),
2128            (header.width() - FLOATING_GRIP_WIDTH).max(0.0),
2129            header.height(),
2130        )
2131    } else {
2132        header
2133    };
2134    let tabs = tab_rects(tab_area, panels, titles);
2135    DockGroupLayout {
2136        location,
2137        bounds,
2138        header,
2139        content,
2140        panels: panels.to_vec(),
2141        active,
2142        tabs,
2143    }
2144}
2145
2146fn tab_rects(
2147    bounds: Rect,
2148    panels: &[DockPanelId],
2149    titles: &HashMap<DockPanelId, String>,
2150) -> Vec<DockTabLayout> {
2151    if panels.is_empty() || bounds.width() <= 0.0 {
2152        return Vec::new();
2153    }
2154    let natural = panels
2155        .iter()
2156        .map(|panel| {
2157            let characters = titles.get(panel).map_or(12, |title| title.chars().count());
2158            (characters as f32 * 7.0 + 28.0).clamp(72.0, 180.0)
2159        })
2160        .collect::<Vec<_>>();
2161    let total = natural.iter().sum::<f32>();
2162    let scale = if total > bounds.width() {
2163        bounds.width() / total
2164    } else {
2165        1.0
2166    };
2167    let mut x = bounds.x();
2168    natural
2169        .into_iter()
2170        .zip(panels.iter().copied())
2171        .map(|(width, panel)| {
2172            let width = (width * scale).max(0.0).min(bounds.max_x() - x);
2173            let tab = DockTabLayout {
2174                panel,
2175                bounds: Rect::new(x, bounds.y(), width, bounds.height()),
2176            };
2177            x += width;
2178            tab
2179        })
2180        .collect()
2181}
2182
2183fn axis_extent(axis: Axis, size: Size) -> f32 {
2184    match axis {
2185        Axis::Horizontal => size.width,
2186        Axis::Vertical => size.height,
2187    }
2188}
2189
2190fn axis_rect(axis: Axis, bounds: Rect, offset: f32, extent: f32) -> Rect {
2191    match axis {
2192        Axis::Horizontal => Rect::new(
2193            bounds.x() + offset,
2194            bounds.y(),
2195            extent.max(0.0),
2196            bounds.height(),
2197        ),
2198        Axis::Vertical => Rect::new(
2199            bounds.x(),
2200            bounds.y() + offset,
2201            bounds.width(),
2202            extent.max(0.0),
2203        ),
2204    }
2205}
2206
2207fn floating_resize_rect(bounds: Rect) -> Rect {
2208    Rect::new(
2209        bounds.max_x() - FLOATING_RESIZE_HANDLE,
2210        bounds.max_y() - FLOATING_RESIZE_HANDLE,
2211        FLOATING_RESIZE_HANDLE,
2212        FLOATING_RESIZE_HANDLE,
2213    )
2214}
2215
2216fn clamp_floating_bounds(host: Rect, proposed: Rect) -> Rect {
2217    let host_width = host.width().max(0.0);
2218    let host_height = host.height().max(0.0);
2219    let width = proposed
2220        .width()
2221        .max(MIN_FLOATING_WIDTH.min(host_width))
2222        .min(host_width);
2223    let height = proposed
2224        .height()
2225        .max(MIN_FLOATING_HEIGHT.min(host_height))
2226        .min(host_height);
2227    let min_x = host.x();
2228    let min_y = host.y();
2229    let max_x = (host.max_x() - width).max(min_x);
2230    let max_y = (host.max_y() - height).max(min_y);
2231    Rect::new(
2232        proposed.x().clamp(min_x, max_x),
2233        proposed.y().clamp(min_y, max_y),
2234        width,
2235        height,
2236    )
2237}
2238
2239fn group_members(
2240    snapshot: &DockWorkspaceSnapshot,
2241    location: &DockGroupLocation,
2242) -> Option<(Vec<DockPanelId>, DockPanelId)> {
2243    match location {
2244        DockGroupLocation::Docked(path) => {
2245            let DockNode::Tabs { panels, active } = node_at_path(&snapshot.root, path)? else {
2246                return None;
2247            };
2248            Some((panels.clone(), *active))
2249        }
2250        DockGroupLocation::Floating(id) => snapshot
2251            .floating
2252            .iter()
2253            .find(|group| group.id == *id)
2254            .map(|group| (group.panels.clone(), group.active)),
2255    }
2256}
2257
2258fn panel_location(
2259    snapshot: &DockWorkspaceSnapshot,
2260    panel: DockPanelId,
2261) -> Option<DockGroupLocation> {
2262    let mut path = Vec::new();
2263    if find_panel_path(&snapshot.root, panel, &mut path) {
2264        return Some(DockGroupLocation::Docked(path));
2265    }
2266    snapshot
2267        .floating
2268        .iter()
2269        .find(|group| group.panels.contains(&panel))
2270        .map(|group| DockGroupLocation::Floating(group.id))
2271}
2272
2273fn find_panel_path(node: &DockNode, panel: DockPanelId, path: &mut Vec<DockBranch>) -> bool {
2274    match node {
2275        DockNode::Empty => false,
2276        DockNode::Tabs { panels, .. } => panels.contains(&panel),
2277        DockNode::Split { first, second, .. } => {
2278            path.push(DockBranch::First);
2279            if find_panel_path(first, panel, path) {
2280                return true;
2281            }
2282            path.pop();
2283            path.push(DockBranch::Second);
2284            if find_panel_path(second, panel, path) {
2285                return true;
2286            }
2287            path.pop();
2288            false
2289        }
2290    }
2291}
2292
2293fn dock_tab_semantics_id(parent: WidgetId, panel: DockPanelId) -> WidgetId {
2294    const TAG: u64 = 5_u64 << 50;
2295    const LOW_MASK: u64 = (1_u64 << 50) - 1;
2296    WidgetId::new(
2297        TAG | (parent
2298            .get()
2299            .wrapping_mul(421)
2300            .wrapping_add(panel.get().wrapping_mul(17))
2301            & LOW_MASK),
2302    )
2303}
2304
2305fn dock_group_semantics_id(parent: WidgetId, location: &DockGroupLocation) -> WidgetId {
2306    const TAG: u64 = 6_u64 << 50;
2307    const LOW_MASK: u64 = (1_u64 << 50) - 1;
2308    let location_hash = match location {
2309        DockGroupLocation::Docked(path) => path.iter().fold(1_u64, |hash, branch| {
2310            hash.wrapping_mul(31).wrapping_add(match branch {
2311                DockBranch::First => 1,
2312                DockBranch::Second => 2,
2313            })
2314        }),
2315        DockGroupLocation::Floating(id) => id.wrapping_mul(97).wrapping_add(3),
2316    };
2317    WidgetId::new(TAG | (parent.get().wrapping_mul(433).wrapping_add(location_hash) & LOW_MASK))
2318}
2319
2320fn dock_splitter_semantics_id(parent: WidgetId, path: &[DockBranch]) -> WidgetId {
2321    const TAG: u64 = 7_u64 << 50;
2322    const LOW_MASK: u64 = (1_u64 << 50) - 1;
2323    let path_hash = path.iter().fold(1_u64, |hash, branch| {
2324        hash.wrapping_mul(37).wrapping_add(match branch {
2325            DockBranch::First => 1,
2326            DockBranch::Second => 2,
2327        })
2328    });
2329    WidgetId::new(TAG | (parent.get().wrapping_mul(439).wrapping_add(path_hash) & LOW_MASK))
2330}
2331
2332#[cfg(test)]
2333mod tests {
2334    use super::*;
2335    use crate::{Label, SizedBox};
2336    use sui_core::{
2337        Event, KeyboardEvent, Modifiers, PointerButtons, PointerEvent, PointerKind, Vector,
2338        WindowEvent,
2339    };
2340    use sui_runtime::{Application, Runtime, WindowBuilder};
2341    use sui_scene::SceneCommand;
2342
2343    const SCENE: DockPanelId = DockPanelId::new(1);
2344    const VIEWPORT: DockPanelId = DockPanelId::new(2);
2345    const DETAILS: DockPanelId = DockPanelId::new(3);
2346
2347    fn root_snapshot() -> DockWorkspaceSnapshot {
2348        DockWorkspaceSnapshot::new(DockNode::split(
2349            Axis::Horizontal,
2350            0.25,
2351            DockNode::tabs([SCENE], SCENE),
2352            DockNode::split(
2353                Axis::Horizontal,
2354                0.72,
2355                DockNode::tabs([VIEWPORT], VIEWPORT),
2356                DockNode::tabs([DETAILS], DETAILS),
2357            ),
2358        ))
2359    }
2360
2361    fn panel(title: &str) -> SizedBox {
2362        SizedBox::new()
2363            .width(200.0)
2364            .height(160.0)
2365            .with_child(Label::new(title))
2366    }
2367
2368    fn build_runtime(root: impl Widget + 'static) -> (Runtime, sui_core::WindowId) {
2369        let runtime = Application::new()
2370            .window(WindowBuilder::new().title("Docking").root(root))
2371            .build()
2372            .expect("runtime builds");
2373        let window_id = runtime.window_ids()[0];
2374        (runtime, window_id)
2375    }
2376
2377    fn resize(runtime: &mut Runtime, window_id: sui_core::WindowId, width: f32, height: f32) {
2378        runtime
2379            .handle_event(
2380                window_id,
2381                Event::Window(WindowEvent::Resized(Size::new(width, height))),
2382            )
2383            .expect("window resizes");
2384    }
2385
2386    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
2387        let mut buttons = PointerButtons::NONE;
2388        if pressed {
2389            buttons.insert(PointerButton::Primary);
2390        }
2391        Event::Pointer(PointerEvent {
2392            pointer_id: 1,
2393            kind,
2394            position,
2395            delta: Vector::ZERO,
2396            scroll_delta: None,
2397            button: Some(PointerButton::Primary),
2398            buttons,
2399            modifiers: Modifiers::NONE,
2400            pointer_kind: PointerKind::Mouse,
2401            is_primary: true,
2402        })
2403    }
2404
2405    #[test]
2406    fn snapshot_rejects_duplicate_panels_and_invalid_splits() {
2407        let duplicate = DockWorkspaceSnapshot::new(DockNode::split(
2408            Axis::Horizontal,
2409            0.5,
2410            DockNode::tabs([SCENE], SCENE),
2411            DockNode::tabs([SCENE], SCENE),
2412        ));
2413        assert!(DockWorkspaceState::new(duplicate).is_err());
2414
2415        let invalid = DockWorkspaceSnapshot::new(DockNode::Split {
2416            axis: Axis::Horizontal,
2417            fraction: f32::NAN,
2418            first: Box::new(DockNode::tabs([SCENE], SCENE)),
2419            second: Box::new(DockNode::tabs([VIEWPORT], VIEWPORT)),
2420        });
2421        assert!(DockWorkspaceState::new(invalid).is_err());
2422
2423        let empty_branch = DockWorkspaceSnapshot::new(DockNode::Split {
2424            axis: Axis::Horizontal,
2425            fraction: 0.5,
2426            first: Box::new(DockNode::Empty),
2427            second: Box::new(DockNode::tabs([VIEWPORT], VIEWPORT)),
2428        });
2429        assert!(DockWorkspaceState::new(empty_branch).is_err());
2430    }
2431
2432    #[test]
2433    fn state_round_trips_hide_float_and_dock_without_duplicates() {
2434        let state = DockWorkspaceState::new(root_snapshot()).expect("valid root");
2435        let floating = state
2436            .float_panel(DETAILS, Rect::new(80.0, 60.0, 300.0, 240.0))
2437            .expect("details floats");
2438        assert_eq!(floating, 1);
2439        assert_eq!(state.snapshot().floating[0].panels, vec![DETAILS]);
2440
2441        assert!(state.hide(SCENE).expect("scene hides"));
2442        assert!(state.snapshot().hidden.contains(&SCENE));
2443        assert!(state.show(SCENE).expect("scene shows"));
2444        assert!(!state.snapshot().hidden.contains(&SCENE));
2445
2446        assert!(
2447            state
2448                .dock(DETAILS, VIEWPORT, DockZone::Center)
2449                .expect("details docks")
2450        );
2451        let snapshot = state.snapshot();
2452        assert!(snapshot.floating.is_empty());
2453        validate_snapshot(&snapshot).expect("mutated snapshot stays canonical");
2454    }
2455
2456    #[test]
2457    fn docking_and_floating_preserve_panel_widget_identity() {
2458        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
2459            [VIEWPORT, DETAILS],
2460            VIEWPORT,
2461        )))
2462        .expect("valid tabs");
2463        let workspace = DockWorkspace::new(state.clone())
2464            .with_panel(VIEWPORT, "Viewport", panel("Viewport content"))
2465            .with_panel(DETAILS, "Details", panel("Details content"));
2466        let details_widget = workspace
2467            .panel_widget_id(DETAILS)
2468            .expect("details widget registered");
2469        let (mut runtime, window_id) = build_runtime(workspace);
2470        resize(&mut runtime, window_id, 800.0, 600.0);
2471        runtime.render(window_id).expect("initial frame");
2472
2473        state
2474            .float_panel(DETAILS, Rect::new(400.0, 80.0, 280.0, 320.0))
2475            .expect("details floats");
2476        runtime.render(window_id).expect("floating frame");
2477        assert!(
2478            runtime
2479                .widget_graph(window_id)
2480                .expect("floating graph")
2481                .nodes
2482                .iter()
2483                .any(|node| node.id == details_widget)
2484        );
2485
2486        state
2487            .dock(DETAILS, VIEWPORT, DockZone::Center)
2488            .expect("details docks again");
2489        state.activate(DETAILS).expect("details activates");
2490        runtime.render(window_id).expect("redocked frame");
2491        assert!(
2492            runtime
2493                .widget_graph(window_id)
2494                .expect("redocked graph")
2495                .nodes
2496                .iter()
2497                .any(|node| node.id == details_widget),
2498            "the original retained details widget must be reused"
2499        );
2500    }
2501
2502    #[test]
2503    fn dock_tab_titles_are_shaped_as_one_line() {
2504        const WORKFLOW: DockPanelId = DockPanelId::new(10);
2505        const MODELS: DockPanelId = DockPanelId::new(11);
2506        const WORKFLOW_TITLE: &str = "Image-to-3D Workflow";
2507        const MODELS_TITLE: &str = "Model Manager";
2508
2509        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
2510            [WORKFLOW, MODELS],
2511            WORKFLOW,
2512        )))
2513        .expect("valid tabs");
2514        let workspace = DockWorkspace::new(state)
2515            .with_panel(WORKFLOW, WORKFLOW_TITLE, panel("Workflow body"))
2516            .with_panel(MODELS, MODELS_TITLE, panel("Models body"));
2517        let (mut runtime, window_id) = build_runtime(workspace);
2518        resize(&mut runtime, window_id, 340.0, 240.0);
2519        let output = runtime.render(window_id).expect("dock tabs render");
2520
2521        for title in [WORKFLOW_TITLE, MODELS_TITLE] {
2522            let mut line_counts = Vec::new();
2523            output.frame.scene.visit_commands(&mut |command| {
2524                let SceneCommand::DrawShapedText(run) = command else {
2525                    return;
2526                };
2527                if let Some(layout) = run
2528                    .resolve(output.frame.text_layout_registry.as_ref())
2529                    .filter(|layout| layout.text() == title)
2530                {
2531                    line_counts.push(layout.lines().len());
2532                }
2533            });
2534            assert_eq!(
2535                line_counts,
2536                vec![1],
2537                "dock tab title {title:?} must remain a single line"
2538            );
2539        }
2540    }
2541
2542    #[test]
2543    fn splitter_pointer_drag_updates_persisted_fraction() {
2544        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
2545            Axis::Horizontal,
2546            0.5,
2547            DockNode::tabs([SCENE], SCENE),
2548            DockNode::tabs([VIEWPORT], VIEWPORT),
2549        )))
2550        .expect("valid split");
2551        let root = DockWorkspace::new(state.clone())
2552            .with_panel(SCENE, "Scene", panel("Scene"))
2553            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
2554        let (mut runtime, window_id) = build_runtime(root);
2555        resize(&mut runtime, window_id, 800.0, 600.0);
2556        runtime.render(window_id).expect("initial frame");
2557
2558        runtime
2559            .handle_event(
2560                window_id,
2561                primary_pointer(PointerEventKind::Down, Point::new(400.0, 300.0), true),
2562            )
2563            .expect("split press");
2564        runtime
2565            .handle_event(
2566                window_id,
2567                primary_pointer(PointerEventKind::Move, Point::new(600.0, 300.0), true),
2568            )
2569            .expect("split move");
2570        runtime
2571            .handle_event(
2572                window_id,
2573                primary_pointer(PointerEventKind::Up, Point::new(600.0, 300.0), false),
2574            )
2575            .expect("split release");
2576
2577        let DockNode::Split { fraction, .. } = state.snapshot().root else {
2578            panic!("root remains split");
2579        };
2580        assert!(fraction > 0.7, "dragged fraction was {fraction}");
2581    }
2582
2583    #[test]
2584    fn pointer_tab_drag_floats_redocks_and_preserves_widget_identity() {
2585        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs(
2586            [SCENE, VIEWPORT],
2587            SCENE,
2588        )))
2589        .expect("valid tabs");
2590        let workspace = DockWorkspace::new(state.clone())
2591            .with_panel(SCENE, "Scene", panel("Scene"))
2592            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
2593        let scene_widget = workspace
2594            .panel_widget_id(SCENE)
2595            .expect("scene widget registered");
2596        let (mut runtime, window_id) = build_runtime(workspace);
2597        resize(&mut runtime, window_id, 800.0, 600.0);
2598        runtime.render(window_id).expect("initial frame");
2599
2600        runtime
2601            .handle_event(
2602                window_id,
2603                primary_pointer(PointerEventKind::Down, Point::new(20.0, 10.0), true),
2604            )
2605            .expect("scene tab press");
2606        runtime
2607            .handle_event(
2608                window_id,
2609                primary_pointer(PointerEventKind::Move, Point::new(840.0, 40.0), true),
2610            )
2611            .expect("scene tab drag outside");
2612        runtime
2613            .handle_event(
2614                window_id,
2615                primary_pointer(PointerEventKind::Up, Point::new(840.0, 40.0), false),
2616            )
2617            .expect("scene tab float drop");
2618
2619        let floated = state.snapshot();
2620        assert_eq!(floated.floating.len(), 1);
2621        assert_eq!(floated.floating[0].panels, vec![SCENE]);
2622        assert!(node_contains_panel(&floated.root, VIEWPORT));
2623        let floating_bounds = floated.floating[0].bounds;
2624
2625        runtime.render(window_id).expect("floating frame");
2626        assert!(
2627            runtime
2628                .widget_graph(window_id)
2629                .expect("floating graph")
2630                .nodes
2631                .iter()
2632                .any(|node| node.id == scene_widget)
2633        );
2634
2635        let floating_tab = Point::new(floating_bounds.x() + 20.0, floating_bounds.y() + 10.0);
2636        runtime
2637            .handle_event(
2638                window_id,
2639                primary_pointer(PointerEventKind::Down, floating_tab, true),
2640            )
2641            .expect("floating scene tab press");
2642        runtime
2643            .handle_event(
2644                window_id,
2645                primary_pointer(PointerEventKind::Move, Point::new(8.0, 300.0), true),
2646            )
2647            .expect("floating scene tab drag to dock edge");
2648        runtime
2649            .handle_event(
2650                window_id,
2651                primary_pointer(PointerEventKind::Up, Point::new(8.0, 300.0), false),
2652            )
2653            .expect("floating scene tab dock drop");
2654
2655        let redocked = state.snapshot();
2656        assert!(redocked.floating.is_empty());
2657        assert!(matches!(
2658            redocked.root,
2659            DockNode::Split {
2660                axis: Axis::Horizontal,
2661                ..
2662            }
2663        ));
2664        validate_snapshot(&redocked).expect("pointer-mutated snapshot stays canonical");
2665
2666        runtime.render(window_id).expect("redocked frame");
2667        assert!(
2668            runtime
2669                .widget_graph(window_id)
2670                .expect("redocked graph")
2671                .nodes
2672                .iter()
2673                .any(|node| node.id == scene_widget),
2674            "the same retained scene widget must survive float and dock gestures"
2675        );
2676    }
2677
2678    #[test]
2679    fn tab_drag_updates_keyboard_navigation_to_the_destination_group() {
2680        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
2681            Axis::Horizontal,
2682            0.5,
2683            DockNode::tabs([SCENE, DETAILS], SCENE),
2684            DockNode::tabs([VIEWPORT], VIEWPORT),
2685        )))
2686        .expect("valid split tabs");
2687        let workspace = DockWorkspace::new(state.clone())
2688            .with_panel(SCENE, "Scene", panel("Scene"))
2689            .with_panel(VIEWPORT, "Viewport", panel("Viewport"))
2690            .with_panel(DETAILS, "Details", panel("Details"));
2691        let (mut runtime, window_id) = build_runtime(workspace);
2692        resize(&mut runtime, window_id, 800.0, 600.0);
2693        runtime.render(window_id).expect("initial frame");
2694
2695        runtime
2696            .handle_event(
2697                window_id,
2698                primary_pointer(PointerEventKind::Down, Point::new(20.0, 10.0), true),
2699            )
2700            .expect("source tab press");
2701        runtime
2702            .handle_event(
2703                window_id,
2704                primary_pointer(PointerEventKind::Move, Point::new(600.0, 300.0), true),
2705            )
2706            .expect("drag to destination center");
2707        runtime
2708            .handle_event(
2709                window_id,
2710                primary_pointer(PointerEventKind::Up, Point::new(600.0, 300.0), false),
2711            )
2712            .expect("drop into destination tabs");
2713        runtime
2714            .handle_event(
2715                window_id,
2716                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
2717            )
2718            .expect("cycle destination tabs");
2719
2720        let DockNode::Split { first, second, .. } = state.snapshot().root else {
2721            panic!("workspace remains split");
2722        };
2723        let DockNode::Tabs {
2724            active: source_active,
2725            ..
2726        } = *first
2727        else {
2728            panic!("source remains a tab group");
2729        };
2730        let DockNode::Tabs {
2731            panels,
2732            active: destination_active,
2733        } = *second
2734        else {
2735            panic!("destination remains a tab group");
2736        };
2737        assert_eq!(source_active, DETAILS);
2738        assert_eq!(panels, vec![VIEWPORT, SCENE]);
2739        assert_eq!(
2740            destination_active, VIEWPORT,
2741            "ArrowRight must cycle the destination group after the drag"
2742        );
2743    }
2744
2745    #[test]
2746    fn splitter_semantics_expose_and_mutate_the_persisted_fraction() {
2747        let state = DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::split(
2748            Axis::Horizontal,
2749            0.5,
2750            DockNode::tabs([SCENE], SCENE),
2751            DockNode::tabs([VIEWPORT], VIEWPORT),
2752        )))
2753        .expect("valid split");
2754        let workspace = DockWorkspace::new(state.clone())
2755            .with_panel(SCENE, "Scene", panel("Scene"))
2756            .with_panel(VIEWPORT, "Viewport", panel("Viewport"));
2757        let (mut runtime, window_id) = build_runtime(workspace);
2758        resize(&mut runtime, window_id, 800.0, 600.0);
2759        let frame = runtime.render(window_id).expect("initial frame");
2760        let splitter = frame
2761            .semantics
2762            .iter()
2763            .find(|node| node.role == SemanticsRole::Splitter)
2764            .expect("dock splitter semantics");
2765        assert_eq!(
2766            splitter.value,
2767            Some(SemanticsValue::Range {
2768                value: 0.5,
2769                min: f64::from(MIN_SPLIT_FRACTION),
2770                max: f64::from(MAX_SPLIT_FRACTION),
2771            })
2772        );
2773        for action in [
2774            SemanticsAction::Increment,
2775            SemanticsAction::Decrement,
2776            SemanticsAction::SetValue,
2777        ] {
2778            assert!(splitter.actions.contains(&action));
2779        }
2780        let splitter_id = splitter.id;
2781
2782        assert!(
2783            runtime
2784                .handle_semantics_action(window_id, splitter_id, SemanticsActionRequest::Increment,)
2785                .expect("increment semantics routes")
2786        );
2787        let DockNode::Split { fraction, .. } = state.snapshot().root else {
2788            panic!("root remains split");
2789        };
2790        assert!((fraction - 0.55).abs() < f32::EPSILON);
2791
2792        runtime.render(window_id).expect("incremented frame");
2793        assert!(
2794            runtime
2795                .handle_semantics_action(
2796                    window_id,
2797                    splitter_id,
2798                    SemanticsActionRequest::SetValue(SemanticsValue::Number(0.8)),
2799                )
2800                .expect("set-value semantics routes")
2801        );
2802        let DockNode::Split { fraction, .. } = state.snapshot().root else {
2803            panic!("root remains split");
2804        };
2805        assert!((fraction - 0.8).abs() < f32::EPSILON);
2806    }
2807
2808    #[test]
2809    fn floating_layout_collapses_minimum_size_to_a_tiny_host() {
2810        let host = Rect::new(10.0, 20.0, 100.0, 80.0);
2811        let resolved = clamp_floating_bounds(host, Rect::new(-400.0, 500.0, 320.0, 260.0));
2812        assert_eq!(resolved, host);
2813    }
2814
2815    #[test]
2816    fn registered_panel_validation_reports_unknown_snapshot_ids() {
2817        let state =
2818            DockWorkspaceState::new(DockWorkspaceSnapshot::new(DockNode::tabs([SCENE], SCENE)))
2819                .expect("valid state");
2820        let workspace =
2821            DockWorkspace::new(state.clone()).with_panel(SCENE, "Scene", panel("Scene"));
2822        let restored = DockWorkspaceSnapshot::new(DockNode::tabs([SCENE, VIEWPORT], SCENE));
2823        let error = workspace
2824            .apply_snapshot(restored.clone())
2825            .expect_err("viewport is not registered");
2826        assert!(error.to_string().contains("panel 2"));
2827        assert!(!node_contains_panel(&state.snapshot().root, VIEWPORT));
2828
2829        state
2830            .apply_snapshot(restored)
2831            .expect("state-only restore validates graph structure");
2832        assert!(workspace.validate_registered_panels().is_err());
2833    }
2834}