Skip to main content

sui_widgets/
panes.rs

1use std::{
2    cell::Cell,
3    sync::{Arc, Mutex, MutexGuard},
4};
5
6use sui_core::{
7    Color, Event, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, Point,
8    PointerButton, PointerEventKind, Rect, SemanticsAction, SemanticsNode, SemanticsRole,
9    SemanticsValue, Size, WakeEvent, WidgetId,
10};
11use sui_layout::{Axis, Constraints};
12use sui_reactive::Signal;
13use sui_runtime::{
14    ArrangeCtx, EventCtx, EventPhase, LayerOptions, MeasureCtx, PaintBoundaryMode, PaintCtx,
15    SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy, Widget, WidgetPod,
16    WidgetPodMutVisitor, WidgetPodVisitor,
17};
18use sui_scene::{LayerCompositionMode, StrokeStyle};
19
20use crate::{
21    DefaultTheme, MotionScalar,
22    containers::{ScrollBar, ScrollState, ScrollView},
23    text_align::paint_aligned_text,
24};
25
26type AnimatedScalar = MotionScalar;
27type ThemeReader = std::rc::Rc<dyn Fn() -> DefaultTheme>;
28
29fn retained_subtree_contains(root: &WidgetPod, target: WidgetId) -> bool {
30    if root.id() == target {
31        return true;
32    }
33
34    struct Finder {
35        target: WidgetId,
36        found: bool,
37    }
38
39    impl WidgetPodVisitor for Finder {
40        fn visit(&mut self, child: &WidgetPod) {
41            if self.found {
42                return;
43            }
44            if child.id() == self.target {
45                self.found = true;
46            } else {
47                child.visit_children(self);
48            }
49        }
50    }
51
52    let mut finder = Finder {
53        target,
54        found: false,
55    };
56    root.visit_children(&mut finder);
57    finder.found
58}
59
60fn first_focusable_in(root: &WidgetPod) -> Option<WidgetId> {
61    if root.accepts_focus() {
62        return Some(root.id());
63    }
64
65    struct Finder {
66        target: Option<WidgetId>,
67    }
68
69    impl WidgetPodVisitor for Finder {
70        fn visit(&mut self, child: &WidgetPod) {
71            if self.target.is_some() {
72                return;
73            }
74            if child.accepts_focus() {
75                self.target = Some(child.id());
76            } else {
77                child.visit_children(self);
78            }
79        }
80    }
81
82    let mut finder = Finder { target: None };
83    root.visit_children(&mut finder);
84    finder.target
85}
86
87fn set_animation_target(
88    animation: &mut AnimatedScalar,
89    target: f32,
90    duration: f64,
91    easing: crate::Easing,
92    ctx: &mut EventCtx,
93) -> bool {
94    animation.set_target_event(target, duration, easing, ctx)
95}
96
97fn set_hover_animation_target(
98    animation: &mut AnimatedScalar,
99    target: f32,
100    theme: &DefaultTheme,
101    ctx: &mut EventCtx,
102) -> bool {
103    set_animation_target(
104        animation,
105        target,
106        theme.motion.hover_duration(),
107        theme.motion.hover_easing(),
108        ctx,
109    )
110}
111
112fn set_press_animation_target(
113    animation: &mut AnimatedScalar,
114    target: f32,
115    theme: &DefaultTheme,
116    ctx: &mut EventCtx,
117) -> bool {
118    set_animation_target(
119        animation,
120        target,
121        theme.motion.press_duration(),
122        theme.motion.press_easing(),
123        ctx,
124    )
125}
126
127fn set_focus_animation_target(
128    animation: &mut AnimatedScalar,
129    target: f32,
130    theme: &DefaultTheme,
131    ctx: &mut EventCtx,
132) -> bool {
133    set_animation_target(
134        animation,
135        target,
136        theme.motion.focus_duration(),
137        theme.motion.focus_easing(),
138        ctx,
139    )
140}
141
142fn mix_color(from: Color, to: Color, amount: f32) -> Color {
143    crate::animation::Interpolate::interpolate(from, to, amount)
144}
145
146pub type ResizablePane = SplitView;
147
148#[derive(Debug, Clone, PartialEq)]
149pub struct FloatingViewConfig {
150    pub title: String,
151    pub bounds: Rect,
152    pub min_size: Size,
153    pub visible: bool,
154}
155
156impl FloatingViewConfig {
157    pub fn new(title: impl Into<String>, bounds: Rect) -> Self {
158        Self {
159            title: title.into(),
160            bounds,
161            min_size: Size::new(220.0, 160.0),
162            visible: true,
163        }
164    }
165
166    pub fn min_size(mut self, min_size: Size) -> Self {
167        self.min_size = Size::new(min_size.width.max(120.0), min_size.height.max(120.0));
168        self
169    }
170
171    pub fn visible(mut self, visible: bool) -> Self {
172        self.visible = visible;
173        self
174    }
175}
176
177#[derive(Debug, Clone, PartialEq)]
178pub struct FloatingViewSnapshot {
179    pub id: u64,
180    pub title: String,
181    pub bounds: Rect,
182    pub min_size: Size,
183    pub visible: bool,
184    pub maximized: bool,
185    pub surface_widget_id: Option<WidgetId>,
186}
187
188#[derive(Debug, Clone, PartialEq)]
189struct FloatingViewState {
190    id: u64,
191    title: String,
192    bounds: Rect,
193    min_size: Size,
194    visible: bool,
195    surface_widget_id: Option<WidgetId>,
196}
197
198#[derive(Debug, Default)]
199struct FloatingWorkspaceStateInner {
200    next_id: u64,
201    views: Vec<FloatingViewState>,
202    z_order: Vec<u64>,
203    maximized_view: Option<u64>,
204    active_resize_view: Option<u64>,
205}
206
207#[derive(Clone, Default)]
208pub struct FloatingWorkspaceState {
209    inner: Arc<Mutex<FloatingWorkspaceStateInner>>,
210}
211
212impl FloatingWorkspaceState {
213    pub fn new() -> Self {
214        Self::default()
215    }
216
217    fn lock_inner(&self) -> MutexGuard<'_, FloatingWorkspaceStateInner> {
218        self.inner
219            .lock()
220            .unwrap_or_else(std::sync::PoisonError::into_inner)
221    }
222
223    pub fn add_view(&self, config: FloatingViewConfig) -> u64 {
224        let mut inner = self.lock_inner();
225        let id = inner.next_id.max(1);
226        inner.next_id = id + 1;
227        inner.views.push(FloatingViewState {
228            id,
229            title: config.title,
230            bounds: config.bounds,
231            min_size: Size::new(
232                config.min_size.width.max(120.0),
233                config.min_size.height.max(120.0),
234            ),
235            visible: config.visible,
236            surface_widget_id: None,
237        });
238        inner.z_order.push(id);
239        id
240    }
241
242    pub fn snapshots(&self) -> Vec<FloatingViewSnapshot> {
243        let inner = self.lock_inner();
244        inner
245            .views
246            .iter()
247            .map(|view| FloatingViewSnapshot {
248                id: view.id,
249                title: view.title.clone(),
250                bounds: view.bounds,
251                min_size: view.min_size,
252                visible: view.visible,
253                maximized: inner.maximized_view == Some(view.id),
254                surface_widget_id: view.surface_widget_id,
255            })
256            .collect()
257    }
258
259    pub fn snapshot(&self, view_id: u64) -> Option<FloatingViewSnapshot> {
260        let inner = self.lock_inner();
261        inner
262            .views
263            .iter()
264            .find(|view| view.id == view_id)
265            .map(|view| FloatingViewSnapshot {
266                id: view.id,
267                title: view.title.clone(),
268                bounds: view.bounds,
269                min_size: view.min_size,
270                visible: view.visible,
271                maximized: inner.maximized_view == Some(view.id),
272                surface_widget_id: view.surface_widget_id,
273            })
274    }
275
276    pub fn set_view_surface_widget(&self, view_id: u64, widget_id: WidgetId) -> bool {
277        let mut inner = self.lock_inner();
278        let Some(view) = inner.views.iter_mut().find(|view| view.id == view_id) else {
279            return false;
280        };
281        if view.surface_widget_id == Some(widget_id) {
282            return false;
283        }
284        view.surface_widget_id = Some(widget_id);
285        true
286    }
287
288    pub fn view_surface_widget_id(&self, view_id: u64) -> Option<WidgetId> {
289        self.inner
290            .lock()
291            .unwrap_or_else(std::sync::PoisonError::into_inner)
292            .views
293            .iter()
294            .find(|view| view.id == view_id)
295            .and_then(|view| view.surface_widget_id)
296    }
297
298    pub fn set_view_visible(&self, view_id: u64, visible: bool) -> bool {
299        let mut inner = self.lock_inner();
300        let Some(view) = inner.views.iter_mut().find(|view| view.id == view_id) else {
301            return false;
302        };
303        if view.visible == visible {
304            return false;
305        }
306        view.visible = visible;
307        if !visible && inner.maximized_view == Some(view_id) {
308            inner.maximized_view = None;
309        }
310        true
311    }
312
313    pub fn toggle_view_visible(&self, view_id: u64) -> Option<bool> {
314        let next = self.snapshot(view_id).map(|view| !view.visible)?;
315        self.set_view_visible(view_id, next);
316        Some(next)
317    }
318
319    pub fn set_view_bounds(&self, view_id: u64, bounds: Rect) -> bool {
320        let mut inner = self.lock_inner();
321        let Some(view) = inner.views.iter_mut().find(|view| view.id == view_id) else {
322            return false;
323        };
324        if view.bounds == bounds {
325            return false;
326        }
327        view.bounds = bounds;
328        true
329    }
330
331    pub fn bring_to_front(&self, view_id: u64) -> bool {
332        let mut inner = self.lock_inner();
333        let Some(index) = inner.z_order.iter().position(|id| *id == view_id) else {
334            return false;
335        };
336        if index + 1 == inner.z_order.len() {
337            return false;
338        }
339        let id = inner.z_order.remove(index);
340        inner.z_order.push(id);
341        true
342    }
343
344    pub fn set_view_maximized(&self, view_id: u64, maximized: bool) -> bool {
345        let mut inner = self.lock_inner();
346        let Some(index) = inner.views.iter().position(|view| view.id == view_id) else {
347            return false;
348        };
349        if maximized {
350            inner.views[index].visible = true;
351            let ordering_changed =
352                if let Some(order_index) = inner.z_order.iter().position(|id| *id == view_id) {
353                    if order_index + 1 == inner.z_order.len() {
354                        false
355                    } else {
356                        let id = inner.z_order.remove(order_index);
357                        inner.z_order.push(id);
358                        true
359                    }
360                } else {
361                    inner.z_order.push(view_id);
362                    true
363                };
364            if inner.maximized_view == Some(view_id) {
365                return ordering_changed;
366            }
367            inner.maximized_view = Some(view_id);
368            return true;
369        }
370
371        if inner.maximized_view != Some(view_id) {
372            return false;
373        }
374        inner.maximized_view = None;
375        true
376    }
377
378    pub fn active_view_ids(&self) -> Vec<u64> {
379        let inner = self.lock_inner();
380        if let Some(maximized) = inner.maximized_view {
381            return inner
382                .views
383                .iter()
384                .find(|view| view.id == maximized && view.visible)
385                .map(|view| vec![view.id])
386                .unwrap_or_default();
387        }
388
389        inner
390            .z_order
391            .iter()
392            .copied()
393            .filter(|id| {
394                inner
395                    .views
396                    .iter()
397                    .any(|view| view.id == *id && view.visible)
398            })
399            .collect()
400    }
401
402    pub fn active_resize_view(&self) -> Option<u64> {
403        self.lock_inner().active_resize_view
404    }
405
406    pub fn set_active_resize_view(&self, view_id: Option<u64>) -> bool {
407        let mut inner = self.lock_inner();
408        if inner.active_resize_view == view_id {
409            return false;
410        }
411        inner.active_resize_view = view_id;
412        true
413    }
414}
415
416struct FloatingWorkspaceEntry {
417    view_id: u64,
418    child: WidgetPod,
419}
420
421enum FloatingWorkspaceGestureKind {
422    Move,
423    Resize,
424}
425
426struct FloatingWorkspaceGesture {
427    view_id: u64,
428    pointer_id: u64,
429    kind: FloatingWorkspaceGestureKind,
430    pointer_origin: Point,
431    initial_bounds: Rect,
432}
433
434pub struct FloatingWorkspace {
435    theme: Box<DefaultTheme>,
436    theme_reader: Option<ThemeReader>,
437    name: Option<String>,
438    state: FloatingWorkspaceState,
439    views: Vec<FloatingWorkspaceEntry>,
440    gesture: Option<FloatingWorkspaceGesture>,
441}
442
443impl FloatingWorkspace {
444    pub fn new(state: FloatingWorkspaceState) -> Self {
445        Self {
446            theme: Box::new(DefaultTheme::default()),
447            theme_reader: None,
448            name: None,
449            state,
450            views: Vec::new(),
451            gesture: None,
452        }
453    }
454
455    pub fn theme(mut self, theme: DefaultTheme) -> Self {
456        self.theme = Box::new(theme);
457        self.theme_reader = None;
458        self
459    }
460
461    pub fn theme_when<F>(mut self, theme: F) -> Self
462    where
463        F: Fn() -> DefaultTheme + 'static,
464    {
465        self.theme_reader = Some(std::rc::Rc::new(theme));
466        self
467    }
468
469    pub fn name(mut self, name: impl Into<String>) -> Self {
470        self.name = Some(name.into());
471        self
472    }
473
474    pub fn state(&self) -> FloatingWorkspaceState {
475        self.state.clone()
476    }
477
478    pub fn with_view<W>(mut self, config: FloatingViewConfig, child: W) -> Self
479    where
480        W: Widget + 'static,
481    {
482        self.push_view(config, child);
483        self
484    }
485
486    /// Attach a child to a view that was already registered in `state`.
487    ///
488    /// This is useful for language bindings and restored layouts where view
489    /// identities are allocated before the retained widget is constructed.
490    pub fn with_registered_view<W>(mut self, view_id: u64, child: W) -> Self
491    where
492        W: Widget + 'static,
493    {
494        assert!(
495            self.state.snapshot(view_id).is_some(),
496            "floating workspace view must be registered before attaching its widget"
497        );
498        let child = WidgetPod::new(FloatingViewSurface::new(
499            self.resolved_theme(),
500            self.theme_reader.clone(),
501            self.state.clone(),
502            view_id,
503            child,
504        ));
505        self.state.set_view_surface_widget(view_id, child.id());
506        self.views.push(FloatingWorkspaceEntry { view_id, child });
507        self
508    }
509
510    pub fn push_view<W>(&mut self, config: FloatingViewConfig, child: W) -> u64
511    where
512        W: Widget + 'static,
513    {
514        let view_id = self.state.add_view(config);
515        let child = WidgetPod::new(FloatingViewSurface::new(
516            self.resolved_theme(),
517            self.theme_reader.clone(),
518            self.state.clone(),
519            view_id,
520            child,
521        ));
522        self.state.set_view_surface_widget(view_id, child.id());
523        self.views.push(FloatingWorkspaceEntry { view_id, child });
524        view_id
525    }
526
527    fn entry(&self, view_id: u64) -> Option<&FloatingWorkspaceEntry> {
528        self.views.iter().find(|entry| entry.view_id == view_id)
529    }
530
531    fn entry_mut(&mut self, view_id: u64) -> Option<&mut FloatingWorkspaceEntry> {
532        self.views.iter_mut().find(|entry| entry.view_id == view_id)
533    }
534
535    fn resolved_theme(&self) -> DefaultTheme {
536        self.theme_reader
537            .as_ref()
538            .map(|theme| theme())
539            .unwrap_or(*self.theme)
540    }
541
542    fn active_view_ids(&self) -> Vec<u64> {
543        self.state.active_view_ids()
544    }
545
546    fn frontmost_hit(&self, host_bounds: Rect, position: Point) -> Option<FloatingWorkspaceHit> {
547        let theme = self.resolved_theme();
548        self.active_view_ids()
549            .into_iter()
550            .rev()
551            .filter_map(|view_id| self.state.snapshot(view_id))
552            .find_map(|view| {
553                let bounds = resolved_floating_view_bounds(&theme, host_bounds, &view);
554                if !bounds.contains(position) {
555                    return None;
556                }
557
558                if !view.maximized
559                    && floating_view_resize_handle_rect(&theme, bounds).contains(position)
560                {
561                    return Some(FloatingWorkspaceHit {
562                        view_id: view.id,
563                        region: FloatingWorkspaceHitRegion::ResizeHandle,
564                    });
565                }
566
567                if !view.maximized
568                    && floating_view_title_bar_rect(&theme, bounds).contains(position)
569                {
570                    return Some(FloatingWorkspaceHit {
571                        view_id: view.id,
572                        region: FloatingWorkspaceHitRegion::TitleBar,
573                    });
574                }
575
576                Some(FloatingWorkspaceHit {
577                    view_id: view.id,
578                    region: FloatingWorkspaceHitRegion::Body,
579                })
580            })
581    }
582
583    fn update_drag(&mut self, host_bounds: Rect, position: Point) -> Option<Rect> {
584        let Some(gesture) = &self.gesture else {
585            return None;
586        };
587        let view = self.state.snapshot(gesture.view_id)?;
588
589        let delta = position - gesture.pointer_origin;
590        let previous_bounds = view.bounds;
591        let next_bounds = match gesture.kind {
592            FloatingWorkspaceGestureKind::Move => Rect::new(
593                gesture.initial_bounds.x() + delta.x,
594                gesture.initial_bounds.y() + delta.y,
595                gesture.initial_bounds.width(),
596                gesture.initial_bounds.height(),
597            ),
598            FloatingWorkspaceGestureKind::Resize => Rect::new(
599                gesture.initial_bounds.x(),
600                gesture.initial_bounds.y(),
601                gesture.initial_bounds.width() + delta.x,
602                gesture.initial_bounds.height() + delta.y,
603            ),
604        };
605        let theme = self.resolved_theme();
606        let clamped = clamp_floating_view_bounds(&theme, host_bounds, next_bounds, view.min_size);
607        if !self.state.set_view_bounds(view.id, clamped) {
608            return None;
609        }
610
611        Some(previous_bounds.union(clamped))
612    }
613}
614
615impl Widget for FloatingWorkspace {
616    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
617        match event {
618            Event::Pointer(pointer)
619                if pointer.kind == PointerEventKind::Move
620                    && self
621                        .gesture
622                        .as_ref()
623                        .is_some_and(|gesture| gesture.pointer_id == pointer.pointer_id) =>
624            {
625                let resizing = self.gesture.as_ref().is_some_and(|gesture| {
626                    matches!(gesture.kind, FloatingWorkspaceGestureKind::Resize)
627                });
628                let refresh_target = if resizing {
629                    self.gesture
630                        .as_ref()
631                        .and_then(|gesture| self.state.view_surface_widget_id(gesture.view_id))
632                        .unwrap_or(ctx.widget_id())
633                } else {
634                    ctx.widget_id()
635                };
636                if let Some(dirty_region) = self.update_drag(ctx.bounds(), pointer.position) {
637                    if resizing {
638                        request_widget_refresh(ctx, refresh_target, true, false, dirty_region);
639                    } else {
640                        request_widget_refresh(ctx, refresh_target, false, false, dirty_region);
641                    }
642                }
643                ctx.set_handled();
644            }
645            Event::Pointer(pointer)
646                if pointer.kind == PointerEventKind::Up
647                    && pointer.button == Some(PointerButton::Primary)
648                    && self
649                        .gesture
650                        .as_ref()
651                        .is_some_and(|gesture| gesture.pointer_id == pointer.pointer_id) =>
652            {
653                let active_view = self.gesture.as_ref().and_then(|gesture| {
654                    matches!(gesture.kind, FloatingWorkspaceGestureKind::Resize)
655                        .then_some(gesture.view_id)
656                });
657                if self.state.set_active_resize_view(None) {
658                    let refresh_target = active_view
659                        .and_then(|view_id| self.state.view_surface_widget_id(view_id))
660                        .unwrap_or(ctx.widget_id());
661                    let refresh_region = active_view
662                        .and_then(|view_id| self.state.snapshot(view_id).map(|view| view.bounds))
663                        .unwrap_or(ctx.bounds());
664                    request_widget_refresh(ctx, refresh_target, true, false, refresh_region);
665                }
666                self.gesture = None;
667                ctx.release_pointer_capture(pointer.pointer_id);
668                ctx.set_handled();
669            }
670            Event::Pointer(pointer)
671                if pointer.kind == PointerEventKind::Cancel
672                    && self
673                        .gesture
674                        .as_ref()
675                        .is_some_and(|gesture| gesture.pointer_id == pointer.pointer_id) =>
676            {
677                let active_view = self.gesture.as_ref().and_then(|gesture| {
678                    matches!(gesture.kind, FloatingWorkspaceGestureKind::Resize)
679                        .then_some(gesture.view_id)
680                });
681                if self.state.set_active_resize_view(None) {
682                    let refresh_target = active_view
683                        .and_then(|view_id| self.state.view_surface_widget_id(view_id))
684                        .unwrap_or(ctx.widget_id());
685                    let refresh_region = active_view
686                        .and_then(|view_id| self.state.snapshot(view_id).map(|view| view.bounds))
687                        .unwrap_or(ctx.bounds());
688                    request_widget_refresh(ctx, refresh_target, true, false, refresh_region);
689                }
690                self.gesture = None;
691                ctx.release_pointer_capture(pointer.pointer_id);
692                ctx.set_handled();
693            }
694            Event::Pointer(pointer)
695                if pointer.kind == PointerEventKind::Down
696                    && pointer.button == Some(PointerButton::Primary) =>
697            {
698                let Some(hit) = self.frontmost_hit(ctx.bounds(), pointer.position) else {
699                    return;
700                };
701
702                let ordering_changed = self.state.bring_to_front(hit.view_id);
703                if ordering_changed {
704                    ctx.request_ordering();
705                    ctx.request_paint();
706                    ctx.request_hit_test();
707                }
708
709                let Some(view) = self.state.snapshot(hit.view_id) else {
710                    return;
711                };
712                let theme = self.resolved_theme();
713                let bounds = resolved_floating_view_bounds(&theme, ctx.bounds(), &view);
714                match hit.region {
715                    FloatingWorkspaceHitRegion::TitleBar => {
716                        self.gesture = Some(FloatingWorkspaceGesture {
717                            view_id: hit.view_id,
718                            pointer_id: pointer.pointer_id,
719                            kind: FloatingWorkspaceGestureKind::Move,
720                            pointer_origin: pointer.position,
721                            initial_bounds: bounds,
722                        });
723                        ctx.request_pointer_capture(pointer.pointer_id);
724                        ctx.set_handled();
725                    }
726                    FloatingWorkspaceHitRegion::ResizeHandle => {
727                        self.state.set_active_resize_view(Some(hit.view_id));
728                        self.gesture = Some(FloatingWorkspaceGesture {
729                            view_id: hit.view_id,
730                            pointer_id: pointer.pointer_id,
731                            kind: FloatingWorkspaceGestureKind::Resize,
732                            pointer_origin: pointer.position,
733                            initial_bounds: bounds,
734                        });
735                        ctx.request_pointer_capture(pointer.pointer_id);
736                        ctx.set_handled();
737                    }
738                    FloatingWorkspaceHitRegion::Body => {}
739                }
740            }
741            _ => {}
742        }
743    }
744
745    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
746        let snapshots = self.state.snapshots();
747        let fallback = snapshots.iter().fold(Size::ZERO, |size, view| {
748            Size::new(
749                size.width.max(view.bounds.max_x().max(0.0)),
750                size.height.max(view.bounds.max_y().max(0.0)),
751            )
752        });
753        let size = constraints.clamp(Size::new(
754            if constraints.max.width.is_finite() {
755                constraints.max.width
756            } else {
757                fallback.width
758            },
759            if constraints.max.height.is_finite() {
760                constraints.max.height
761            } else {
762                fallback.height
763            },
764        ));
765
766        let host_bounds = Rect::from_origin_size(Point::ZERO, size);
767        let theme = self.resolved_theme();
768        for view_id in self.active_view_ids() {
769            let Some(snapshot) = self.state.snapshot(view_id) else {
770                continue;
771            };
772            let bounds = resolved_floating_view_bounds(&theme, host_bounds, &snapshot);
773            if let Some(entry) = self.entry_mut(view_id) {
774                entry.child.measure(ctx, Constraints::tight(bounds.size));
775            }
776        }
777
778        size
779    }
780
781    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
782        let theme = self.resolved_theme();
783        for view_id in self.active_view_ids() {
784            let Some(snapshot) = self.state.snapshot(view_id) else {
785                continue;
786            };
787            let resolved = resolved_floating_view_bounds(&theme, bounds, &snapshot);
788            if !snapshot.maximized && resolved != snapshot.bounds {
789                self.state.set_view_bounds(view_id, resolved);
790            }
791            if let Some(entry) = self.entry_mut(view_id) {
792                entry.child.arrange(ctx, resolved);
793            }
794        }
795    }
796
797    fn paint(&self, ctx: &mut PaintCtx) {
798        let dirty_region = widget_invalidation_region(ctx.invalidations(), ctx.widget_id())
799            .and_then(|region| region.intersection(ctx.bounds()));
800
801        if let Some(region) = dirty_region {
802            ctx.push_clip_rect(region);
803        }
804
805        let theme = self.resolved_theme();
806        let palette = theme.palette;
807        ctx.fill_bounds(palette.control);
808        ctx.fill_rect(
809            ctx.bounds().inflate(
810                -theme.metrics.floating_workspace_margin,
811                -theme.metrics.floating_workspace_margin,
812            ),
813            palette.surface_raised.with_alpha(0.72),
814        );
815
816        for view_id in self.active_view_ids() {
817            if let Some(entry) = self.entry(view_id) {
818                if dirty_region
819                    .is_some_and(|region| entry.child.bounds().intersection(region).is_none())
820                {
821                    continue;
822                }
823                entry.child.paint(ctx);
824            }
825        }
826
827        if dirty_region.is_some() {
828            ctx.pop_clip();
829        }
830    }
831
832    fn stack_host_options(&self) -> Option<StackHostOptions> {
833        Some(StackHostOptions {
834            order_policy: StackOrderPolicy::FocusFronted,
835        })
836    }
837
838    fn semantics(&self, ctx: &mut SemanticsCtx) {
839        let mut node = SemanticsNode::new(
840            ctx.widget_id(),
841            SemanticsRole::GenericContainer,
842            ctx.bounds(),
843        );
844        node.name = self.name.clone();
845        node.state.focused = ctx.is_focused();
846        ctx.push(node);
847
848        for view_id in self.active_view_ids() {
849            if let Some(entry) = self.entry(view_id) {
850                entry.child.semantics(ctx);
851            }
852        }
853    }
854
855    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
856        for view_id in self.active_view_ids() {
857            if let Some(entry) = self.entry(view_id) {
858                visitor.visit(&entry.child);
859            }
860        }
861    }
862
863    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
864        for view_id in self.active_view_ids() {
865            if let Some(entry) = self.entry_mut(view_id) {
866                visitor.visit(&mut entry.child);
867            }
868        }
869    }
870}
871
872struct FloatingWorkspaceHit {
873    view_id: u64,
874    region: FloatingWorkspaceHitRegion,
875}
876
877enum FloatingWorkspaceHitRegion {
878    TitleBar,
879    ResizeHandle,
880    Body,
881}
882
883struct FloatingViewSurface {
884    theme: Box<DefaultTheme>,
885    theme_reader: Option<ThemeReader>,
886    state: FloatingWorkspaceState,
887    view_id: u64,
888    host: SingleChild,
889}
890
891impl FloatingViewSurface {
892    fn new<W>(
893        theme: DefaultTheme,
894        theme_reader: Option<ThemeReader>,
895        state: FloatingWorkspaceState,
896        view_id: u64,
897        child: W,
898    ) -> Self
899    where
900        W: Widget + 'static,
901    {
902        Self {
903            theme: Box::new(theme),
904            theme_reader: theme_reader.clone(),
905            state: state.clone(),
906            view_id,
907            host: SingleChild::new(FloatingViewHost::new(
908                theme,
909                theme_reader,
910                state,
911                view_id,
912                child,
913            )),
914        }
915    }
916
917    fn resolved_theme(&self) -> DefaultTheme {
918        self.theme_reader
919            .as_ref()
920            .map(|theme| theme())
921            .unwrap_or(*self.theme)
922    }
923}
924
925impl Widget for FloatingViewSurface {
926    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
927        self.host.measure(ctx, constraints)
928    }
929
930    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
931        self.host.arrange(ctx, bounds);
932    }
933
934    fn paint(&self, ctx: &mut PaintCtx) {
935        let Some(view) = self.state.snapshot(self.view_id) else {
936            return;
937        };
938
939        let theme = self.resolved_theme();
940        let palette = theme.palette;
941        let metrics = theme.metrics;
942        let border_width = metrics.border_width.max(1.0);
943        ctx.push_clip_rect(ctx.bounds());
944        ctx.fill_rect(ctx.bounds(), palette.surface_raised);
945        if !view.maximized {
946            let title_bar = floating_view_title_bar_rect(&theme, ctx.bounds());
947            ctx.fill_rect(title_bar, palette.control_active);
948            let title_padding = metrics.floating_view_title_padding;
949            let text_slot = Rect::new(
950                title_bar.x() + title_padding.left,
951                title_bar.y() + title_padding.top,
952                (title_bar.width() - title_padding.left - title_padding.right).max(0.0),
953                (title_bar.height() - title_padding.top - title_padding.bottom).max(0.0),
954            );
955            let title_style = theme.text_style(palette.text);
956            ctx.push_clip_rect(text_slot);
957            paint_aligned_text(
958                ctx,
959                text_slot,
960                &view.title,
961                &title_style,
962                title_style.line_height,
963                0.0,
964            );
965            ctx.pop_clip();
966        }
967        self.host.paint(ctx);
968        if !view.maximized {
969            ctx.stroke_rect(ctx.bounds(), palette.border, StrokeStyle::new(border_width));
970            let handle = floating_view_resize_handle_rect(&theme, ctx.bounds());
971            let accent = palette.border.with_alpha(0.95);
972            let first_length = (metrics.floating_view_resize_handle_size * 0.56).max(6.0);
973            let second_length = (metrics.floating_view_resize_handle_size * 0.34).max(4.0);
974            let handle_inset = metrics.border_width.max(1.0);
975            let handle_stroke = metrics.border_width.max(1.0) + 0.5;
976            ctx.stroke(
977                diagonal_handle_path(handle, first_length, handle_inset),
978                accent,
979                StrokeStyle::new(handle_stroke),
980            );
981            ctx.stroke(
982                diagonal_handle_path(handle, second_length, handle_inset + theme.spacing),
983                accent.with_alpha(0.72),
984                StrokeStyle::new(handle_stroke),
985            );
986        }
987        ctx.pop_clip();
988    }
989
990    fn layer_options(&self) -> LayerOptions {
991        LayerOptions {
992            paint_boundary: PaintBoundaryMode::Explicit,
993            composition_mode: LayerCompositionMode::Normal,
994        }
995    }
996
997    fn semantics(&self, ctx: &mut SemanticsCtx) {
998        if let Some(view) = self.state.snapshot(self.view_id) {
999            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
1000            node.name = Some(view.title);
1001            ctx.push(node);
1002        }
1003        self.host.semantics(ctx);
1004    }
1005
1006    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1007        self.host.visit_children(visitor);
1008    }
1009
1010    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1011        self.host.visit_children_mut(visitor);
1012    }
1013}
1014
1015struct FloatingViewHost {
1016    theme: Box<DefaultTheme>,
1017    theme_reader: Option<ThemeReader>,
1018    state: FloatingWorkspaceState,
1019    view_id: u64,
1020    content: SingleChild,
1021    scroll_state: ScrollState,
1022    gutter: Size,
1023    vertical_scroll_bar: SingleChild,
1024    horizontal_scroll_bar: SingleChild,
1025}
1026
1027impl FloatingViewHost {
1028    fn new<W>(
1029        theme: DefaultTheme,
1030        theme_reader: Option<ThemeReader>,
1031        state: FloatingWorkspaceState,
1032        view_id: u64,
1033        child: W,
1034    ) -> Self
1035    where
1036        W: Widget + 'static,
1037    {
1038        let scroll_state = ScrollState::new();
1039        let scroll_view = ScrollView::both(child)
1040            .state(scroll_state.clone())
1041            .scroll_bars(false)
1042            .viewport_size_hint(true)
1043            .name("Floating view content");
1044        let vertical_scroll_bar = ScrollBar::vertical(scroll_state.clone());
1045        let vertical_scroll_bar = if let Some(theme_reader) = theme_reader.clone() {
1046            vertical_scroll_bar.theme_when(move || theme_reader())
1047        } else {
1048            vertical_scroll_bar.theme(theme)
1049        };
1050        let horizontal_scroll_bar = ScrollBar::horizontal(scroll_state.clone());
1051        let horizontal_scroll_bar = if let Some(theme_reader) = theme_reader.clone() {
1052            horizontal_scroll_bar.theme_when(move || theme_reader())
1053        } else {
1054            horizontal_scroll_bar.theme(theme)
1055        };
1056        Self {
1057            theme: Box::new(theme),
1058            theme_reader,
1059            state,
1060            view_id,
1061            vertical_scroll_bar: SingleChild::new(vertical_scroll_bar.name("Vertical scroll bar")),
1062            horizontal_scroll_bar: SingleChild::new(
1063                horizontal_scroll_bar.name("Horizontal scroll bar"),
1064            ),
1065            content: SingleChild::new(scroll_view),
1066            scroll_state,
1067            gutter: Size::ZERO,
1068        }
1069    }
1070
1071    fn resolved_theme(&self) -> DefaultTheme {
1072        self.theme_reader
1073            .as_ref()
1074            .map(|theme| theme())
1075            .unwrap_or(*self.theme)
1076    }
1077
1078    fn resizing(&self) -> bool {
1079        self.state.active_resize_view() == Some(self.view_id)
1080    }
1081}
1082
1083impl Widget for FloatingViewHost {
1084    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1085        let Some(view) = self.state.snapshot(self.view_id) else {
1086            return constraints.max;
1087        };
1088        let theme = self.resolved_theme();
1089        let outer = constraints.max;
1090        let probe = Rect::from_origin_size(Point::ZERO, outer);
1091        let content = floating_view_content_rect(&theme, probe, view.maximized);
1092        let thickness = theme.metrics.scroll_bar_thickness;
1093        self.gutter = Size::ZERO;
1094        for _ in 0..3 {
1095            let viewport = crate::containers::scroll_viewport_size(content.size, self.gutter);
1096            self.content.measure(ctx, Constraints::tight(viewport));
1097            let next = crate::containers::scroll_bar_gutter(
1098                true,
1099                crate::ScrollAxes::Both,
1100                content.size,
1101                self.scroll_state.content_size(),
1102                thickness,
1103            );
1104            if next == self.gutter {
1105                break;
1106            }
1107            self.gutter = next;
1108        }
1109        self.vertical_scroll_bar.measure(
1110            ctx,
1111            Constraints::tight(Size::new(thickness, content.height())),
1112        );
1113        self.horizontal_scroll_bar.measure(
1114            ctx,
1115            Constraints::tight(Size::new(content.width(), thickness)),
1116        );
1117        constraints.clamp(outer)
1118    }
1119
1120    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1121        let Some(view) = self.state.snapshot(self.view_id) else {
1122            return;
1123        };
1124        let theme = self.resolved_theme();
1125        let content = floating_view_content_rect(&theme, bounds, view.maximized);
1126        self.gutter = crate::containers::scroll_bar_gutter(
1127            true,
1128            crate::ScrollAxes::Both,
1129            content.size,
1130            self.scroll_state.content_size(),
1131            theme.metrics.scroll_bar_thickness,
1132        );
1133        let viewport = crate::containers::scroll_viewport_size(content.size, self.gutter);
1134        self.content
1135            .arrange(ctx, Rect::from_origin_size(content.origin, viewport));
1136        self.vertical_scroll_bar.arrange(
1137            ctx,
1138            Rect::new(
1139                content.x() + viewport.width,
1140                content.y(),
1141                self.gutter.width,
1142                viewport.height,
1143            ),
1144        );
1145        self.horizontal_scroll_bar.arrange(
1146            ctx,
1147            Rect::new(
1148                content.x(),
1149                content.y() + viewport.height,
1150                viewport.width,
1151                self.gutter.height,
1152            ),
1153        );
1154    }
1155
1156    fn paint(&self, ctx: &mut PaintCtx) {
1157        ctx.push_clip_rect(ctx.bounds());
1158        self.content.paint(ctx);
1159        if !self.resizing() {
1160            if self.gutter.width > 0.0 {
1161                self.vertical_scroll_bar.paint(ctx);
1162            }
1163            if self.gutter.height > 0.0 {
1164                self.horizontal_scroll_bar.paint(ctx);
1165            }
1166        }
1167        ctx.pop_clip();
1168    }
1169
1170    fn layer_options(&self) -> LayerOptions {
1171        LayerOptions {
1172            paint_boundary: PaintBoundaryMode::Explicit,
1173            composition_mode: if self.resizing() {
1174                LayerCompositionMode::Normal
1175            } else {
1176                LayerCompositionMode::Scroll
1177            },
1178        }
1179    }
1180
1181    fn stack_host_options(&self) -> Option<StackHostOptions> {
1182        Some(StackHostOptions::default())
1183    }
1184
1185    fn semantics(&self, ctx: &mut SemanticsCtx) {
1186        self.content.semantics(ctx);
1187        if !self.resizing() {
1188            if self.gutter.width > 0.0 {
1189                self.vertical_scroll_bar.semantics(ctx);
1190            }
1191            if self.gutter.height > 0.0 {
1192                self.horizontal_scroll_bar.semantics(ctx);
1193            }
1194        }
1195    }
1196
1197    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1198        self.content.visit_children(visitor);
1199        if self.gutter.width > 0.0 && !self.resizing() {
1200            self.vertical_scroll_bar.visit_children(visitor);
1201        }
1202        if self.gutter.height > 0.0 && !self.resizing() {
1203            self.horizontal_scroll_bar.visit_children(visitor);
1204        }
1205    }
1206
1207    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1208        self.content.visit_children_mut(visitor);
1209        if self.gutter.width > 0.0 && !self.resizing() {
1210            self.vertical_scroll_bar.visit_children_mut(visitor);
1211        }
1212        if self.gutter.height > 0.0 && !self.resizing() {
1213            self.horizontal_scroll_bar.visit_children_mut(visitor);
1214        }
1215    }
1216}
1217
1218#[derive(Debug, Clone, Copy, PartialEq)]
1219pub enum SplitExtent {
1220    Fraction(f32),
1221    Pixels(f32),
1222}
1223
1224impl SplitExtent {
1225    fn normalized(self) -> Self {
1226        match self {
1227            Self::Fraction(fraction) => Self::Fraction(fraction.clamp(0.0, 1.0)),
1228            Self::Pixels(pixels) => Self::Pixels(pixels.max(0.0)),
1229        }
1230    }
1231}
1232
1233impl Default for SplitExtent {
1234    fn default() -> Self {
1235        Self::Fraction(0.5)
1236    }
1237}
1238
1239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1240pub enum SplitPaneSide {
1241    First,
1242    Second,
1243}
1244
1245#[derive(Debug, Clone, Copy, PartialEq)]
1246pub struct SplitStateSnapshot {
1247    pub extent: SplitExtent,
1248    pub collapsed: Option<SplitPaneSide>,
1249    pub last_expanded_extent: SplitExtent,
1250}
1251
1252impl SplitStateSnapshot {
1253    pub fn new(extent: SplitExtent) -> Self {
1254        let extent = extent.normalized();
1255        Self {
1256            extent,
1257            collapsed: None,
1258            last_expanded_extent: extent,
1259        }
1260    }
1261}
1262
1263impl Default for SplitStateSnapshot {
1264    fn default() -> Self {
1265        Self::new(SplitExtent::default())
1266    }
1267}
1268
1269/// Cloneable, observable split-pane state.
1270///
1271/// Applications may persist [`Self::snapshot`] in their own settings system
1272/// and later restore it with [`Self::apply_snapshot`]. SUI owns no storage or
1273/// serialization policy.
1274#[derive(Clone, Debug)]
1275pub struct SplitState {
1276    snapshot: Signal<SplitStateSnapshot>,
1277}
1278
1279impl SplitState {
1280    pub fn new(extent: SplitExtent) -> Self {
1281        Self {
1282            snapshot: Signal::named("SplitState", SplitStateSnapshot::new(extent)),
1283        }
1284    }
1285
1286    pub fn fraction(fraction: f32) -> Self {
1287        Self::new(SplitExtent::Fraction(fraction))
1288    }
1289
1290    pub fn pixels(pixels: f32) -> Self {
1291        Self::new(SplitExtent::Pixels(pixels))
1292    }
1293
1294    pub fn snapshot(&self) -> SplitStateSnapshot {
1295        self.snapshot.get()
1296    }
1297
1298    pub fn apply_snapshot(&self, snapshot: SplitStateSnapshot) -> bool {
1299        let extent = snapshot.extent.normalized();
1300        let last_expanded_extent = snapshot.last_expanded_extent.normalized();
1301        self.snapshot.set(SplitStateSnapshot {
1302            extent,
1303            collapsed: snapshot.collapsed,
1304            last_expanded_extent,
1305        })
1306    }
1307
1308    pub fn set_extent(&self, extent: SplitExtent) -> bool {
1309        let extent = extent.normalized();
1310        self.snapshot.update(|snapshot| {
1311            snapshot.extent = extent;
1312            snapshot.last_expanded_extent = extent;
1313            snapshot.collapsed = None;
1314        })
1315    }
1316
1317    pub fn set_fraction(&self, fraction: f32) -> bool {
1318        self.set_extent(SplitExtent::Fraction(fraction))
1319    }
1320
1321    pub fn set_pixels(&self, pixels: f32) -> bool {
1322        self.set_extent(SplitExtent::Pixels(pixels))
1323    }
1324
1325    pub fn collapse(&self, side: SplitPaneSide) -> bool {
1326        self.snapshot.update(|snapshot| {
1327            if snapshot.collapsed.is_none() {
1328                snapshot.last_expanded_extent = snapshot.extent;
1329            }
1330            snapshot.collapsed = Some(side);
1331        })
1332    }
1333
1334    pub fn expand(&self) -> bool {
1335        self.snapshot.update(|snapshot| {
1336            if snapshot.collapsed.is_some() {
1337                snapshot.extent = snapshot.last_expanded_extent;
1338                snapshot.collapsed = None;
1339            }
1340        })
1341    }
1342
1343    pub fn toggle(&self, side: SplitPaneSide) -> bool {
1344        if self.snapshot().collapsed == Some(side) {
1345            self.expand()
1346        } else {
1347            self.collapse(side)
1348        }
1349    }
1350
1351    pub(crate) fn observable(&self) -> &Signal<SplitStateSnapshot> {
1352        &self.snapshot
1353    }
1354}
1355
1356impl Default for SplitState {
1357    fn default() -> Self {
1358        Self::new(SplitExtent::default())
1359    }
1360}
1361
1362pub struct SplitView {
1363    theme: Box<DefaultTheme>,
1364    theme_reader: Option<ThemeReader>,
1365    name: Option<String>,
1366    axis: Axis,
1367    state: SplitState,
1368    snapshot: SplitStateSnapshot,
1369    ratio: f32,
1370    min_first: f32,
1371    min_second: f32,
1372    divider_thickness: Option<f32>,
1373    first: SingleChild,
1374    second: SingleChild,
1375    hovered: bool,
1376    hover_animation: AnimatedScalar,
1377    drag_animation: AnimatedScalar,
1378    focus_animation: AnimatedScalar,
1379    drag_pointer: Option<u64>,
1380    divider_bounds: Rect,
1381    on_change: Option<Box<dyn FnMut(f32)>>,
1382    first_last_focus: Cell<Option<WidgetId>>,
1383    second_last_focus: Cell<Option<WidgetId>>,
1384    pending_focus_restore: Cell<Option<SplitPaneSide>>,
1385}
1386
1387impl SplitView {
1388    pub fn new<W1, W2>(axis: Axis, first: W1, second: W2) -> Self
1389    where
1390        W1: Widget + 'static,
1391        W2: Widget + 'static,
1392    {
1393        Self {
1394            theme: Box::new(DefaultTheme::default()),
1395            theme_reader: None,
1396            name: None,
1397            axis,
1398            state: SplitState::default(),
1399            snapshot: SplitStateSnapshot::default(),
1400            ratio: 0.5,
1401            min_first: 120.0,
1402            min_second: 120.0,
1403            divider_thickness: None,
1404            first: SingleChild::new(first),
1405            second: SingleChild::new(second),
1406            hovered: false,
1407            hover_animation: AnimatedScalar::new(0.0),
1408            drag_animation: AnimatedScalar::new(0.0),
1409            focus_animation: AnimatedScalar::new(0.0),
1410            drag_pointer: None,
1411            divider_bounds: Rect::ZERO,
1412            on_change: None,
1413            first_last_focus: Cell::new(None),
1414            second_last_focus: Cell::new(None),
1415            pending_focus_restore: Cell::new(None),
1416        }
1417    }
1418
1419    pub fn horizontal<W1, W2>(first: W1, second: W2) -> Self
1420    where
1421        W1: Widget + 'static,
1422        W2: Widget + 'static,
1423    {
1424        Self::new(Axis::Horizontal, first, second)
1425    }
1426
1427    pub fn vertical<W1, W2>(first: W1, second: W2) -> Self
1428    where
1429        W1: Widget + 'static,
1430        W2: Widget + 'static,
1431    {
1432        Self::new(Axis::Vertical, first, second)
1433    }
1434
1435    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1436        self.theme = Box::new(theme);
1437        self.theme_reader = None;
1438        self
1439    }
1440
1441    pub fn theme_when<F>(mut self, theme: F) -> Self
1442    where
1443        F: Fn() -> DefaultTheme + 'static,
1444    {
1445        self.theme_reader = Some(std::rc::Rc::new(theme));
1446        self
1447    }
1448
1449    pub fn name(mut self, name: impl Into<String>) -> Self {
1450        self.name = Some(name.into());
1451        self
1452    }
1453
1454    pub fn ratio(mut self, ratio: f32) -> Self {
1455        self.set_ratio(ratio);
1456        self
1457    }
1458
1459    pub fn extent(mut self, extent: SplitExtent) -> Self {
1460        self.set_extent(extent);
1461        self
1462    }
1463
1464    pub fn state(mut self, state: SplitState) -> Self {
1465        self.snapshot = state.snapshot();
1466        self.state = state;
1467        self.ratio = self.resolved_ratio_for_available(1.0);
1468        self
1469    }
1470
1471    pub fn split_state(&self) -> SplitState {
1472        self.state.clone()
1473    }
1474
1475    pub fn set_ratio(&mut self, ratio: f32) -> bool {
1476        self.set_extent(SplitExtent::Fraction(ratio))
1477    }
1478
1479    pub fn set_extent(&mut self, extent: SplitExtent) -> bool {
1480        let changed = self.state.set_extent(extent);
1481        self.snapshot = self.state.snapshot();
1482        if let SplitExtent::Fraction(ratio) = self.snapshot.extent {
1483            self.ratio = ratio;
1484        }
1485        changed
1486    }
1487
1488    pub fn min_first(mut self, min_first: f32) -> Self {
1489        self.min_first = min_first.max(0.0);
1490        self
1491    }
1492
1493    pub fn min_second(mut self, min_second: f32) -> Self {
1494        self.min_second = min_second.max(0.0);
1495        self
1496    }
1497
1498    pub fn divider_thickness(mut self, divider_thickness: f32) -> Self {
1499        self.divider_thickness = Some(divider_thickness.max(0.0));
1500        self
1501    }
1502
1503    pub fn on_change<F>(mut self, on_change: F) -> Self
1504    where
1505        F: FnMut(f32) + 'static,
1506    {
1507        self.on_change = Some(Box::new(on_change));
1508        self
1509    }
1510
1511    pub fn first(&self) -> &sui_runtime::WidgetPod {
1512        self.first.child()
1513    }
1514
1515    pub fn first_mut(&mut self) -> &mut sui_runtime::WidgetPod {
1516        self.first.child_mut()
1517    }
1518
1519    pub fn second(&self) -> &sui_runtime::WidgetPod {
1520        self.second.child()
1521    }
1522
1523    pub fn second_mut(&mut self) -> &mut sui_runtime::WidgetPod {
1524        self.second.child_mut()
1525    }
1526
1527    pub fn current_ratio(&self) -> f32 {
1528        self.ratio
1529    }
1530
1531    pub fn current_snapshot(&self) -> SplitStateSnapshot {
1532        self.state.snapshot()
1533    }
1534
1535    fn resolved_theme(&self) -> DefaultTheme {
1536        self.theme_reader
1537            .as_ref()
1538            .map(|theme| theme())
1539            .unwrap_or(*self.theme)
1540    }
1541
1542    fn resolved_divider_thickness(&self) -> f32 {
1543        let theme = self.resolved_theme();
1544        self.divider_thickness
1545            .unwrap_or(theme.metrics.split_view_divider_thickness)
1546            .max(theme.metrics.border_width.max(1.0))
1547    }
1548
1549    fn divider_rect(&self, bounds: Rect) -> Rect {
1550        self.divider_bounds.translate(bounds.origin.to_vector())
1551    }
1552
1553    fn divider_hit_rect(&self, bounds: Rect) -> Rect {
1554        let divider = self.divider_rect(bounds);
1555        let theme = self.resolved_theme();
1556        let target = theme
1557            .metrics
1558            .split_view_drag_target_thickness
1559            .max(self.resolved_divider_thickness());
1560        let extra = ((target - axis_main(self.axis, divider.size)).max(0.0)) * 0.5;
1561        let hit = match self.axis {
1562            Axis::Horizontal => divider.inflate(extra, 0.0),
1563            Axis::Vertical => divider.inflate(0.0, extra),
1564        };
1565
1566        hit.intersection(bounds).unwrap_or(divider)
1567    }
1568
1569    fn allowed_first_main_range(&self, available: f32) -> (f32, f32) {
1570        let available = available.max(0.0);
1571        let lower = self.min_first.min(available);
1572        let upper = (available - self.min_second).max(0.0);
1573
1574        if lower <= upper {
1575            (lower, upper)
1576        } else {
1577            (0.0, available)
1578        }
1579    }
1580
1581    fn divider_main_offset(&self, bounds: Rect) -> f32 {
1582        let divider = self.resolved_divider_thickness();
1583        let available = (axis_main(self.axis, bounds.size) - divider).max(0.0);
1584        match self.snapshot.collapsed {
1585            Some(SplitPaneSide::First) => return 0.0,
1586            Some(SplitPaneSide::Second) => return available,
1587            None => {}
1588        }
1589        let (lower, upper) = self.allowed_first_main_range(available);
1590        self.resolved_first_main(available).clamp(lower, upper)
1591    }
1592
1593    fn resolved_first_main(&self, available: f32) -> f32 {
1594        match self.snapshot.extent {
1595            SplitExtent::Fraction(fraction) => available * fraction,
1596            SplitExtent::Pixels(pixels) => pixels,
1597        }
1598    }
1599
1600    fn resolved_ratio_for_available(&self, available: f32) -> f32 {
1601        if available <= f32::EPSILON {
1602            return self.ratio.clamp(0.0, 1.0);
1603        }
1604        match self.snapshot.collapsed {
1605            Some(SplitPaneSide::First) => 0.0,
1606            Some(SplitPaneSide::Second) => 1.0,
1607            None => (self.resolved_first_main(available) / available).clamp(0.0, 1.0),
1608        }
1609    }
1610
1611    fn sync_snapshot(&mut self, snapshot: SplitStateSnapshot, available: Option<f32>) {
1612        let previous_collapsed = self.snapshot.collapsed;
1613        self.snapshot = snapshot;
1614        if previous_collapsed != self.snapshot.collapsed {
1615            match previous_collapsed {
1616                Some(SplitPaneSide::First)
1617                    if self.snapshot.collapsed != Some(SplitPaneSide::First) =>
1618                {
1619                    self.pending_focus_restore.set(Some(SplitPaneSide::First));
1620                }
1621                Some(SplitPaneSide::Second)
1622                    if self.snapshot.collapsed != Some(SplitPaneSide::Second) =>
1623                {
1624                    self.pending_focus_restore.set(Some(SplitPaneSide::Second));
1625                }
1626                _ => {}
1627            }
1628        }
1629        if let Some(available) = available {
1630            self.ratio = self.resolved_ratio_for_available(available);
1631        } else if let SplitExtent::Fraction(ratio) = self.snapshot.extent {
1632            self.ratio = ratio;
1633        }
1634    }
1635
1636    fn update_extent_from_first_main(&mut self, first_main: f32, available: f32) -> bool {
1637        let extent = match self.snapshot.extent {
1638            SplitExtent::Fraction(_) => SplitExtent::Fraction(if available <= f32::EPSILON {
1639                0.0
1640            } else {
1641                first_main / available
1642            }),
1643            SplitExtent::Pixels(_) => SplitExtent::Pixels(first_main),
1644        };
1645        let changed = self.state.set_extent(extent);
1646        self.sync_snapshot(self.state.snapshot(), Some(available));
1647        changed
1648    }
1649
1650    fn update_hover(&mut self, hovered: bool, ctx: &mut EventCtx) {
1651        if self.hovered != hovered {
1652            let theme = self.resolved_theme();
1653            self.hovered = hovered;
1654            set_hover_animation_target(
1655                &mut self.hover_animation,
1656                hovered as u8 as f32,
1657                &theme,
1658                ctx,
1659            );
1660            ctx.request_paint();
1661            ctx.request_semantics();
1662        }
1663    }
1664
1665    fn set_dragging(&mut self, dragging: bool, ctx: &mut EventCtx) {
1666        let theme = self.resolved_theme();
1667        set_press_animation_target(&mut self.drag_animation, dragging as u8 as f32, &theme, ctx);
1668        ctx.request_paint();
1669        ctx.request_semantics();
1670    }
1671
1672    fn advance_animations(&mut self, time: f64) -> bool {
1673        self.hover_animation.advance(time)
1674            | self.drag_animation.advance(time)
1675            | self.focus_animation.advance(time)
1676    }
1677
1678    fn set_ratio_from_position(&mut self, bounds: Rect, position: Point) {
1679        let divider = self.resolved_divider_thickness();
1680        let total = (axis_main(self.axis, bounds.size) - divider).max(0.0);
1681        if total <= 0.0 {
1682            return;
1683        }
1684
1685        let pointer_main = axis_position(self.axis, position) - axis_origin(self.axis, bounds);
1686        let (lower, upper) = self.allowed_first_main_range(total);
1687        let clamped = pointer_main.clamp(lower, upper);
1688        if self.update_extent_from_first_main(clamped, total)
1689            && let Some(on_change) = &mut self.on_change
1690        {
1691            on_change(self.ratio);
1692        }
1693    }
1694
1695    fn nudge_ratio(&mut self, delta: f32, available: f32) {
1696        let next = (self.ratio + delta).clamp(0.0, 1.0);
1697        self.set_first_main_and_notify(next * available, available);
1698    }
1699
1700    fn set_first_main_and_notify(&mut self, first_main: f32, available: f32) {
1701        if self.update_extent_from_first_main(first_main, available)
1702            && let Some(on_change) = &mut self.on_change
1703        {
1704            on_change(self.ratio);
1705        }
1706    }
1707
1708    fn remember_focus(&self, focused: Option<WidgetId>) {
1709        let Some(focused) = focused else {
1710            return;
1711        };
1712        if retained_subtree_contains(self.first.child(), focused) {
1713            self.first_last_focus.set(Some(focused));
1714        } else if retained_subtree_contains(self.second.child(), focused) {
1715            self.second_last_focus.set(Some(focused));
1716        }
1717    }
1718
1719    fn restore_pending_focus(&self, ctx: &mut EventCtx) {
1720        let Some(side) = self.pending_focus_restore.take() else {
1721            return;
1722        };
1723        let (pane, remembered) = match side {
1724            SplitPaneSide::First => (self.first.child(), self.first_last_focus.get()),
1725            SplitPaneSide::Second => (self.second.child(), self.second_last_focus.get()),
1726        };
1727        let target = remembered
1728            .filter(|target| retained_subtree_contains(pane, *target))
1729            .or_else(|| first_focusable_in(pane));
1730        if let Some(target) = target {
1731            ctx.request_focus_for(target);
1732            ctx.request_paint();
1733            ctx.request_semantics();
1734        }
1735    }
1736}
1737
1738impl Widget for SplitView {
1739    fn supports_output_reuse(&self) -> bool {
1740        self.theme_reader.is_none()
1741    }
1742    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1743        self.remember_focus(ctx.focused_widget_id());
1744        let divider = self.resolved_divider_thickness();
1745        let available = (axis_main(self.axis, ctx.bounds().size) - divider).max(0.0);
1746        self.sync_snapshot(self.state.snapshot(), Some(available));
1747        match event {
1748            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1749                if self.drag_pointer == Some(pointer.pointer_id) {
1750                    self.set_ratio_from_position(ctx.bounds(), pointer.position);
1751                    ctx.request_arrange();
1752                    ctx.request_paint();
1753                    ctx.request_semantics();
1754                    ctx.set_handled();
1755                } else if ctx.phase() != EventPhase::Capture {
1756                    self.update_hover(
1757                        self.divider_hit_rect(ctx.bounds())
1758                            .contains(pointer.position),
1759                        ctx,
1760                    );
1761                } else {
1762                    self.update_hover(false, ctx);
1763                }
1764            }
1765            Event::Pointer(pointer)
1766                if pointer.kind == PointerEventKind::Down
1767                    && ctx.phase() != EventPhase::Capture
1768                    && pointer.button == Some(PointerButton::Primary)
1769                    && self
1770                        .divider_hit_rect(ctx.bounds())
1771                        .contains(pointer.position) =>
1772            {
1773                self.drag_pointer = Some(pointer.pointer_id);
1774                self.update_hover(true, ctx);
1775                self.set_dragging(true, ctx);
1776                ctx.request_focus();
1777                ctx.request_pointer_capture(pointer.pointer_id);
1778                self.set_ratio_from_position(ctx.bounds(), pointer.position);
1779                ctx.request_arrange();
1780                ctx.set_handled();
1781            }
1782            Event::Pointer(pointer)
1783                if pointer.kind == PointerEventKind::Up
1784                    && pointer.button == Some(PointerButton::Primary)
1785                    && self.drag_pointer == Some(pointer.pointer_id) =>
1786            {
1787                self.drag_pointer = None;
1788                self.set_dragging(false, ctx);
1789                self.update_hover(
1790                    self.divider_hit_rect(ctx.bounds())
1791                        .contains(pointer.position),
1792                    ctx,
1793                );
1794                ctx.release_pointer_capture(pointer.pointer_id);
1795                ctx.set_handled();
1796            }
1797            Event::Pointer(pointer)
1798                if pointer.kind == PointerEventKind::Cancel
1799                    && self.drag_pointer == Some(pointer.pointer_id) =>
1800            {
1801                self.drag_pointer = None;
1802                self.set_dragging(false, ctx);
1803                self.update_hover(false, ctx);
1804                ctx.release_pointer_capture(pointer.pointer_id);
1805                ctx.set_handled();
1806            }
1807            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
1808                if self.drag_pointer.is_none() {
1809                    self.update_hover(false, ctx);
1810                }
1811            }
1812            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1813                let step = 0.05;
1814                let delta = match (self.axis, key.key.as_str()) {
1815                    (Axis::Horizontal, "ArrowLeft") | (Axis::Vertical, "ArrowUp") => -step,
1816                    (Axis::Horizontal, "ArrowRight") | (Axis::Vertical, "ArrowDown") => step,
1817                    (Axis::Horizontal, "Home") | (Axis::Vertical, "Home") => {
1818                        self.set_first_main_and_notify(0.0, available);
1819                        ctx.request_arrange();
1820                        ctx.request_paint();
1821                        ctx.request_semantics();
1822                        ctx.set_handled();
1823                        return;
1824                    }
1825                    (Axis::Horizontal, "End") | (Axis::Vertical, "End") => {
1826                        self.set_first_main_and_notify(available, available);
1827                        ctx.request_arrange();
1828                        ctx.request_paint();
1829                        ctx.request_semantics();
1830                        ctx.set_handled();
1831                        return;
1832                    }
1833                    _ => return,
1834                };
1835                self.nudge_ratio(delta, available);
1836                ctx.request_arrange();
1837                ctx.request_paint();
1838                ctx.request_semantics();
1839                ctx.set_handled();
1840            }
1841            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1842                self.restore_pending_focus(ctx);
1843                if self.advance_animations(*time) {
1844                    ctx.request_animation_frame();
1845                }
1846                ctx.request_paint();
1847            }
1848            _ => {}
1849        }
1850    }
1851
1852    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1853        let snapshot = ctx.observe(self.state.observable());
1854        self.sync_snapshot(snapshot, None);
1855        if self.pending_focus_restore.get().is_some() {
1856            ctx.request_animation_frame();
1857        }
1858        let divider = self.resolved_divider_thickness();
1859
1860        let probe_constraints = constraints.loosen();
1861        let first_probe = self.first.measure(ctx, probe_constraints);
1862        let second_probe = self.second.measure(ctx, probe_constraints);
1863        let natural = axis_size(
1864            self.axis,
1865            axis_main(self.axis, first_probe) + divider + axis_main(self.axis, second_probe),
1866            axis_cross(self.axis, first_probe).max(axis_cross(self.axis, second_probe)),
1867        );
1868
1869        let size = constraints.clamp(Size::new(
1870            if constraints.max.width.is_finite() {
1871                constraints.max.width
1872            } else {
1873                natural.width
1874            },
1875            if constraints.max.height.is_finite() {
1876                constraints.max.height
1877            } else {
1878                natural.height
1879            },
1880        ));
1881
1882        let total_main = axis_main(self.axis, size);
1883        self.sync_snapshot(snapshot, Some((total_main - divider).max(0.0)));
1884        let cross = axis_cross(self.axis, size);
1885        let divider_offset = self.divider_main_offset(Rect::from_origin_size(Point::ZERO, size));
1886        let first_main = divider_offset.max(0.0);
1887        let second_main = (total_main - divider - first_main).max(0.0);
1888        self.first
1889            .measure(ctx, split_child_constraints(self.axis, first_main, cross));
1890        self.second
1891            .measure(ctx, split_child_constraints(self.axis, second_main, cross));
1892
1893        size
1894    }
1895
1896    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1897        let divider = self.resolved_divider_thickness();
1898        let size = bounds.size;
1899
1900        let total_main = axis_main(self.axis, size);
1901        self.sync_snapshot(self.state.snapshot(), Some((total_main - divider).max(0.0)));
1902        let cross = axis_cross(self.axis, size);
1903        let divider_offset = self.divider_main_offset(Rect::from_origin_size(Point::ZERO, size));
1904        let first_main = divider_offset.max(0.0);
1905        let second_main = (total_main - divider - first_main).max(0.0);
1906        let first_constraints = split_child_constraints(self.axis, first_main, cross);
1907        let second_constraints = split_child_constraints(self.axis, second_main, cross);
1908        let first_size = first_constraints.clamp(self.first.child().measured_size());
1909        let second_size = second_constraints.clamp(self.second.child().measured_size());
1910
1911        self.first
1912            .arrange(ctx, Rect::from_origin_size(bounds.origin, first_size));
1913        let second_origin =
1914            bounds.origin + axis_point(self.axis, first_main + divider, 0.0).to_vector();
1915        self.second
1916            .arrange(ctx, Rect::from_origin_size(second_origin, second_size));
1917
1918        self.divider_bounds = Rect::from_origin_size(
1919            axis_point(self.axis, first_size_main(self.axis, first_size), 0.0),
1920            axis_size(self.axis, divider, cross),
1921        );
1922    }
1923
1924    fn paint(&self, ctx: &mut PaintCtx) {
1925        self.remember_focus(ctx.focused_widget_id());
1926        if self.snapshot.collapsed != Some(SplitPaneSide::First) {
1927            self.first.paint(ctx);
1928        }
1929        if self.snapshot.collapsed != Some(SplitPaneSide::Second) {
1930            self.second.paint(ctx);
1931        }
1932
1933        let theme = self.resolved_theme();
1934        let palette = theme.palette;
1935        let metrics = theme.metrics;
1936        let divider_bounds = self.divider_rect(ctx.bounds());
1937        let hover_color = mix_color(
1938            palette.border,
1939            palette.border_hover,
1940            self.hover_animation.value,
1941        );
1942        let focus_color = mix_color(
1943            hover_color,
1944            palette.border_focus,
1945            self.focus_animation.value,
1946        );
1947        let divider_color = mix_color(focus_color, palette.border_focus, self.drag_animation.value);
1948
1949        ctx.fill_rect(divider_bounds, divider_color);
1950        if self.resolved_divider_thickness() > metrics.border_width.max(1.0) {
1951            ctx.stroke_rect(
1952                divider_bounds,
1953                divider_color.with_alpha(0.72),
1954                StrokeStyle::new(metrics.border_width.max(1.0)),
1955            );
1956        }
1957    }
1958
1959    fn semantics(&self, ctx: &mut SemanticsCtx) {
1960        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Splitter, ctx.bounds());
1961        node.name = self.name.clone();
1962        node.state.focused = ctx.is_focused();
1963        node.value = Some(SemanticsValue::Number(self.ratio as f64));
1964        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
1965        ctx.push(node);
1966        self.remember_focus(ctx.focused_widget_id());
1967        if self.snapshot.collapsed != Some(SplitPaneSide::First) {
1968            self.first.semantics(ctx);
1969        }
1970        if self.snapshot.collapsed != Some(SplitPaneSide::Second) {
1971            self.second.semantics(ctx);
1972        }
1973    }
1974
1975    fn accepts_focus(&self) -> bool {
1976        true
1977    }
1978
1979    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1980        let theme = self.resolved_theme();
1981        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1982        ctx.request_paint();
1983        ctx.request_semantics();
1984    }
1985
1986    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1987        if self.snapshot.collapsed != Some(SplitPaneSide::First) {
1988            self.first.visit_children(visitor);
1989        }
1990        if self.snapshot.collapsed != Some(SplitPaneSide::Second) {
1991            self.second.visit_children(visitor);
1992        }
1993    }
1994
1995    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1996        if self.snapshot.collapsed != Some(SplitPaneSide::First) {
1997            self.first.visit_children_mut(visitor);
1998        }
1999        if self.snapshot.collapsed != Some(SplitPaneSide::Second) {
2000            self.second.visit_children_mut(visitor);
2001        }
2002    }
2003}
2004
2005struct FloatingWindowEntry {
2006    bounds: Rect,
2007    child: WidgetPod,
2008}
2009
2010struct FloatingStackSurface {
2011    host: SingleChild,
2012}
2013
2014impl FloatingStackSurface {
2015    fn new<W>(child: W) -> Self
2016    where
2017        W: Widget + 'static,
2018    {
2019        Self {
2020            host: SingleChild::new(child),
2021        }
2022    }
2023}
2024
2025impl Widget for FloatingStackSurface {
2026    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2027        self.host.measure(ctx, constraints)
2028    }
2029
2030    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2031        self.host.arrange(ctx, bounds);
2032    }
2033
2034    fn paint(&self, ctx: &mut PaintCtx) {
2035        self.host.paint(ctx);
2036    }
2037
2038    fn layer_options(&self) -> LayerOptions {
2039        LayerOptions {
2040            paint_boundary: PaintBoundaryMode::Explicit,
2041            composition_mode: LayerCompositionMode::Normal,
2042        }
2043    }
2044
2045    fn semantics(&self, ctx: &mut SemanticsCtx) {
2046        self.host.semantics(ctx);
2047    }
2048
2049    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2050        self.host.visit_children(visitor);
2051    }
2052
2053    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2054        self.host.visit_children_mut(visitor);
2055    }
2056}
2057
2058pub struct FloatingStack {
2059    theme: Box<DefaultTheme>,
2060    name: Option<String>,
2061    windows: Vec<FloatingWindowEntry>,
2062}
2063
2064impl FloatingStack {
2065    pub fn new() -> Self {
2066        Self {
2067            theme: Box::new(DefaultTheme::default()),
2068            name: None,
2069            windows: Vec::new(),
2070        }
2071    }
2072
2073    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2074        self.theme = Box::new(theme);
2075        self
2076    }
2077
2078    pub fn name(mut self, name: impl Into<String>) -> Self {
2079        self.name = Some(name.into());
2080        self
2081    }
2082
2083    pub fn with_window<W>(mut self, bounds: Rect, child: W) -> Self
2084    where
2085        W: Widget + 'static,
2086    {
2087        self.push_window(bounds, child);
2088        self
2089    }
2090
2091    pub fn push_window<W>(&mut self, bounds: Rect, child: W)
2092    where
2093        W: Widget + 'static,
2094    {
2095        self.windows.push(FloatingWindowEntry {
2096            bounds,
2097            child: WidgetPod::new(FloatingStackSurface::new(child)),
2098        });
2099    }
2100
2101    pub fn len(&self) -> usize {
2102        self.windows.len()
2103    }
2104
2105    pub fn is_empty(&self) -> bool {
2106        self.windows.is_empty()
2107    }
2108
2109    fn frontmost_window_at(&self, host_bounds: Rect, position: Point) -> Option<usize> {
2110        self.windows
2111            .iter()
2112            .enumerate()
2113            .rev()
2114            .find_map(|(index, entry)| {
2115                entry
2116                    .bounds
2117                    .translate(host_bounds.origin.to_vector())
2118                    .contains(position)
2119                    .then_some(index)
2120            })
2121    }
2122
2123    fn bring_to_front(&mut self, index: usize) -> bool {
2124        if index >= self.windows.len() || index + 1 == self.windows.len() {
2125            return false;
2126        }
2127
2128        let entry = self.windows.remove(index);
2129        self.windows.push(entry);
2130        true
2131    }
2132
2133    fn content_rect(&self) -> Rect {
2134        self.windows
2135            .iter()
2136            .fold(Rect::ZERO, |current, entry| current.union(entry.bounds))
2137    }
2138}
2139
2140impl Default for FloatingStack {
2141    fn default() -> Self {
2142        Self::new()
2143    }
2144}
2145
2146impl Widget for FloatingStack {
2147    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2148        if let Event::Pointer(pointer) = event
2149            && pointer.kind == PointerEventKind::Down
2150            && pointer.button == Some(PointerButton::Primary)
2151            && let Some(index) = self.frontmost_window_at(ctx.bounds(), pointer.position)
2152            && self.bring_to_front(index)
2153        {
2154            ctx.request_ordering();
2155            ctx.request_paint();
2156            ctx.request_hit_test();
2157        }
2158    }
2159
2160    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2161        for entry in self.windows.iter_mut() {
2162            entry
2163                .child
2164                .measure(ctx, Constraints::tight(entry.bounds.size));
2165        }
2166
2167        let content = self.content_rect();
2168        constraints.clamp(Size::new(
2169            content.max_x().max(0.0),
2170            content.max_y().max(0.0),
2171        ))
2172    }
2173
2174    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2175        for entry in self.windows.iter_mut() {
2176            entry
2177                .child
2178                .arrange(ctx, entry.bounds.translate(bounds.origin.to_vector()));
2179        }
2180    }
2181
2182    fn paint(&self, ctx: &mut PaintCtx) {
2183        for entry in &self.windows {
2184            entry.child.paint(ctx);
2185        }
2186    }
2187
2188    fn stack_host_options(&self) -> Option<StackHostOptions> {
2189        Some(StackHostOptions {
2190            order_policy: StackOrderPolicy::FocusFronted,
2191        })
2192    }
2193
2194    fn semantics(&self, ctx: &mut SemanticsCtx) {
2195        let mut node = SemanticsNode::new(
2196            ctx.widget_id(),
2197            SemanticsRole::GenericContainer,
2198            self.content_rect()
2199                .translate(ctx.bounds().origin.to_vector()),
2200        );
2201        node.name = self.name.clone();
2202        node.state.focused = ctx.is_focused();
2203        ctx.push(node);
2204
2205        for entry in &self.windows {
2206            entry.child.semantics(ctx);
2207        }
2208    }
2209
2210    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2211        for entry in &self.windows {
2212            visitor.visit(&entry.child);
2213        }
2214    }
2215
2216    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2217        for entry in &mut self.windows {
2218            visitor.visit(&mut entry.child);
2219        }
2220    }
2221}
2222
2223fn split_child_constraints(axis: Axis, main: f32, cross: f32) -> Constraints {
2224    match axis {
2225        Axis::Horizontal => Constraints::tight(Size::new(main.max(0.0), cross.max(0.0))),
2226        Axis::Vertical => Constraints::tight(Size::new(cross.max(0.0), main.max(0.0))),
2227    }
2228}
2229
2230fn axis_main(axis: Axis, size: Size) -> f32 {
2231    match axis {
2232        Axis::Horizontal => size.width,
2233        Axis::Vertical => size.height,
2234    }
2235}
2236
2237fn axis_cross(axis: Axis, size: Size) -> f32 {
2238    match axis {
2239        Axis::Horizontal => size.height,
2240        Axis::Vertical => size.width,
2241    }
2242}
2243
2244fn axis_size(axis: Axis, main: f32, cross: f32) -> Size {
2245    match axis {
2246        Axis::Horizontal => Size::new(main, cross),
2247        Axis::Vertical => Size::new(cross, main),
2248    }
2249}
2250
2251fn axis_point(axis: Axis, main: f32, cross: f32) -> Point {
2252    match axis {
2253        Axis::Horizontal => Point::new(main, cross),
2254        Axis::Vertical => Point::new(cross, main),
2255    }
2256}
2257
2258fn axis_position(axis: Axis, point: Point) -> f32 {
2259    match axis {
2260        Axis::Horizontal => point.x,
2261        Axis::Vertical => point.y,
2262    }
2263}
2264
2265fn axis_origin(axis: Axis, rect: Rect) -> f32 {
2266    match axis {
2267        Axis::Horizontal => rect.x(),
2268        Axis::Vertical => rect.y(),
2269    }
2270}
2271
2272fn first_size_main(axis: Axis, size: Size) -> f32 {
2273    axis_main(axis, size)
2274}
2275
2276fn floating_view_title_bar_height(theme: &DefaultTheme) -> f32 {
2277    theme.metrics.floating_view_title_bar_height
2278}
2279
2280fn floating_view_title_bar_rect(theme: &DefaultTheme, bounds: Rect) -> Rect {
2281    Rect::new(
2282        bounds.x(),
2283        bounds.y(),
2284        bounds.width(),
2285        floating_view_title_bar_height(theme).min(bounds.height()),
2286    )
2287}
2288
2289fn floating_view_content_rect(theme: &DefaultTheme, bounds: Rect, maximized: bool) -> Rect {
2290    if maximized {
2291        return bounds;
2292    }
2293
2294    let border = theme.metrics.border_width.max(1.0);
2295    let title_height = floating_view_title_bar_height(theme);
2296    Rect::new(
2297        bounds.x() + border,
2298        bounds.y() + title_height,
2299        (bounds.width() - (border * 2.0)).max(0.0),
2300        (bounds.height() - title_height - border).max(0.0),
2301    )
2302}
2303
2304fn floating_view_resize_handle_rect(theme: &DefaultTheme, bounds: Rect) -> Rect {
2305    let size = theme.metrics.floating_view_resize_handle_size;
2306    Rect::new(bounds.max_x() - size, bounds.max_y() - size, size, size)
2307}
2308
2309fn clamp_floating_view_bounds(
2310    theme: &DefaultTheme,
2311    host_bounds: Rect,
2312    bounds: Rect,
2313    min_size: Size,
2314) -> Rect {
2315    let title_height = floating_view_title_bar_height(theme);
2316    let max_width = host_bounds.width().max(0.0);
2317    let max_height = host_bounds.height().max(0.0);
2318    let width = bounds.width().clamp(
2319        min_size.width.min(max_width),
2320        max_width.max(min_size.width.min(max_width)),
2321    );
2322    let height = bounds.height().clamp(
2323        min_size.height.min(max_height),
2324        max_height.max(min_size.height.min(max_height)),
2325    );
2326    let min_visible_width = width.min(56.0);
2327    let min_visible_height = height.min(title_height.max(32.0));
2328    let max_x = (host_bounds.max_x() - min_visible_width).max(host_bounds.x());
2329    let max_y = (host_bounds.max_y() - min_visible_height).max(host_bounds.y());
2330    Rect::new(
2331        bounds.x().clamp(host_bounds.x(), max_x),
2332        bounds.y().clamp(host_bounds.y(), max_y),
2333        width,
2334        height,
2335    )
2336}
2337
2338fn resolved_floating_view_bounds(
2339    theme: &DefaultTheme,
2340    host_bounds: Rect,
2341    view: &FloatingViewSnapshot,
2342) -> Rect {
2343    if view.maximized {
2344        host_bounds
2345    } else {
2346        clamp_floating_view_bounds(theme, host_bounds, view.bounds, view.min_size)
2347    }
2348}
2349
2350fn diagonal_handle_path(bounds: Rect, inset: f32, offset: f32) -> sui_core::Path {
2351    let start = Point::new(bounds.max_x() - inset, bounds.max_y() - offset);
2352    let end = Point::new(bounds.max_x() - offset, bounds.max_y() - inset);
2353    let mut builder = sui_core::PathBuilder::new();
2354    builder.move_to(start);
2355    builder.line_to(end);
2356    builder.build()
2357}
2358
2359fn request_widget_refresh(
2360    ctx: &mut EventCtx,
2361    widget_id: WidgetId,
2362    include_measure: bool,
2363    include_ordering: bool,
2364    region: Rect,
2365) {
2366    let target = InvalidationTarget::Widget(widget_id);
2367    if include_measure {
2368        ctx.request(
2369            InvalidationRequest::new(target, InvalidationKind::Measure).with_region(region),
2370        );
2371    } else {
2372        ctx.request(
2373            InvalidationRequest::new(target, InvalidationKind::Arrange).with_region(region),
2374        );
2375    }
2376    if include_ordering {
2377        ctx.request(
2378            InvalidationRequest::new(target, InvalidationKind::Ordering).with_region(region),
2379        );
2380    }
2381    ctx.request(InvalidationRequest::new(target, InvalidationKind::Paint).with_region(region));
2382    ctx.request(InvalidationRequest::new(target, InvalidationKind::HitTest).with_region(region));
2383    ctx.request(InvalidationRequest::new(target, InvalidationKind::Semantics).with_region(region));
2384}
2385
2386fn widget_invalidation_region(
2387    invalidations: &[InvalidationRequest],
2388    widget_id: WidgetId,
2389) -> Option<Rect> {
2390    invalidations
2391        .iter()
2392        .filter(|request| matches!(request.target, InvalidationTarget::Widget(target) if target == widget_id))
2393        .filter(|request| {
2394            matches!(
2395                request.kind,
2396                InvalidationKind::Measure
2397                    | InvalidationKind::Arrange
2398                    | InvalidationKind::Ordering
2399                    | InvalidationKind::Transform
2400                    | InvalidationKind::Clip
2401                    | InvalidationKind::Effect
2402                    | InvalidationKind::Visibility
2403                    | InvalidationKind::Paint
2404            )
2405        })
2406        .filter_map(|request| request.region)
2407        .reduce(|current, next| current.union(next))
2408}
2409
2410#[cfg(test)]
2411mod tests {
2412    use std::{cell::RefCell, rc::Rc};
2413
2414    use super::{
2415        FloatingStack, FloatingViewConfig, FloatingWorkspace, FloatingWorkspaceState, SplitExtent,
2416        SplitPaneSide, SplitState, SplitStateSnapshot, SplitView,
2417    };
2418    use crate::DefaultTheme;
2419    use crate::containers::SizedBox;
2420    use sui_core::{
2421        Color, Event, KeyState, KeyboardEvent, Point, PointerButton, PointerButtons, PointerEvent,
2422        PointerEventKind, Rect, Result, ScrollDelta, SemanticsActionRequest, SemanticsNode,
2423        SemanticsRole, SemanticsValue, Size, Vector, WidgetId, WindowEvent,
2424    };
2425    use sui_layout::{Axis, Constraints};
2426    use sui_render_wgpu::{RgbaImage, WgpuRenderer};
2427    use sui_runtime::{
2428        Application, EventCtx, MeasureCtx, PaintCtx, RenderOutput, Runtime, SemanticsCtx,
2429        StackOrderPolicy, Widget, WindowBuilder,
2430    };
2431    use sui_scene::{Brush, SceneCommand, SceneLayerUpdateKind};
2432    use sui_text::{FontRegistry, TextSystem};
2433
2434    struct ColorFill {
2435        color: Color,
2436    }
2437
2438    #[test]
2439    fn split_state_snapshot_round_trips_extent_and_collapse_state() {
2440        let state = SplitState::pixels(312.0);
2441        assert!(state.collapse(SplitPaneSide::First));
2442        let persisted = state.snapshot();
2443        assert_eq!(persisted.extent, SplitExtent::Pixels(312.0));
2444        assert_eq!(persisted.collapsed, Some(SplitPaneSide::First));
2445
2446        let restored = SplitState::default();
2447        assert!(restored.apply_snapshot(persisted));
2448        assert_eq!(restored.snapshot(), persisted);
2449        assert!(restored.expand());
2450        assert_eq!(
2451            restored.snapshot(),
2452            SplitStateSnapshot {
2453                extent: SplitExtent::Pixels(312.0),
2454                collapsed: None,
2455                last_expanded_extent: SplitExtent::Pixels(312.0),
2456            }
2457        );
2458    }
2459
2460    #[test]
2461    fn split_view_restores_focus_after_collapsed_pane_expands() -> Result<()> {
2462        let state = SplitState::fraction(0.5);
2463        let (mut runtime, window_id) = build_runtime(
2464            SizedBox::new().width(420.0).height(180.0).with_child(
2465                SplitView::horizontal(
2466                    crate::Button::new("First action"),
2467                    crate::Button::new("Second action"),
2468                )
2469                .state(state.clone()),
2470            ),
2471        );
2472
2473        let first_id = runtime
2474            .render(window_id)?
2475            .semantics
2476            .into_iter()
2477            .find(|node| node.name.as_deref() == Some("First action"))
2478            .expect("first pane action present")
2479            .id;
2480        assert!(runtime.handle_semantics_action(
2481            window_id,
2482            first_id,
2483            SemanticsActionRequest::Focus,
2484        )?);
2485        let _ = runtime.render(window_id)?;
2486
2487        state.collapse(SplitPaneSide::First);
2488        let collapsed = runtime.render(window_id)?;
2489        assert!(!collapsed.semantics.iter().any(|node| node.id == first_id));
2490        assert_eq!(runtime.focused_widget(window_id)?, None);
2491
2492        state.expand();
2493        let expanded = runtime.render(window_id)?;
2494        assert!(expanded.semantics.iter().any(|node| node.id == first_id));
2495        for (ready_window, event) in runtime.drain_ready_events() {
2496            runtime.handle_event(ready_window, event)?;
2497        }
2498        assert_eq!(runtime.focused_widget(window_id)?, Some(first_id));
2499        Ok(())
2500    }
2501
2502    impl ColorFill {
2503        fn new(color: Color) -> Self {
2504            Self { color }
2505        }
2506    }
2507
2508    impl Widget for ColorFill {
2509        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: sui_layout::Constraints) -> Size {
2510            constraints.max
2511        }
2512
2513        fn paint(&self, ctx: &mut PaintCtx) {
2514            ctx.fill_bounds(self.color);
2515        }
2516    }
2517
2518    struct ConstraintProbe {
2519        name: String,
2520        desired: Size,
2521        color: Color,
2522        seen: Rc<RefCell<Vec<Constraints>>>,
2523    }
2524
2525    impl ConstraintProbe {
2526        fn new(
2527            name: impl Into<String>,
2528            desired: Size,
2529            color: Color,
2530            seen: Rc<RefCell<Vec<Constraints>>>,
2531        ) -> Self {
2532            Self {
2533                name: name.into(),
2534                desired,
2535                color,
2536                seen,
2537            }
2538        }
2539    }
2540
2541    impl Widget for ConstraintProbe {
2542        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2543            self.seen.borrow_mut().push(constraints);
2544            self.desired
2545        }
2546
2547        fn paint(&self, ctx: &mut PaintCtx) {
2548            ctx.fill_bounds(self.color);
2549        }
2550
2551        fn semantics(&self, ctx: &mut SemanticsCtx) {
2552            let mut node = SemanticsNode::new(
2553                ctx.widget_id(),
2554                SemanticsRole::GenericContainer,
2555                ctx.bounds(),
2556            );
2557            node.name = Some(self.name.clone());
2558            ctx.push(node);
2559        }
2560    }
2561
2562    struct PointerDownProbe {
2563        name: String,
2564        desired: Size,
2565        seen: Rc<RefCell<Vec<String>>>,
2566    }
2567
2568    impl PointerDownProbe {
2569        fn new(name: impl Into<String>, seen: Rc<RefCell<Vec<String>>>) -> Self {
2570            Self {
2571                name: name.into(),
2572                desired: Size::new(100.0, 40.0),
2573                seen,
2574            }
2575        }
2576    }
2577
2578    impl Widget for PointerDownProbe {
2579        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2580            if matches!(
2581                event,
2582                Event::Pointer(pointer)
2583                    if pointer.kind == PointerEventKind::Down
2584                        && pointer.button == Some(PointerButton::Primary)
2585            ) {
2586                self.seen.borrow_mut().push("down".to_string());
2587                ctx.set_handled();
2588            }
2589        }
2590
2591        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2592            constraints.clamp(self.desired)
2593        }
2594
2595        fn paint(&self, ctx: &mut PaintCtx) {
2596            ctx.fill_bounds(Color::rgba(0.16, 0.36, 0.72, 1.0));
2597        }
2598
2599        fn semantics(&self, ctx: &mut SemanticsCtx) {
2600            let mut node = SemanticsNode::new(
2601                ctx.widget_id(),
2602                SemanticsRole::GenericContainer,
2603                ctx.bounds(),
2604            );
2605            node.name = Some(self.name.clone());
2606            ctx.push(node);
2607        }
2608    }
2609
2610    fn build_runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
2611    where
2612        W: Widget + 'static,
2613    {
2614        let runtime = Application::new()
2615            .window(WindowBuilder::new().title("SplitView").root(root))
2616            .build()
2617            .unwrap();
2618        let window_id = runtime.window_ids()[0];
2619        (runtime, window_id)
2620    }
2621
2622    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
2623        let mut buttons = PointerButtons::NONE;
2624        if pressed {
2625            buttons.insert(PointerButton::Primary);
2626        }
2627
2628        Event::Pointer(PointerEvent {
2629            pointer_id: 1,
2630            kind,
2631            position,
2632            delta: Vector::ZERO,
2633            scroll_delta: None,
2634            button: Some(PointerButton::Primary),
2635            buttons,
2636            modifiers: sui_core::Modifiers::NONE,
2637            pointer_kind: sui_core::PointerKind::Mouse,
2638            is_primary: true,
2639        })
2640    }
2641
2642    fn handle_ready_events(runtime: &mut Runtime) -> Result<usize> {
2643        let ready = runtime.drain_ready_events();
2644        let count = ready.len();
2645        for (window_id, event) in ready {
2646            runtime.handle_event(window_id, event)?;
2647        }
2648        Ok(count)
2649    }
2650
2651    fn solid_fill_colors(output: &RenderOutput) -> Vec<Color> {
2652        let mut colors = Vec::new();
2653        output.frame.scene.visit_commands(&mut |command| {
2654            if let SceneCommand::FillRect {
2655                brush: Brush::Solid(color),
2656                ..
2657            }
2658            | SceneCommand::FillPath {
2659                brush: Brush::Solid(color),
2660                ..
2661            } = command
2662            {
2663                colors.push(*color);
2664            }
2665        });
2666        colors
2667    }
2668
2669    fn contains_approx_color(colors: &[Color], expected: Color) -> bool {
2670        const CHANNEL_TOLERANCE: f32 = 1.0 / 255.0;
2671
2672        colors.iter().any(|color| {
2673            color.space == expected.space
2674                && (color.red - expected.red).abs() <= CHANNEL_TOLERANCE
2675                && (color.green - expected.green).abs() <= CHANNEL_TOLERANCE
2676                && (color.blue - expected.blue).abs() <= CHANNEL_TOLERANCE
2677                && (color.alpha - expected.alpha).abs() <= CHANNEL_TOLERANCE
2678        })
2679    }
2680
2681    fn render_rgba(
2682        runtime: &mut Runtime,
2683        renderer: &mut WgpuRenderer,
2684        window_id: sui_core::WindowId,
2685    ) -> Result<(RenderOutput, RgbaImage)> {
2686        let output = runtime.render(window_id)?;
2687        renderer.render(&output.frame)?;
2688        let image = renderer.capture_last_frame_rgba(window_id)?;
2689        Ok((output, image))
2690    }
2691
2692    fn rgba_pixel(image: &RgbaImage, x: u32, y: u32) -> [u8; 4] {
2693        let index = ((y as usize * image.width() as usize) + x as usize) * 4;
2694        let pixels = image.pixels();
2695        [
2696            pixels[index],
2697            pixels[index + 1],
2698            pixels[index + 2],
2699            pixels[index + 3],
2700        ]
2701    }
2702
2703    fn text_run_for(output: &RenderOutput, text: &str) -> sui_text::TextRun {
2704        let mut found = None;
2705        output.frame.scene.visit_commands(&mut |command| {
2706            if found.is_some() {
2707                return;
2708            }
2709            found = match command {
2710                SceneCommand::DrawText(run) if run.text == text => Some(run.clone()),
2711                SceneCommand::DrawShapedText(run) => run
2712                    .resolve(output.frame.text_layout_registry.as_ref())
2713                    .filter(|layout| layout.text() == text)
2714                    .map(|layout| {
2715                        let measurement = layout.measurement();
2716                        let bounds = measurement.bounds;
2717                        let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
2718                            bounds.width()
2719                        } else {
2720                            measurement.width
2721                        };
2722                        let mut style = layout.style().clone();
2723                        if let Some(color) = run.color_override {
2724                            style.color = color;
2725                        }
2726                        sui_text::TextRun {
2727                            rect: Rect::new(
2728                                run.origin.x + bounds.x(),
2729                                run.origin.y
2730                                    + ((layout.box_size().height - measurement.height).max(0.0)
2731                                        * 0.5),
2732                                width,
2733                                layout.style().line_height.max(measurement.height),
2734                            ),
2735                            text: layout.text().to_string(),
2736                            style,
2737                        }
2738                    }),
2739                _ => None,
2740            };
2741        });
2742        found.expect("text draw command present")
2743    }
2744
2745    fn optical_visual_center(measurement: sui_text::TextMeasurement) -> f32 {
2746        let top = -measurement.cap_height.unwrap_or(measurement.ascent);
2747        let bottom = measurement.descent * 0.5;
2748        (top + bottom) * 0.5
2749    }
2750
2751    fn text_run_layout(run: &sui_text::TextRun) -> sui_text::TextLayout {
2752        TextSystem::new()
2753            .shape_text(
2754                run.text.clone(),
2755                Size::new(f32::INFINITY, run.rect.height().max(1.0)),
2756                run.style.clone(),
2757                &FontRegistry::new(),
2758            )
2759            .expect("text run should shape")
2760    }
2761
2762    fn scene_layer_widget_ids(scene: &sui_scene::Scene) -> Vec<WidgetId> {
2763        scene
2764            .commands()
2765            .iter()
2766            .filter_map(|command| match command {
2767                SceneCommand::Layer(layer) => Some(layer.widget_id()),
2768                _ => None,
2769            })
2770            .collect()
2771    }
2772
2773    #[test]
2774    fn split_view_drag_updates_ratio_and_semantics() -> Result<()> {
2775        let changes = Rc::new(RefCell::new(Vec::new()));
2776        let on_change = Rc::clone(&changes);
2777        let (mut runtime, window_id) = build_runtime(
2778            SplitView::new(
2779                Axis::Horizontal,
2780                SizedBox::new().width(100.0).height(40.0),
2781                SizedBox::new().width(100.0).height(40.0),
2782            )
2783            .name("Editor split")
2784            .min_first(40.0)
2785            .min_second(40.0)
2786            .on_change(move |ratio| on_change.borrow_mut().push(ratio)),
2787        );
2788
2789        let _ = runtime.render(window_id)?;
2790        runtime.handle_event(
2791            window_id,
2792            primary_pointer(PointerEventKind::Down, Point::new(105.0, 20.0), true),
2793        )?;
2794        runtime.handle_event(
2795            window_id,
2796            primary_pointer(PointerEventKind::Move, Point::new(145.0, 20.0), true),
2797        )?;
2798        runtime.handle_event(
2799            window_id,
2800            primary_pointer(PointerEventKind::Up, Point::new(145.0, 20.0), false),
2801        )?;
2802
2803        assert!(changes.borrow().last().is_some_and(|ratio| *ratio > 0.65));
2804
2805        let output = runtime.render(window_id)?;
2806        let splitter = output
2807            .semantics
2808            .iter()
2809            .find(|node| node.role == SemanticsRole::Splitter)
2810            .expect("splitter semantics present");
2811        assert_eq!(splitter.name.as_deref(), Some("Editor split"));
2812        assert!(matches!(
2813            splitter.value,
2814            Some(SemanticsValue::Number(value)) if value > 0.65
2815        ));
2816        Ok(())
2817    }
2818
2819    #[test]
2820    fn split_view_theme_when_reads_current_theme_for_divider() -> Result<()> {
2821        let mut light = DefaultTheme::default();
2822        light.palette.border = Color::rgba(0.18, 0.27, 0.36, 1.0);
2823        let mut dark = light;
2824        dark.palette.border = Color::rgba(0.74, 0.42, 0.16, 1.0);
2825
2826        let theme = Rc::new(RefCell::new(light));
2827        let theme_reader = Rc::clone(&theme);
2828        let (mut runtime, window_id) = build_runtime(
2829            SplitView::new(
2830                Axis::Horizontal,
2831                SizedBox::new().width(100.0).height(40.0),
2832                SizedBox::new().width(100.0).height(40.0),
2833            )
2834            .theme_when(move || *theme_reader.borrow())
2835            .min_first(40.0)
2836            .min_second(40.0),
2837        );
2838
2839        let light_output = runtime.render(window_id)?;
2840        let light_fills = solid_fill_colors(&light_output);
2841        assert!(
2842            contains_approx_color(&light_fills, light.palette.border),
2843            "split divider should use the initial theme border; fills={light_fills:?}"
2844        );
2845
2846        *theme.borrow_mut() = dark;
2847        runtime.handle_event(
2848            window_id,
2849            Event::Window(WindowEvent::Resized(Size::new(640.0, 180.0))),
2850        )?;
2851        let dark_output = runtime.render(window_id)?;
2852        let dark_fills = solid_fill_colors(&dark_output);
2853        assert!(
2854            contains_approx_color(&dark_fills, dark.palette.border),
2855            "split divider should use the current theme border after repaint; fills={dark_fills:?}"
2856        );
2857        assert!(
2858            !contains_approx_color(&dark_fills, light.palette.border),
2859            "split divider should not keep the stale theme border after repaint"
2860        );
2861        Ok(())
2862    }
2863
2864    #[test]
2865    fn split_view_divider_hover_and_drag_use_theme_motion() -> Result<()> {
2866        let theme = DefaultTheme::default();
2867        let hover_duration = theme.motion.hover_duration();
2868        let press_duration = theme.motion.press_duration();
2869        let expected_hover = theme.palette.border_hover;
2870        let expected_drag = theme.palette.border_focus;
2871        let divider_x = 100.0 + theme.metrics.split_view_divider_thickness * 0.5;
2872        let divider_point = Point::new(divider_x, 20.0);
2873        let (mut runtime, window_id) = build_runtime(
2874            SplitView::new(
2875                Axis::Horizontal,
2876                SizedBox::new().width(100.0).height(40.0),
2877                SizedBox::new().width(100.0).height(40.0),
2878            )
2879            .theme(theme)
2880            .min_first(40.0)
2881            .min_second(40.0),
2882        );
2883
2884        runtime.render(window_id)?;
2885        runtime.handle_event(
2886            window_id,
2887            primary_pointer(PointerEventKind::Move, divider_point, false),
2888        )?;
2889        runtime.tick(hover_duration * 0.5);
2890        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2891        let mid_hover = runtime.render(window_id)?;
2892        assert!(
2893            !solid_fill_colors(&mid_hover).contains(&expected_hover),
2894            "split divider hover should not snap to the settled hover color"
2895        );
2896
2897        runtime.tick(hover_duration);
2898        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2899        let settled_hover = runtime.render(window_id)?;
2900        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
2901
2902        runtime.handle_event(
2903            window_id,
2904            primary_pointer(PointerEventKind::Down, divider_point, true),
2905        )?;
2906        runtime.tick(hover_duration + press_duration * 0.5);
2907        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2908        let mid_drag = runtime.render(window_id)?;
2909        assert!(
2910            !solid_fill_colors(&mid_drag).contains(&expected_drag),
2911            "split divider drag should not snap to the settled drag color"
2912        );
2913
2914        runtime.tick(hover_duration + press_duration);
2915        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2916        let settled_drag = runtime.render(window_id)?;
2917        assert!(solid_fill_colors(&settled_drag).contains(&expected_drag));
2918
2919        Ok(())
2920    }
2921
2922    #[test]
2923    fn split_view_divider_focus_uses_theme_motion() -> Result<()> {
2924        let theme = DefaultTheme::default();
2925        let focus_duration = theme.motion.focus_duration();
2926        let expected_focus = theme.palette.border_focus;
2927        let (mut runtime, window_id) = build_runtime(
2928            SplitView::new(
2929                Axis::Horizontal,
2930                SizedBox::new().width(100.0).height(40.0),
2931                SizedBox::new().width(100.0).height(40.0),
2932            )
2933            .theme(theme)
2934            .min_first(40.0)
2935            .min_second(40.0),
2936        );
2937
2938        runtime.render(window_id)?;
2939        runtime.handle_event(
2940            window_id,
2941            Event::Keyboard(KeyboardEvent::new("Tab", KeyState::Pressed)),
2942        )?;
2943
2944        runtime.tick(focus_duration * 0.5);
2945        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2946        let mid_focus = runtime.render(window_id)?;
2947        assert!(
2948            !solid_fill_colors(&mid_focus).contains(&expected_focus),
2949            "split divider focus should not snap to the settled focus color"
2950        );
2951
2952        runtime.tick(focus_duration + 0.01);
2953        assert_eq!(handle_ready_events(&mut runtime)?, 1);
2954        let settled_focus = runtime.render(window_id)?;
2955        let settled_fills = solid_fill_colors(&settled_focus);
2956        assert!(
2957            contains_approx_color(&settled_fills, expected_focus),
2958            "split divider focus should settle to {expected_focus:?}; fills={settled_fills:?}"
2959        );
2960
2961        Ok(())
2962    }
2963
2964    #[test]
2965    fn split_view_allows_resize_below_combined_minimums() -> Result<()> {
2966        let (mut runtime, window_id) = build_runtime(
2967            SplitView::new(
2968                Axis::Horizontal,
2969                SizedBox::new().width(320.0).height(180.0),
2970                SizedBox::new().width(320.0).height(180.0),
2971            )
2972            .min_first(236.0)
2973            .min_second(420.0)
2974            .divider_thickness(12.0),
2975        );
2976
2977        runtime.handle_event(
2978            window_id,
2979            Event::Window(WindowEvent::Resized(Size::new(664.0, 360.0))),
2980        )?;
2981
2982        let output = runtime.render(window_id)?;
2983
2984        assert_eq!(output.frame.viewport, Size::new(664.0, 360.0));
2985        Ok(())
2986    }
2987
2988    #[test]
2989    fn split_view_default_divider_uses_thin_layout_gap() -> Result<()> {
2990        let first_constraints = Rc::new(RefCell::new(Vec::new()));
2991        let second_constraints = Rc::new(RefCell::new(Vec::new()));
2992        let (mut runtime, window_id) = build_runtime(
2993            SizedBox::new().width(240.0).height(100.0).with_child(
2994                SplitView::new(
2995                    Axis::Horizontal,
2996                    ConstraintProbe::new(
2997                        "First pane",
2998                        Size::new(400.0, 100.0),
2999                        Color::rgba(0.22, 0.48, 0.72, 1.0),
3000                        Rc::clone(&first_constraints),
3001                    ),
3002                    ConstraintProbe::new(
3003                        "Second pane",
3004                        Size::new(400.0, 100.0),
3005                        Color::rgba(0.72, 0.48, 0.22, 1.0),
3006                        Rc::clone(&second_constraints),
3007                    ),
3008                )
3009                .min_first(40.0)
3010                .min_second(40.0),
3011            ),
3012        );
3013
3014        let _ = runtime.render(window_id)?;
3015
3016        let pane_width =
3017            (240.0 - DefaultTheme::default().metrics.split_view_divider_thickness) * 0.5;
3018        let expected = Constraints::tight(Size::new(pane_width, 100.0));
3019        assert_eq!(first_constraints.borrow().last(), Some(&expected));
3020        assert_eq!(second_constraints.borrow().last(), Some(&expected));
3021        Ok(())
3022    }
3023
3024    #[test]
3025    fn pane_chrome_defaults_follow_theme_density() -> Result<()> {
3026        let compact = DefaultTheme::compact();
3027        let touch = DefaultTheme::touch();
3028
3029        let (mut compact_runtime, compact_window) = build_runtime(
3030            SplitView::new(
3031                Axis::Horizontal,
3032                SizedBox::new().width(80.0).height(40.0),
3033                SizedBox::new().width(80.0).height(40.0),
3034            )
3035            .theme(compact)
3036            .min_first(0.0)
3037            .min_second(0.0),
3038        );
3039        let compact_size = compact_runtime.render(compact_window)?.frame.viewport;
3040
3041        let (mut touch_runtime, touch_window) = build_runtime(
3042            SplitView::new(
3043                Axis::Horizontal,
3044                SizedBox::new().width(80.0).height(40.0),
3045                SizedBox::new().width(80.0).height(40.0),
3046            )
3047            .theme(touch)
3048            .min_first(0.0)
3049            .min_second(0.0),
3050        );
3051        let touch_size = touch_runtime.render(touch_window)?.frame.viewport;
3052
3053        assert_eq!(
3054            compact_size.width,
3055            160.0 + compact.metrics.split_view_divider_thickness
3056        );
3057        assert_eq!(
3058            touch_size.width,
3059            160.0 + touch.metrics.split_view_divider_thickness
3060        );
3061        assert!(touch_size.width > compact_size.width);
3062
3063        let bounds = Rect::new(0.0, 0.0, 240.0, 180.0);
3064        assert_eq!(
3065            super::floating_view_title_bar_rect(&compact, bounds).height(),
3066            compact.metrics.floating_view_title_bar_height
3067        );
3068        assert_eq!(
3069            super::floating_view_title_bar_rect(&touch, bounds).height(),
3070            touch.metrics.floating_view_title_bar_height
3071        );
3072        assert!(
3073            super::floating_view_content_rect(&touch, bounds, false).y()
3074                > super::floating_view_content_rect(&compact, bounds, false).y()
3075        );
3076
3077        let compact_handle = super::floating_view_resize_handle_rect(&compact, bounds);
3078        let touch_handle = super::floating_view_resize_handle_rect(&touch, bounds);
3079        assert_eq!(
3080            compact_handle.size,
3081            Size::new(
3082                compact.metrics.floating_view_resize_handle_size,
3083                compact.metrics.floating_view_resize_handle_size,
3084            )
3085        );
3086        assert_eq!(
3087            touch_handle.size,
3088            Size::new(
3089                touch.metrics.floating_view_resize_handle_size,
3090                touch.metrics.floating_view_resize_handle_size,
3091            )
3092        );
3093        assert!(touch_handle.width() > compact_handle.width());
3094        Ok(())
3095    }
3096
3097    #[test]
3098    fn split_view_measures_children_with_resolved_pane_constraints() -> Result<()> {
3099        let first_constraints = Rc::new(RefCell::new(Vec::new()));
3100        let second_constraints = Rc::new(RefCell::new(Vec::new()));
3101        let (mut runtime, window_id) = build_runtime(
3102            SizedBox::new().width(240.0).height(100.0).with_child(
3103                SplitView::new(
3104                    Axis::Horizontal,
3105                    ConstraintProbe::new(
3106                        "First pane",
3107                        Size::new(400.0, 100.0),
3108                        Color::rgba(0.22, 0.48, 0.72, 1.0),
3109                        Rc::clone(&first_constraints),
3110                    ),
3111                    ConstraintProbe::new(
3112                        "Second pane",
3113                        Size::new(400.0, 100.0),
3114                        Color::rgba(0.72, 0.48, 0.22, 1.0),
3115                        Rc::clone(&second_constraints),
3116                    ),
3117                )
3118                .min_first(40.0)
3119                .min_second(40.0)
3120                .divider_thickness(8.0),
3121            ),
3122        );
3123
3124        let _ = runtime.render(window_id)?;
3125
3126        let expected = Constraints::tight(Size::new(116.0, 100.0));
3127        assert_eq!(
3128            first_constraints.borrow().last(),
3129            Some(&expected),
3130            "first pane should be remeasured with the resolved pane width"
3131        );
3132        assert_eq!(
3133            second_constraints.borrow().last(),
3134            Some(&expected),
3135            "second pane should be remeasured with the resolved pane width"
3136        );
3137        Ok(())
3138    }
3139
3140    #[test]
3141    fn split_view_extra_drag_target_defers_to_child_hit() -> Result<()> {
3142        let changes = Rc::new(RefCell::new(Vec::new()));
3143        let on_change = Rc::clone(&changes);
3144        let child_events = Rc::new(RefCell::new(Vec::new()));
3145        let (mut runtime, window_id) = build_runtime(
3146            SplitView::new(
3147                Axis::Horizontal,
3148                SizedBox::new().width(100.0).height(40.0),
3149                PointerDownProbe::new("Second pane target", Rc::clone(&child_events)),
3150            )
3151            .min_first(40.0)
3152            .min_second(40.0)
3153            .on_change(move |ratio| on_change.borrow_mut().push(ratio)),
3154        );
3155
3156        let _ = runtime.render(window_id)?;
3157        runtime.handle_event(
3158            window_id,
3159            primary_pointer(PointerEventKind::Down, Point::new(105.0, 20.0), true),
3160        )?;
3161        runtime.handle_event(
3162            window_id,
3163            primary_pointer(PointerEventKind::Move, Point::new(145.0, 20.0), true),
3164        )?;
3165        runtime.handle_event(
3166            window_id,
3167            primary_pointer(PointerEventKind::Up, Point::new(145.0, 20.0), false),
3168        )?;
3169
3170        assert_eq!(child_events.borrow().as_slice(), ["down"]);
3171        assert!(
3172            changes.borrow().is_empty(),
3173            "splitter should not drag when a child handles the enlarged hit area"
3174        );
3175        Ok(())
3176    }
3177
3178    #[test]
3179    fn floating_stack_reorders_host_surfaces_on_pointer_focus() -> Result<()> {
3180        let (mut runtime, window_id) = build_runtime(
3181            FloatingStack::new()
3182                .name("floating workspace")
3183                .with_window(
3184                    Rect::new(0.0, 0.0, 120.0, 80.0),
3185                    SizedBox::new().width(120.0).height(80.0),
3186                )
3187                .with_window(
3188                    Rect::new(48.0, 0.0, 120.0, 80.0),
3189                    SizedBox::new().width(120.0).height(80.0),
3190                ),
3191        );
3192
3193        let before = runtime.render(window_id)?;
3194        let before_graph = runtime.widget_graph(window_id)?;
3195        let host = before_graph
3196            .stack_hosts
3197            .iter()
3198            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3199            .expect("focus-fronted host should be present");
3200        assert_eq!(host.surfaces.len(), 2);
3201        let layer_widget_ids = scene_layer_widget_ids(&before.frame.scene);
3202        assert!(
3203            host.surfaces
3204                .iter()
3205                .all(|surface| layer_widget_ids.contains(surface))
3206        );
3207        let first_surface = host.surfaces[0];
3208
3209        runtime.handle_event(
3210            window_id,
3211            primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
3212        )?;
3213        let reordered = runtime.render(window_id)?;
3214
3215        let after = runtime.widget_graph(window_id)?;
3216        let host = after
3217            .stack_hosts
3218            .iter()
3219            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3220            .expect("focus-fronted host should still be present");
3221        assert_eq!(host.surfaces.len(), 2);
3222        assert_eq!(host.surfaces[1], first_surface);
3223        assert!(
3224            reordered
3225                .frame
3226                .layer_updates
3227                .iter()
3228                .any(|update| update.kind == SceneLayerUpdateKind::Ordering)
3229        );
3230        Ok(())
3231    }
3232
3233    #[test]
3234    fn floating_workspace_drag_updates_view_bounds() -> Result<()> {
3235        let state = FloatingWorkspaceState::new();
3236        let mut workspace = FloatingWorkspace::new(state.clone());
3237        let first_id = workspace.push_view(
3238            FloatingViewConfig::new("First", Rect::new(16.0, 16.0, 180.0, 140.0))
3239                .min_size(Size::new(140.0, 110.0)),
3240            SizedBox::new().width(180.0).height(140.0),
3241        );
3242        workspace.push_view(
3243            FloatingViewConfig::new("Second", Rect::new(240.0, 48.0, 180.0, 140.0))
3244                .min_size(Size::new(140.0, 110.0)),
3245            SizedBox::new().width(180.0).height(140.0),
3246        );
3247
3248        let (mut runtime, window_id) = build_runtime(
3249            SizedBox::new()
3250                .width(520.0)
3251                .height(360.0)
3252                .with_child(workspace),
3253        );
3254
3255        let _ = runtime.render(window_id)?;
3256        runtime.handle_event(
3257            window_id,
3258            primary_pointer(PointerEventKind::Down, Point::new(48.0, 32.0), true),
3259        )?;
3260        runtime.handle_event(
3261            window_id,
3262            primary_pointer(PointerEventKind::Move, Point::new(132.0, 96.0), true),
3263        )?;
3264        runtime.handle_event(
3265            window_id,
3266            primary_pointer(PointerEventKind::Up, Point::new(132.0, 96.0), false),
3267        )?;
3268
3269        let moved = state.snapshot(first_id).expect("first view state present");
3270        assert!(moved.bounds.x() > 72.0);
3271        assert!(moved.bounds.y() > 56.0);
3272        Ok(())
3273    }
3274
3275    #[test]
3276    fn floating_workspace_resize_drag_remeasures_content_before_drop() -> Result<()> {
3277        let state = FloatingWorkspaceState::new();
3278        let seen_constraints = Rc::new(RefCell::new(Vec::new()));
3279        let mut workspace = FloatingWorkspace::new(state.clone());
3280        let view_id = workspace.push_view(
3281            FloatingViewConfig::new("Inspector", Rect::new(24.0, 24.0, 240.0, 180.0)),
3282            ConstraintProbe::new(
3283                "Resizable content",
3284                Size::new(420.0, 300.0),
3285                Color::rgba(0.22, 0.48, 0.72, 1.0),
3286                Rc::clone(&seen_constraints),
3287            ),
3288        );
3289
3290        let (mut runtime, window_id) = build_runtime(
3291            SizedBox::new()
3292                .width(520.0)
3293                .height(360.0)
3294                .with_child(workspace),
3295        );
3296        let _ = runtime.render(window_id)?;
3297        let initial_count = seen_constraints.borrow().len();
3298        let initial_constraints = *seen_constraints
3299            .borrow()
3300            .last()
3301            .expect("content should be measured initially");
3302        let initial_bounds = state.snapshot(view_id).expect("view state present").bounds;
3303        let handle =
3304            super::floating_view_resize_handle_rect(&DefaultTheme::default(), initial_bounds);
3305        let resize_start = Point::new(
3306            handle.x() + handle.width() * 0.5,
3307            handle.y() + handle.height() * 0.5,
3308        );
3309        let resize_end = Point::new(resize_start.x + 72.0, resize_start.y + 48.0);
3310
3311        runtime.handle_event(
3312            window_id,
3313            primary_pointer(PointerEventKind::Down, resize_start, true),
3314        )?;
3315        runtime.handle_event(
3316            window_id,
3317            primary_pointer(PointerEventKind::Move, resize_end, true),
3318        )?;
3319        let _ = runtime.render(window_id)?;
3320
3321        let seen = seen_constraints.borrow();
3322        let latest = seen
3323            .last()
3324            .copied()
3325            .expect("content should be measured after resize move");
3326        assert!(seen.len() > initial_count);
3327        assert!(latest.max.width > initial_constraints.max.width + 40.0);
3328        assert!(latest.max.height > initial_constraints.max.height + 20.0);
3329
3330        Ok(())
3331    }
3332
3333    #[test]
3334    fn floating_workspace_body_click_brings_view_to_front() -> Result<()> {
3335        let state = FloatingWorkspaceState::new();
3336        let mut workspace = FloatingWorkspace::new(state.clone());
3337        let first_id = workspace.push_view(
3338            FloatingViewConfig::new("First", Rect::new(16.0, 16.0, 180.0, 140.0)),
3339            crate::Button::new("First action"),
3340        );
3341        workspace.push_view(
3342            FloatingViewConfig::new("Second", Rect::new(120.0, 40.0, 180.0, 140.0)),
3343            crate::Button::new("Second action"),
3344        );
3345
3346        let (mut runtime, window_id) = build_runtime(
3347            SizedBox::new()
3348                .width(420.0)
3349                .height(260.0)
3350                .with_child(workspace),
3351        );
3352
3353        let _ = runtime.render(window_id)?;
3354        let first_surface = state
3355            .snapshot(first_id)
3356            .and_then(|view| view.surface_widget_id)
3357            .expect("first view surface should be registered");
3358        let before = runtime.widget_graph(window_id)?;
3359        let host = before
3360            .stack_hosts
3361            .iter()
3362            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3363            .expect("focus-fronted host should be present");
3364        assert_eq!(host.surfaces.len(), 2);
3365        assert_eq!(host.surfaces[0], first_surface);
3366        assert_ne!(host.surfaces[1], first_surface);
3367
3368        runtime.handle_event(
3369            window_id,
3370            primary_pointer(PointerEventKind::Down, Point::new(44.0, 88.0), true),
3371        )?;
3372        runtime.handle_event(
3373            window_id,
3374            primary_pointer(PointerEventKind::Up, Point::new(44.0, 88.0), false),
3375        )?;
3376
3377        let reordered = runtime.render(window_id)?;
3378        let after = runtime.widget_graph(window_id)?;
3379        let host = after
3380            .stack_hosts
3381            .iter()
3382            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3383            .expect("focus-fronted host should still be present");
3384        assert_eq!(host.surfaces.len(), 2);
3385        assert_eq!(host.surfaces[1], first_surface);
3386        assert!(
3387            reordered
3388                .frame
3389                .layer_updates
3390                .iter()
3391                .any(|update| update.kind == SceneLayerUpdateKind::Ordering)
3392        );
3393        Ok(())
3394    }
3395
3396    #[test]
3397    fn floating_workspace_view_content_receives_size_hint_and_scroll_bars() -> Result<()> {
3398        let state = FloatingWorkspaceState::new();
3399        let seen_constraints = Rc::new(RefCell::new(Vec::new()));
3400        let mut workspace = FloatingWorkspace::new(state.clone());
3401        let view_id = workspace.push_view(
3402            FloatingViewConfig::new("Inspector", Rect::new(24.0, 24.0, 240.0, 180.0)),
3403            ConstraintProbe::new(
3404                "Overflowing content",
3405                Size::new(420.0, 300.0),
3406                Color::rgba(0.22, 0.48, 0.72, 1.0),
3407                Rc::clone(&seen_constraints),
3408            ),
3409        );
3410
3411        let (mut runtime, window_id) = build_runtime(
3412            SizedBox::new()
3413                .width(520.0)
3414                .height(360.0)
3415                .with_child(workspace),
3416        );
3417        let output = runtime.render(window_id)?;
3418        let snapshot = state.snapshot(view_id).expect("view state present");
3419        let content = super::floating_view_content_rect(
3420            &crate::DefaultTheme::default(),
3421            snapshot.bounds,
3422            snapshot.maximized,
3423        );
3424        let hinted = seen_constraints
3425            .borrow()
3426            .last()
3427            .copied()
3428            .expect("content should be measured");
3429
3430        let thickness = crate::DefaultTheme::default().metrics.scroll_bar_thickness;
3431        assert_eq!(
3432            hinted.max,
3433            Size::new(content.width() - thickness, content.height() - thickness)
3434        );
3435
3436        let vertical = output
3437            .semantics
3438            .iter()
3439            .find(|node| {
3440                node.role == SemanticsRole::Slider
3441                    && node.name.as_deref() == Some("Vertical scroll bar")
3442            })
3443            .expect("vertical scroll bar semantics present");
3444        let horizontal = output
3445            .semantics
3446            .iter()
3447            .find(|node| {
3448                node.role == SemanticsRole::Slider
3449                    && node.name.as_deref() == Some("Horizontal scroll bar")
3450            })
3451            .expect("horizontal scroll bar semantics present");
3452
3453        assert!(!vertical.state.disabled);
3454        assert!(!horizontal.state.disabled);
3455        assert!(matches!(
3456            vertical.value,
3457            Some(SemanticsValue::Range { max, .. }) if max > 0.0
3458        ));
3459        assert!(matches!(
3460            horizontal.value,
3461            Some(SemanticsValue::Range { max, .. }) if max > 0.0
3462        ));
3463        Ok(())
3464    }
3465
3466    #[test]
3467    fn floating_workspace_active_resize_clips_preview_without_host_scroll_bars() -> Result<()> {
3468        let state = FloatingWorkspaceState::new();
3469        let seen_constraints = Rc::new(RefCell::new(Vec::new()));
3470        let mut workspace = FloatingWorkspace::new(state.clone());
3471        let view_id = workspace.push_view(
3472            FloatingViewConfig::new("Inspector", Rect::new(24.0, 24.0, 240.0, 180.0)),
3473            ConstraintProbe::new(
3474                "Overflowing content",
3475                Size::new(420.0, 300.0),
3476                Color::rgba(0.22, 0.48, 0.72, 1.0),
3477                Rc::clone(&seen_constraints),
3478            ),
3479        );
3480        state.set_active_resize_view(Some(view_id));
3481
3482        let (mut runtime, window_id) = build_runtime(
3483            SizedBox::new()
3484                .width(520.0)
3485                .height(360.0)
3486                .with_child(workspace),
3487        );
3488        let output = runtime.render(window_id)?;
3489
3490        assert!(output.semantics.iter().any(|node| {
3491            node.role == SemanticsRole::GenericContainer
3492                && node.name.as_deref() == Some("Overflowing content")
3493        }));
3494        assert!(!output.semantics.iter().any(|node| {
3495            node.role == SemanticsRole::Slider
3496                && matches!(
3497                    node.name.as_deref(),
3498                    Some("Vertical scroll bar" | "Horizontal scroll bar")
3499                )
3500        }));
3501        Ok(())
3502    }
3503
3504    #[test]
3505    fn floating_workspace_view_allows_horizontal_scrolling() -> Result<()> {
3506        let state = FloatingWorkspaceState::new();
3507        let seen_constraints = Rc::new(RefCell::new(Vec::new()));
3508        let mut workspace = FloatingWorkspace::new(state.clone());
3509        workspace.push_view(
3510            FloatingViewConfig::new("Inspector", Rect::new(24.0, 24.0, 240.0, 180.0)),
3511            ConstraintProbe::new(
3512                "Wide content",
3513                Size::new(520.0, 120.0),
3514                Color::rgba(0.22, 0.48, 0.72, 1.0),
3515                seen_constraints,
3516            ),
3517        );
3518
3519        let (mut runtime, window_id) = build_runtime(
3520            SizedBox::new()
3521                .width(520.0)
3522                .height(360.0)
3523                .with_child(workspace),
3524        );
3525        let before = runtime.render(window_id)?;
3526        let before_content_id = before
3527            .semantics
3528            .iter()
3529            .find(|node| node.name.as_deref() == Some("Wide content"))
3530            .map(|node| node.id)
3531            .expect("content semantics present");
3532        let before_graph = runtime.widget_graph(window_id)?;
3533        let before_bounds = before_graph
3534            .nodes
3535            .iter()
3536            .find(|node| node.id == before_content_id)
3537            .map(|node| node.bounds)
3538            .expect("content graph node present");
3539
3540        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(72.0, 96.0));
3541        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(-80.0, 0.0)));
3542        runtime.handle_event(window_id, Event::Pointer(scroll))?;
3543
3544        let after = runtime.render(window_id)?;
3545        let after_content_id = after
3546            .semantics
3547            .iter()
3548            .find(|node| node.name.as_deref() == Some("Wide content"))
3549            .map(|node| node.id)
3550            .expect("content semantics present after scroll");
3551        let after_graph = runtime.widget_graph(window_id)?;
3552        let after_bounds = after_graph
3553            .nodes
3554            .iter()
3555            .find(|node| node.id == after_content_id)
3556            .map(|node| node.bounds)
3557            .expect("content graph node present after scroll");
3558
3559        assert!(after_bounds.x() < before_bounds.x() - 40.0);
3560        Ok(())
3561    }
3562
3563    #[test]
3564    fn floating_workspace_title_label_visual_center_matches_title_slot_center() -> Result<()> {
3565        let default_theme = DefaultTheme::default();
3566        let mut constrained_theme = default_theme;
3567        constrained_theme.metrics.floating_view_title_padding = sui_layout::Padding {
3568            left: 10.0,
3569            top: 9.0,
3570            right: 10.0,
3571            bottom: 9.0,
3572        };
3573        let state = FloatingWorkspaceState::new();
3574        let mut workspace = FloatingWorkspace::new(state.clone()).theme(constrained_theme);
3575        let view_bounds = Rect::new(24.0, 24.0, 240.0, 180.0);
3576        workspace.push_view(
3577            FloatingViewConfig::new("Inspector", view_bounds),
3578            ColorFill::new(Color::rgba(0.22, 0.48, 0.72, 1.0)),
3579        );
3580
3581        let (mut runtime, window_id) = build_runtime(
3582            SizedBox::new()
3583                .width(520.0)
3584                .height(360.0)
3585                .with_child(workspace),
3586        );
3587        let output = runtime.render(window_id)?;
3588        let text = text_run_for(&output, "Inspector");
3589        let layout = text_run_layout(&text);
3590        let line = layout
3591            .lines()
3592            .first()
3593            .expect("floating view title should contain one line");
3594        let actual_visual_center =
3595            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
3596        let title_bar = super::floating_view_title_bar_rect(&constrained_theme, view_bounds);
3597        let padding = constrained_theme.metrics.floating_view_title_padding;
3598        let title_slot = Rect::new(
3599            title_bar.x() + padding.left,
3600            title_bar.y() + padding.top,
3601            (title_bar.width() - padding.left - padding.right).max(0.0),
3602            (title_bar.height() - padding.top - padding.bottom).max(0.0),
3603        );
3604        let slot_center = title_slot.y() + (title_slot.height() * 0.5);
3605
3606        assert!(
3607            (actual_visual_center - slot_center).abs() <= 0.75,
3608            "floating title visual center {actual_visual_center} did not match slot center {slot_center}; text rect {:?}, title slot {:?}",
3609            text.rect,
3610            title_slot
3611        );
3612        assert_eq!(
3613            text.style.line_height,
3614            default_theme
3615                .text_style(default_theme.palette.text)
3616                .line_height
3617        );
3618        Ok(())
3619    }
3620
3621    #[test]
3622    fn floating_workspace_title_label_preserves_tall_measurement() -> Result<()> {
3623        let mut theme = DefaultTheme::default();
3624        theme.typography.body_font_size = 28.0;
3625        theme.typography.body_line_height = 12.0;
3626        theme.metrics.floating_view_title_bar_height = 68.0;
3627        theme.metrics.floating_view_title_padding = sui_layout::Padding {
3628            left: 12.0,
3629            top: 8.0,
3630            right: 12.0,
3631            bottom: 8.0,
3632        };
3633
3634        let state = FloatingWorkspaceState::new();
3635        let mut workspace = FloatingWorkspace::new(state.clone()).theme(theme);
3636        let view_bounds = Rect::new(24.0, 24.0, 260.0, 190.0);
3637        workspace.push_view(
3638            FloatingViewConfig::new("Inspector", view_bounds),
3639            ColorFill::new(Color::rgba(0.22, 0.48, 0.72, 1.0)),
3640        );
3641
3642        let (mut runtime, window_id) = build_runtime(
3643            SizedBox::new()
3644                .width(520.0)
3645                .height(360.0)
3646                .with_child(workspace),
3647        );
3648        let output = runtime.render(window_id)?;
3649        let text = text_run_for(&output, "Inspector");
3650        let layout = text_run_layout(&text);
3651        let line = layout
3652            .lines()
3653            .first()
3654            .expect("floating view title should contain one line");
3655        let actual_visual_center =
3656            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
3657        let title_bar = super::floating_view_title_bar_rect(&theme, view_bounds);
3658        let padding = theme.metrics.floating_view_title_padding;
3659        let title_slot = Rect::new(
3660            title_bar.x() + padding.left,
3661            title_bar.y() + padding.top,
3662            (title_bar.width() - padding.left - padding.right).max(0.0),
3663            (title_bar.height() - padding.top - padding.bottom).max(0.0),
3664        );
3665        let slot_center = title_slot.y() + (title_slot.height() * 0.5);
3666
3667        assert_eq!(text.style.font_size, 28.0);
3668        assert_eq!(text.style.line_height, 12.0);
3669        assert!(text.rect.height() >= layout.measurement().height - 0.01);
3670        assert!(text.rect.height() > text.style.line_height);
3671        assert!((text.rect.x() - title_slot.x()).abs() < 0.75);
3672        assert!((actual_visual_center - slot_center).abs() <= 0.75);
3673        Ok(())
3674    }
3675
3676    #[test]
3677    fn floating_workspace_title_bar_fronting_updates_renderer_output() -> Result<()> {
3678        let first_color = Color::rgba(0.82, 0.36, 0.18, 1.0);
3679        let second_color = Color::rgba(0.18, 0.54, 0.82, 1.0);
3680        let state = FloatingWorkspaceState::new();
3681        let mut workspace = FloatingWorkspace::new(state.clone());
3682        let first_id = workspace.push_view(
3683            FloatingViewConfig::new("First", Rect::new(16.0, 16.0, 180.0, 140.0)),
3684            ColorFill::new(first_color),
3685        );
3686        workspace.push_view(
3687            FloatingViewConfig::new("Second", Rect::new(120.0, 40.0, 180.0, 140.0)),
3688            ColorFill::new(second_color),
3689        );
3690
3691        let (mut runtime, window_id) = build_runtime(
3692            SizedBox::new()
3693                .width(420.0)
3694                .height(260.0)
3695                .with_child(workspace),
3696        );
3697        let mut renderer = WgpuRenderer::default();
3698
3699        let (_, initial_image) = render_rgba(&mut runtime, &mut renderer, window_id)?;
3700        let initial_pixel = rgba_pixel(&initial_image, 140, 100);
3701        assert!(initial_pixel[2] > initial_pixel[0]);
3702
3703        runtime.handle_event(
3704            window_id,
3705            primary_pointer(PointerEventKind::Down, Point::new(44.0, 32.0), true),
3706        )?;
3707        runtime.handle_event(
3708            window_id,
3709            primary_pointer(PointerEventKind::Up, Point::new(44.0, 32.0), false),
3710        )?;
3711
3712        let (reordered, reordered_image) = render_rgba(&mut runtime, &mut renderer, window_id)?;
3713        let host = runtime
3714            .widget_graph(window_id)?
3715            .stack_hosts
3716            .into_iter()
3717            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3718            .expect("focus-fronted host should still be present");
3719        let first_surface = state
3720            .snapshot(first_id)
3721            .and_then(|view| view.surface_widget_id)
3722            .expect("first view surface should be registered");
3723        assert_eq!(host.surfaces.last().copied(), Some(first_surface));
3724        assert!(
3725            reordered
3726                .frame
3727                .layer_updates
3728                .iter()
3729                .any(|update| update.kind == SceneLayerUpdateKind::Ordering)
3730        );
3731        let reordered_pixel = rgba_pixel(&reordered_image, 140, 100);
3732        assert!(reordered_pixel[0] > reordered_pixel[2]);
3733        Ok(())
3734    }
3735
3736    #[test]
3737    fn floating_workspace_title_bar_drag_keeps_fronted_view_visually_on_top() -> Result<()> {
3738        let first_color = Color::rgba(0.82, 0.36, 0.18, 1.0);
3739        let second_color = Color::rgba(0.18, 0.54, 0.82, 1.0);
3740        let state = FloatingWorkspaceState::new();
3741        let mut workspace = FloatingWorkspace::new(state.clone());
3742        let first_id = workspace.push_view(
3743            FloatingViewConfig::new("First", Rect::new(16.0, 16.0, 180.0, 140.0)),
3744            ColorFill::new(first_color),
3745        );
3746        workspace.push_view(
3747            FloatingViewConfig::new("Second", Rect::new(120.0, 40.0, 180.0, 140.0)),
3748            ColorFill::new(second_color),
3749        );
3750
3751        let (mut runtime, window_id) = build_runtime(
3752            SizedBox::new()
3753                .width(420.0)
3754                .height(260.0)
3755                .with_child(workspace),
3756        );
3757        let mut renderer = WgpuRenderer::default();
3758
3759        let (_, initial_image) = render_rgba(&mut runtime, &mut renderer, window_id)?;
3760        let initial_pixel = rgba_pixel(&initial_image, 140, 100);
3761        assert!(initial_pixel[2] > initial_pixel[0]);
3762
3763        runtime.handle_event(
3764            window_id,
3765            primary_pointer(PointerEventKind::Down, Point::new(44.0, 32.0), true),
3766        )?;
3767        runtime.handle_event(
3768            window_id,
3769            primary_pointer(PointerEventKind::Move, Point::new(52.0, 36.0), true),
3770        )?;
3771
3772        let (dragging, dragging_image) = render_rgba(&mut runtime, &mut renderer, window_id)?;
3773        let host = runtime
3774            .widget_graph(window_id)?
3775            .stack_hosts
3776            .into_iter()
3777            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3778            .expect("focus-fronted host should still be present");
3779        let first_surface = state
3780            .snapshot(first_id)
3781            .and_then(|view| view.surface_widget_id)
3782            .expect("first view surface should be registered");
3783        assert_eq!(host.surfaces.last().copied(), Some(first_surface));
3784        assert!(
3785            dragging
3786                .frame
3787                .layer_updates
3788                .iter()
3789                .any(|update| update.kind == SceneLayerUpdateKind::Ordering)
3790        );
3791        let dragging_pixel = rgba_pixel(&dragging_image, 140, 100);
3792        assert!(dragging_pixel[0] > dragging_pixel[2]);
3793        Ok(())
3794    }
3795
3796    #[test]
3797    fn floating_workspace_popover_resolves_to_nearest_view_host() -> Result<()> {
3798        let state = FloatingWorkspaceState::new();
3799        let (mut runtime, window_id) = build_runtime(
3800            SizedBox::new().width(520.0).height(360.0).with_child(
3801                FloatingWorkspace::new(state)
3802                    .with_view(
3803                        FloatingViewConfig::new(
3804                            "Popover view",
3805                            Rect::new(24.0, 24.0, 240.0, 180.0),
3806                        ),
3807                        crate::Padding::all(
3808                            16.0,
3809                            crate::Popover::new(
3810                                "Options",
3811                                crate::Button::new("Open"),
3812                                crate::Label::new("Popover body"),
3813                            )
3814                            .open(true),
3815                        ),
3816                    )
3817                    .with_view(
3818                        FloatingViewConfig::new("Inspector", Rect::new(292.0, 64.0, 180.0, 140.0)),
3819                        SizedBox::new().width(180.0).height(140.0),
3820                    ),
3821            ),
3822        );
3823
3824        let output = runtime.render(window_id)?;
3825        let graph = runtime.widget_graph(window_id)?;
3826        let popover = output
3827            .semantics
3828            .iter()
3829            .find(|node| node.role == SemanticsRole::Popover)
3830            .expect("popover semantics present");
3831        let node = graph
3832            .nodes
3833            .iter()
3834            .find(|node| node.id == popover.id)
3835            .expect("popover graph node present");
3836
3837        assert_ne!(node.stack_host, graph.root);
3838        assert!(
3839            graph
3840                .stack_hosts
3841                .iter()
3842                .any(|host| host.host == node.stack_host)
3843        );
3844        Ok(())
3845    }
3846
3847    #[test]
3848    fn floating_workspace_maximize_limits_workspace_host_surfaces() -> Result<()> {
3849        let state = FloatingWorkspaceState::new();
3850        let mut workspace = FloatingWorkspace::new(state.clone());
3851        workspace.push_view(
3852            FloatingViewConfig::new("First", Rect::new(16.0, 16.0, 180.0, 140.0)),
3853            SizedBox::new().width(180.0).height(140.0),
3854        );
3855        let second_id = workspace.push_view(
3856            FloatingViewConfig::new("Second", Rect::new(200.0, 32.0, 180.0, 140.0)),
3857            SizedBox::new().width(180.0).height(140.0),
3858        );
3859        state.set_view_maximized(second_id, true);
3860
3861        let (mut runtime, window_id) = build_runtime(
3862            SizedBox::new()
3863                .width(520.0)
3864                .height(360.0)
3865                .with_child(workspace),
3866        );
3867
3868        let _ = runtime.render(window_id)?;
3869        let graph = runtime.widget_graph(window_id)?;
3870        let host = graph
3871            .stack_hosts
3872            .iter()
3873            .find(|host| host.order_policy == StackOrderPolicy::FocusFronted)
3874            .expect("workspace host present");
3875
3876        assert_eq!(host.surfaces.len(), 1);
3877        Ok(())
3878    }
3879}