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