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