1use std::{cell::RefCell, rc::Rc, sync::Arc};
2
3use sui_core::{
4 Color, Event, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, Path,
5 PathBuilder, Point, PointerButton, PointerEventKind, Rect, SemanticsAction, SemanticsNode,
6 SemanticsPopupKind, SemanticsRole, SemanticsState, SemanticsValue, Size, TimerToken, Transform,
7 Vector, WakeEvent, WidgetId,
8};
9use sui_layout::{
10 Alignment, Axis, Constraints, FlexAlignContent, FlexItem, FlexJustify, FlexLayout, FlexStyle,
11 FlexWrap, Padding as Insets, arrange_flex, flex_layout,
12};
13use sui_reactive::{Observable, Signal};
14use sui_runtime::{
15 ArrangeCtx, Command, EventCtx, EventPhase, LayerOptions, MeasureCtx, OVERLAY_DISMISS_REQUEST,
16 OverlayDismissPolicy, OverlayFocusBehavior, OverlayKind, OverlayOptions, PaintBoundaryMode,
17 PaintCtx, REACTIVE_CHANGED, SemanticsCtx, SingleChild, StackSurfaceOptions, Widget,
18 WidgetChildren, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
19};
20use sui_scene::{LayerCompositionMode, LayerProperties, StrokeStyle};
21use sui_text::{
22 FontFeature, FontWeight, TextAlign, TextDocument, TextLayoutRequest, TextMeasurement,
23 TextStyle, TextWrap,
24};
25
26use crate::{
27 Button, ButtonAppearance, ControlMetrics, DefaultTheme, HdrThemeMode, IconGlyph, Interpolate,
28 MotionScalar, ResolvedEffectStyle, ResolvedHdrStyle, SemanticTone, ThemeTextToken,
29 WidgetColorRole, WidgetEffectRole, WidgetLuminanceRole, WidgetMaterialRole,
30 controls::{apply_hdr_policy_cap, cap_resolved_hdr_style, draw_icon_glyph},
31 overlay::{
32 OverlayAlignment, OverlayPlacement, OverlayPlacementRequest, OverlaySide, place_overlay,
33 },
34 paint_theme_shadow, resolve_widget_hdr_style,
35 text_align::{
36 paint_aligned_text, paint_aligned_text_contained, paint_single_line_aligned_text,
37 },
38};
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum TooltipPlacement {
42 Above,
43 Below,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum TooltipAlignment {
48 Start,
49 Center,
50 End,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SurfaceRole {
55 Window,
56 Sidebar,
57 Panel,
58 Titlebar,
59 Field,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum SurfaceBorder {
64 None,
65 All,
66 Top,
67 Right,
68 Bottom,
69 Left,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum SurfaceElevation {
74 None,
75 Small,
76 Medium,
77 Large,
78}
79
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub enum SurfaceAppearance {
82 #[default]
84 Standard,
85 Raised,
87 Soft,
89 Filled,
91}
92
93pub struct Surface {
94 theme: Box<DefaultTheme>,
95 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
96 name: Option<String>,
97 role: SurfaceRole,
98 appearance: SurfaceAppearance,
99 tone: SemanticTone,
100 border: SurfaceBorder,
101 elevation: SurfaceElevation,
102 radius: f32,
103 padding: Insets,
104 fill_width: bool,
105 fill_height: bool,
106 child: SingleChild,
107}
108
109impl Surface {
110 pub fn new<W>(role: SurfaceRole, child: W) -> Self
111 where
112 W: Widget + 'static,
113 {
114 Self {
115 theme: Box::new(DefaultTheme::default()),
116 theme_reader: None,
117 name: None,
118 role,
119 appearance: SurfaceAppearance::Standard,
120 tone: SemanticTone::Neutral,
121 border: SurfaceBorder::None,
122 elevation: SurfaceElevation::None,
123 radius: 0.0,
124 padding: Insets::ZERO,
125 fill_width: false,
126 fill_height: false,
127 child: SingleChild::new(child),
128 }
129 }
130
131 pub fn window<W>(child: W) -> Self
132 where
133 W: Widget + 'static,
134 {
135 Self::new(SurfaceRole::Window, child)
136 }
137
138 pub fn sidebar<W>(child: W) -> Self
139 where
140 W: Widget + 'static,
141 {
142 Self::new(SurfaceRole::Sidebar, child).border(SurfaceBorder::Right)
143 }
144
145 pub fn panel<W>(child: W) -> Self
146 where
147 W: Widget + 'static,
148 {
149 Self::new(SurfaceRole::Panel, child)
150 .border(SurfaceBorder::All)
151 .radius(8.0)
152 }
153
154 pub fn titlebar<W>(child: W) -> Self
155 where
156 W: Widget + 'static,
157 {
158 Self::new(SurfaceRole::Titlebar, child).border(SurfaceBorder::Bottom)
159 }
160
161 pub fn field<W>(child: W) -> Self
162 where
163 W: Widget + 'static,
164 {
165 Self::new(SurfaceRole::Field, child)
166 .border(SurfaceBorder::All)
167 .radius(6.0)
168 }
169
170 pub fn theme(mut self, theme: DefaultTheme) -> Self {
171 self.theme = Box::new(theme);
172 self.theme_reader = None;
173 self
174 }
175
176 pub fn theme_when<F>(mut self, theme: F) -> Self
177 where
178 F: Fn() -> DefaultTheme + 'static,
179 {
180 self.theme_reader = Some(Box::new(theme));
181 self
182 }
183
184 pub fn name(mut self, name: impl Into<String>) -> Self {
185 self.name = Some(name.into());
186 self
187 }
188
189 pub fn border(mut self, border: SurfaceBorder) -> Self {
190 self.border = border;
191 self
192 }
193
194 pub fn appearance(mut self, appearance: SurfaceAppearance) -> Self {
195 self.appearance = appearance;
196 self
197 }
198
199 pub fn tone(mut self, tone: SemanticTone) -> Self {
200 self.tone = tone;
201 self
202 }
203
204 pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
205 self.elevation = elevation;
206 self
207 }
208
209 pub fn radius(mut self, radius: f32) -> Self {
210 self.radius = radius.max(0.0);
211 self
212 }
213
214 pub fn padding(mut self, padding: Insets) -> Self {
215 self.padding = padding;
216 self
217 }
218
219 pub fn fill(mut self) -> Self {
220 self.fill_width = true;
221 self.fill_height = true;
222 self
223 }
224
225 pub fn fill_width(mut self) -> Self {
226 self.fill_width = true;
227 self
228 }
229
230 pub fn fill_height(mut self) -> Self {
231 self.fill_height = true;
232 self
233 }
234
235 fn resolved_theme(&self) -> DefaultTheme {
236 self.theme_reader
237 .as_ref()
238 .map(|theme| theme())
239 .unwrap_or(*self.theme)
240 }
241
242 fn background_for_role(theme: &DefaultTheme, role: SurfaceRole) -> Color {
243 match role {
244 SurfaceRole::Window => theme.surfaces.window,
245 SurfaceRole::Sidebar => theme.surfaces.sidebar,
246 SurfaceRole::Panel => theme.surfaces.panel,
247 SurfaceRole::Titlebar => theme.surfaces.titlebar,
248 SurfaceRole::Field => theme.surfaces.field,
249 }
250 }
251
252 fn resolved_colors(&self, theme: &DefaultTheme) -> (Color, Color) {
253 match self.appearance {
254 SurfaceAppearance::Standard => (
255 Self::background_for_role(theme, self.role),
256 theme.surfaces.border,
257 ),
258 SurfaceAppearance::Raised => (theme.palette.surface_raised, theme.surfaces.border),
259 SurfaceAppearance::Soft => {
260 let (fill, _) = theme.semantic_tone_soft_colors(self.tone);
261 let border = if self.tone == SemanticTone::Neutral {
262 theme.surfaces.border
263 } else {
264 theme.semantic_tone_color(self.tone).with_alpha(0.36)
265 };
266 (fill, border)
267 }
268 SurfaceAppearance::Filled => {
269 let (fill, _) = theme.semantic_tone_colors(self.tone);
270 (fill, fill)
271 }
272 }
273 }
274
275 fn content_rect(&self, bounds: Rect) -> Rect {
276 inset_rect(bounds, self.padding)
277 }
278}
279
280impl Widget for Surface {
281 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
282 let max_child = Size::new(
283 if constraints.max.width.is_finite() {
284 (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
285 } else {
286 f32::INFINITY
287 },
288 if constraints.max.height.is_finite() {
289 (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
290 } else {
291 f32::INFINITY
292 },
293 );
294 let min_child = Size::new(
301 if self.fill_width && max_child.width.is_finite() {
302 max_child.width
303 } else {
304 (constraints.min.width - self.padding.left - self.padding.right)
305 .max(0.0)
306 .min(max_child.width)
307 },
308 if self.fill_height && max_child.height.is_finite() {
309 max_child.height
310 } else {
311 (constraints.min.height - self.padding.top - self.padding.bottom)
312 .max(0.0)
313 .min(max_child.height)
314 },
315 );
316 let child_size = self
317 .child
318 .measure(ctx, Constraints::new(min_child, max_child));
319 let mut size = Size::new(
320 child_size.width + self.padding.left + self.padding.right,
321 child_size.height + self.padding.top + self.padding.bottom,
322 );
323 if self.fill_width && constraints.max.width.is_finite() {
324 size.width = constraints.max.width;
325 }
326 if self.fill_height && constraints.max.height.is_finite() {
327 size.height = constraints.max.height;
328 }
329 constraints.clamp(size)
330 }
331
332 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
333 self.child.arrange(ctx, self.content_rect(bounds));
334 }
335
336 fn paint(&self, ctx: &mut PaintCtx) {
337 let theme = self.resolved_theme();
338 let bounds = ctx.bounds();
339 let radius = self.radius.min(bounds.width().min(bounds.height()) * 0.5);
340
341 let shadow = match self.elevation {
342 SurfaceElevation::None => None,
343 SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
344 SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
345 SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
346 };
347 if let Some(shadow) = shadow {
348 paint_theme_shadow(ctx, bounds, [radius; 4], shadow);
349 }
350
351 let (background, border) = self.resolved_colors(&theme);
352 if radius > 0.0 {
353 ctx.fill(rounded_rect_path(bounds, radius), background);
354 } else {
355 ctx.fill_rect(bounds, background);
356 }
357
358 let stroke_width = physical_pixels(ctx, theme.metrics.border_width.max(1.0));
359 match self.border {
360 SurfaceBorder::None => {}
361 SurfaceBorder::All => {
362 ctx.stroke(
363 rounded_rect_path(bounds, radius),
364 border,
365 StrokeStyle::new(stroke_width),
366 );
367 }
368 SurfaceBorder::Top => ctx.fill_rect(
369 Rect::new(bounds.x(), bounds.y(), bounds.width(), stroke_width),
370 border,
371 ),
372 SurfaceBorder::Right => ctx.fill_rect(
373 Rect::new(
374 bounds.max_x() - stroke_width,
375 bounds.y(),
376 stroke_width,
377 bounds.height(),
378 ),
379 border,
380 ),
381 SurfaceBorder::Bottom => ctx.fill_rect(
382 Rect::new(
383 bounds.x(),
384 bounds.max_y() - stroke_width,
385 bounds.width(),
386 stroke_width,
387 ),
388 border,
389 ),
390 SurfaceBorder::Left => ctx.fill_rect(
391 Rect::new(bounds.x(), bounds.y(), stroke_width, bounds.height()),
392 border,
393 ),
394 }
395
396 self.child.paint(ctx);
397 }
398
399 fn semantics(&self, ctx: &mut SemanticsCtx) {
400 if let Some(name) = &self.name {
401 let mut node = SemanticsNode::new(
402 ctx.widget_id(),
403 SemanticsRole::GenericContainer,
404 ctx.bounds(),
405 );
406 node.name = Some(name.clone());
407 ctx.push(node);
408 }
409 self.child.semantics(ctx);
410 }
411
412 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
413 self.child.visit_children(visitor);
414 }
415
416 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
417 self.child.visit_children_mut(visitor);
418 }
419}
420
421pub struct FramedField {
428 theme: Box<DefaultTheme>,
429 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
430 name: Option<String>,
431 description: Option<String>,
432 padding: Insets,
433 min_height: Option<f32>,
434 fill_width: bool,
435 focused: Option<bool>,
436 focused_reader: Option<Box<dyn Fn() -> bool>>,
437 invalid: bool,
438 invalid_reader: Option<Box<dyn Fn() -> bool>>,
439 hovered: bool,
440 hover_animation: AnimatedScalar,
441 child: SingleChild,
442}
443
444impl FramedField {
445 pub fn new<W>(child: W) -> Self
446 where
447 W: Widget + 'static,
448 {
449 Self {
450 theme: Box::new(DefaultTheme::default()),
451 theme_reader: None,
452 name: None,
453 description: None,
454 padding: Insets::ZERO,
455 min_height: None,
456 fill_width: false,
457 focused: None,
458 focused_reader: None,
459 invalid: false,
460 invalid_reader: None,
461 hovered: false,
462 hover_animation: AnimatedScalar::new(0.0),
463 child: SingleChild::new(child),
464 }
465 }
466
467 pub fn theme(mut self, theme: DefaultTheme) -> Self {
468 self.theme = Box::new(theme);
469 self.theme_reader = None;
470 self
471 }
472
473 pub fn theme_when<F>(mut self, theme: F) -> Self
474 where
475 F: Fn() -> DefaultTheme + 'static,
476 {
477 self.theme_reader = Some(Box::new(theme));
478 self
479 }
480
481 pub fn name(mut self, name: impl Into<String>) -> Self {
482 self.name = Some(name.into());
483 self
484 }
485
486 pub fn description(mut self, description: impl Into<String>) -> Self {
487 self.description = Some(description.into());
488 self
489 }
490
491 pub fn padding(mut self, padding: Insets) -> Self {
492 self.padding = padding;
493 self
494 }
495
496 pub fn min_height(mut self, min_height: f32) -> Self {
497 self.min_height = Some(min_height.max(0.0));
498 self
499 }
500
501 pub fn fill_width(mut self) -> Self {
502 self.fill_width = true;
503 self
504 }
505
506 pub fn focused(mut self, focused: bool) -> Self {
507 self.focused = Some(focused);
508 self.focused_reader = None;
509 self
510 }
511
512 pub fn focused_when<F>(mut self, focused: F) -> Self
513 where
514 F: Fn() -> bool + 'static,
515 {
516 self.focused_reader = Some(Box::new(focused));
517 self
518 }
519
520 pub fn invalid(mut self, invalid: bool) -> Self {
521 self.invalid = invalid;
522 self.invalid_reader = None;
523 self
524 }
525
526 pub fn invalid_when<F>(mut self, invalid: F) -> Self
527 where
528 F: Fn() -> bool + 'static,
529 {
530 self.invalid_reader = Some(Box::new(invalid));
531 self
532 }
533
534 fn resolved_theme(&self) -> DefaultTheme {
535 self.theme_reader
536 .as_ref()
537 .map(|theme| theme())
538 .unwrap_or(*self.theme)
539 }
540
541 fn child_contains(&self, target: WidgetId) -> bool {
542 if self.child.child().id() == target {
543 return true;
544 }
545 struct Finder {
546 target: WidgetId,
547 found: bool,
548 }
549 impl WidgetPodVisitor for Finder {
550 fn visit(&mut self, child: &WidgetPod) {
551 if self.found {
552 return;
553 }
554 if child.id() == self.target {
555 self.found = true;
556 } else {
557 child.visit_children(self);
558 }
559 }
560 }
561 let mut finder = Finder {
562 target,
563 found: false,
564 };
565 self.child.child().visit_children(&mut finder);
566 finder.found
567 }
568
569 fn is_focused(&self, focused_widget_id: Option<WidgetId>) -> bool {
570 if let Some(focused) = &self.focused_reader {
571 return focused();
572 }
573 if let Some(focused) = self.focused {
574 return focused;
575 }
576 focused_widget_id
577 .map(|focused| self.child_contains(focused))
578 .unwrap_or(false)
579 }
580
581 fn is_invalid(&self) -> bool {
582 self.invalid_reader
583 .as_ref()
584 .map(|invalid| invalid())
585 .unwrap_or(self.invalid)
586 }
587
588 fn content_rect(&self, bounds: Rect) -> Rect {
589 inset_rect(bounds, self.padding)
590 }
591
592 fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
593 if self.hovered == hovered {
594 return;
595 }
596 self.hovered = hovered;
597 let theme = self.resolved_theme();
598 set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
599 ctx.request_paint();
600 }
601}
602
603impl Widget for FramedField {
604 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
605 match event {
606 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
607 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
608 }
609 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
610 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
611 }
612 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
613 self.set_hovered(false, ctx);
614 }
615 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
616 let previous = self.hover_animation.value;
617 if self.hover_animation.advance(*time) {
618 ctx.request_animation_frame();
619 }
620 if self.hover_animation.changed_since(previous) {
621 ctx.request_paint();
622 }
623 }
624 _ => {}
625 }
626 }
627
628 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
629 let max_child = Size::new(
630 if constraints.max.width.is_finite() {
631 (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
632 } else {
633 f32::INFINITY
634 },
635 if constraints.max.height.is_finite() {
636 (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
637 } else {
638 f32::INFINITY
639 },
640 );
641 let child = self
642 .child
643 .measure(ctx, Constraints::new(Size::ZERO, max_child));
644 let theme = self.resolved_theme();
645 let mut size = Size::new(
646 child.width + self.padding.left + self.padding.right,
647 (child.height + self.padding.top + self.padding.bottom)
648 .max(self.min_height.unwrap_or(theme.metrics.min_height)),
649 );
650 if self.fill_width && constraints.max.width.is_finite() {
651 size.width = constraints.max.width;
652 }
653 constraints.clamp(size)
654 }
655
656 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
657 self.child.arrange(ctx, self.content_rect(bounds));
658 }
659
660 fn paint(&self, ctx: &mut PaintCtx) {
661 let theme = self.resolved_theme();
662 let bounds = ctx.bounds();
663 let radius = theme
664 .metrics
665 .corner_radius
666 .min(bounds.width().min(bounds.height()) * 0.5);
667 let invalid = self.is_invalid();
668 let focused = self.is_focused(ctx.focused_widget_id());
669 let interaction_border = mix_color(
670 theme.palette.border,
671 theme.palette.border_hover,
672 self.hover_animation.value,
673 );
674 let border = if invalid {
675 theme.semantic_tone_color(SemanticTone::Danger)
676 } else if focused {
677 theme.palette.border_focus
678 } else {
679 interaction_border
680 };
681 let background = mix_color(
682 theme.surfaces.field,
683 theme.palette.surface_focus,
684 focused as u8 as f32,
685 );
686 ctx.fill(rounded_rect_path(bounds, radius), background);
687 ctx.stroke(
688 rounded_rect_path(bounds, radius),
689 border,
690 StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
691 );
692 if focused {
693 let outset = physical_pixels(ctx, theme.metrics.focus_ring_outset);
694 ctx.stroke(
695 rounded_rect_path(bounds.inflate(outset, outset), radius + outset),
696 if invalid {
697 theme.semantic_tone_color(SemanticTone::Danger)
698 } else {
699 theme.palette.focus_ring
700 },
701 StrokeStyle::new(physical_pixels(ctx, theme.metrics.focus_ring_width)),
702 );
703 }
704 self.child.paint(ctx);
705 }
706
707 fn semantics(&self, ctx: &mut SemanticsCtx) {
708 if self.name.is_some() || self.description.is_some() {
709 let mut node = SemanticsNode::new(
710 ctx.widget_id(),
711 SemanticsRole::GenericContainer,
712 ctx.bounds(),
713 );
714 node.name = self.name.clone();
715 node.description = self.description.clone();
716 node.state.focused = self.is_focused(ctx.focused_widget_id());
717 node.state.hovered = self.hovered;
718 ctx.push(node);
719 }
720 self.child.semantics(ctx);
721 }
722
723 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
724 self.child.visit_children(visitor);
725 }
726
727 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
728 self.child.visit_children_mut(visitor);
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq)]
733pub struct MenuItem {
734 label: String,
735 shortcut: Option<String>,
736 enabled: bool,
737 destructive: bool,
738 separator_before: bool,
739 submenu: Vec<MenuItem>,
740}
741
742impl MenuItem {
743 pub fn new(label: impl Into<String>) -> Self {
744 Self {
745 label: label.into(),
746 shortcut: None,
747 enabled: true,
748 destructive: false,
749 separator_before: false,
750 submenu: Vec::new(),
751 }
752 }
753
754 pub fn label(&self) -> &str {
755 &self.label
756 }
757
758 pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
759 self.shortcut = Some(shortcut.into());
760 self
761 }
762
763 pub fn disabled(mut self) -> Self {
764 self.enabled = false;
765 self
766 }
767
768 pub fn destructive(mut self) -> Self {
769 self.destructive = true;
770 self
771 }
772
773 pub fn separator_before(mut self) -> Self {
774 self.separator_before = true;
775 self
776 }
777
778 pub fn submenu<I>(mut self, items: I) -> Self
781 where
782 I: IntoIterator<Item = MenuItem>,
783 {
784 self.submenu.extend(items);
785 self
786 }
787
788 pub fn submenu_items(&self) -> &[MenuItem] {
790 &self.submenu
791 }
792
793 pub fn has_submenu(&self) -> bool {
795 !self.submenu.is_empty()
796 }
797
798 fn text_color(&self, theme: &DefaultTheme) -> Color {
799 if !self.enabled {
800 theme.palette.placeholder
801 } else if self.destructive {
802 theme.semantic_tone_color(SemanticTone::Danger)
803 } else {
804 theme.palette.text
805 }
806 }
807}
808
809fn virtual_menu_item_id(parent: WidgetId, index: usize) -> WidgetId {
810 virtual_menu_item_path_id(parent, &[index])
811}
812
813fn virtual_menu_item_path_id(parent: WidgetId, path: &[usize]) -> WidgetId {
814 let value = path.iter().fold(parent.get(), |value, index| {
815 value.wrapping_mul(257).wrapping_add(*index as u64 + 1)
816 });
817 WidgetId::new((1_u64 << 63) | value)
818}
819
820fn menu_row_height(theme: &DefaultTheme) -> f32 {
821 theme.metrics.menu_row_height
822}
823
824fn themed_menu_height_for_rows(theme: &DefaultTheme, row_height: f32, rows: usize) -> f32 {
825 theme.metrics.menu_padding.top + theme.metrics.menu_padding.bottom + (row_height * rows as f32)
826}
827
828fn menu_submenu_indicator_width(theme: &DefaultTheme) -> f32 {
829 menu_row_height(theme) * 0.55
830}
831
832fn menu_item_semantics_node(
833 parent: WidgetId,
834 index: usize,
835 item: &MenuItem,
836 bounds: Rect,
837 highlighted: bool,
838) -> SemanticsNode {
839 let mut node = SemanticsNode::new(
840 virtual_menu_item_id(parent, index),
841 SemanticsRole::MenuItem,
842 bounds,
843 );
844 node.parent = Some(parent);
845 node.name = Some(item.label.clone());
846 node.state.disabled = !item.enabled;
847 node.state.selected = highlighted;
848 if item.enabled {
849 node.actions = vec![SemanticsAction::Activate];
850 }
851 node
852}
853
854fn context_menu_item_semantics_node(
855 root: WidgetId,
856 parent: WidgetId,
857 path: &[usize],
858 item: &MenuItem,
859 bounds: Rect,
860 highlighted: bool,
861 expanded: bool,
862) -> SemanticsNode {
863 let mut node = SemanticsNode::new(
864 virtual_menu_item_path_id(root, path),
865 SemanticsRole::MenuItem,
866 bounds,
867 );
868 node.parent = Some(parent);
869 node.name = Some(item.label.clone());
870 node.state.disabled = !item.enabled;
871 node.state.selected = highlighted;
872 if item.has_submenu() {
873 node.state.expanded = Some(expanded);
874 node.popup = Some(SemanticsPopupKind::Menu);
875 }
876 if item.enabled {
877 node.actions = if item.has_submenu() {
878 vec![
879 SemanticsAction::Activate,
880 SemanticsAction::Expand,
881 SemanticsAction::Collapse,
882 ]
883 } else {
884 vec![SemanticsAction::Activate]
885 };
886 }
887 node
888}
889
890pub struct Toolbar {
891 theme: Box<DefaultTheme>,
892 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
893 axis: Axis,
894 name: Option<String>,
895 extent: Option<f32>,
896 padding: Option<Insets>,
897 spacing: Option<f32>,
898 line_spacing: Option<f32>,
899 wrap: FlexWrap,
900 background: Option<Color>,
901 divider: bool,
902 children: WidgetChildren,
903 layout: Option<FlexLayout>,
904}
905
906impl Toolbar {
907 pub fn horizontal() -> Self {
908 Self::new(Axis::Horizontal)
909 }
910
911 pub fn vertical() -> Self {
912 Self::new(Axis::Vertical)
913 }
914
915 pub fn new(axis: Axis) -> Self {
916 Self {
917 theme: Box::new(DefaultTheme::default()),
918 theme_reader: None,
919 axis,
920 name: None,
921 extent: None,
922 padding: None,
923 spacing: None,
924 line_spacing: None,
925 wrap: FlexWrap::NoWrap,
926 background: None,
927 divider: true,
928 children: WidgetChildren::new(),
929 layout: None,
930 }
931 }
932
933 pub fn theme(mut self, theme: DefaultTheme) -> Self {
934 self.theme = Box::new(theme);
935 self.theme_reader = None;
936 self
937 }
938
939 pub fn theme_when<F>(mut self, theme: F) -> Self
940 where
941 F: Fn() -> DefaultTheme + 'static,
942 {
943 self.theme_reader = Some(Box::new(theme));
944 self
945 }
946
947 pub fn name(mut self, name: impl Into<String>) -> Self {
948 self.name = Some(name.into());
949 self
950 }
951
952 pub fn extent(mut self, extent: f32) -> Self {
953 self.extent = Some(extent.max(0.0));
954 self
955 }
956
957 pub fn padding(mut self, padding: Insets) -> Self {
958 self.padding = Some(padding);
959 self
960 }
961
962 pub fn spacing(mut self, spacing: f32) -> Self {
963 self.spacing = Some(spacing.max(0.0));
964 self
965 }
966
967 pub fn wrap(mut self, wrap: FlexWrap) -> Self {
970 self.wrap = wrap;
971 self
972 }
973
974 pub fn wrapping(self) -> Self {
975 self.wrap(FlexWrap::Wrap)
976 }
977
978 pub fn line_spacing(mut self, spacing: f32) -> Self {
979 self.line_spacing = Some(spacing.max(0.0));
980 self
981 }
982
983 pub fn background(mut self, color: Color) -> Self {
984 self.background = Some(color);
985 self
986 }
987
988 pub fn divider(mut self, divider: bool) -> Self {
989 self.divider = divider;
990 self
991 }
992
993 pub fn with_child<W>(mut self, child: W) -> Self
994 where
995 W: Widget + 'static,
996 {
997 self.children.push(child);
998 self
999 }
1000
1001 pub fn push<W>(&mut self, child: W)
1002 where
1003 W: Widget + 'static,
1004 {
1005 self.children.push(child);
1006 }
1007
1008 pub fn children(&self) -> &[sui_runtime::WidgetPod] {
1009 self.children.as_slice()
1010 }
1011
1012 pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
1013 self.children.as_mut_slice()
1014 }
1015
1016 fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
1017 self.extent.unwrap_or(metrics.toolbar_extent)
1018 }
1019
1020 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1021 self.padding.unwrap_or(metrics.toolbar_padding)
1022 }
1023
1024 fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1025 self.spacing.unwrap_or(metrics.toolbar_spacing)
1026 }
1027
1028 fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1029 let padding = self.resolved_padding(metrics);
1030 Rect::new(
1031 bounds.x() + padding.left,
1032 bounds.y() + padding.top,
1033 (bounds.width() - padding.left - padding.right).max(0.0),
1034 (bounds.height() - padding.top - padding.bottom).max(0.0),
1035 )
1036 }
1037
1038 fn resolved_theme(&self) -> DefaultTheme {
1039 self.theme_reader
1040 .as_ref()
1041 .map(|theme| theme())
1042 .unwrap_or(*self.theme)
1043 }
1044}
1045
1046impl Default for Toolbar {
1047 fn default() -> Self {
1048 Self::horizontal()
1049 }
1050}
1051
1052impl Widget for Toolbar {
1053 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1054 let theme = self.resolved_theme();
1055 let metrics = theme.metrics;
1056 let extent = self.resolved_extent(metrics);
1057 let padding = self.resolved_padding(metrics);
1058 let spacing = self.resolved_spacing(metrics);
1059 if self.wrap == FlexWrap::Wrap {
1060 let line_spacing = self.line_spacing.unwrap_or(spacing);
1061 let max_content = Size::new(
1062 if constraints.max.width.is_finite() {
1063 (constraints.max.width - padding.left - padding.right).max(0.0)
1064 } else {
1065 f32::INFINITY
1066 },
1067 if constraints.max.height.is_finite() {
1068 (constraints.max.height - padding.top - padding.bottom).max(0.0)
1069 } else {
1070 f32::INFINITY
1071 },
1072 );
1073 let min_cross = match self.axis {
1074 Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
1075 Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
1076 };
1077 let min_content = match self.axis {
1078 Axis::Horizontal => Size::new(
1079 if max_content.width.is_finite() {
1080 max_content.width
1081 } else {
1082 0.0
1083 },
1084 min_cross,
1085 ),
1086 Axis::Vertical => Size::new(
1087 min_cross,
1088 if max_content.height.is_finite() {
1089 max_content.height
1090 } else {
1091 0.0
1092 },
1093 ),
1094 };
1095 let style = FlexStyle::new(self.axis)
1096 .wrap(FlexWrap::Wrap)
1097 .main_gap(spacing)
1098 .cross_gap(line_spacing)
1099 .justify(FlexJustify::Start)
1100 .align_items(Alignment::Center)
1101 .align_content(FlexAlignContent::Start);
1102 let items = vec![FlexItem::new(); self.children.len()];
1103 let layout = flex_layout(
1104 style,
1105 &items,
1106 Constraints::new(min_content, max_content),
1107 |index, child_constraints| {
1108 self.children.measure_child(index, ctx, child_constraints)
1109 },
1110 );
1111 let natural = Size::new(
1112 layout.size.width + padding.left + padding.right,
1113 layout.size.height + padding.top + padding.bottom,
1114 );
1115 self.layout = Some(layout);
1116 return constraints.clamp(natural);
1117 }
1118 self.layout = None;
1119 let content_cross = match self.axis {
1120 Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
1121 Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
1122 };
1123 let child_constraints = match self.axis {
1124 Axis::Horizontal => {
1125 Constraints::new(Size::ZERO, Size::new(f32::INFINITY, content_cross))
1126 }
1127 Axis::Vertical => Constraints::new(Size::ZERO, Size::new(content_cross, f32::INFINITY)),
1128 };
1129
1130 let mut main: f32 = 0.0;
1131 let mut cross: f32 = 0.0;
1132 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1133 let child_size = child.measure(ctx, child_constraints);
1134 if index > 0 {
1135 main += spacing;
1136 }
1137 main += toolbar_main(self.axis, child_size);
1138 cross = cross.max(toolbar_cross(self.axis, child_size));
1139 }
1140
1141 let natural = match self.axis {
1142 Axis::Horizontal => Size::new(
1143 main + padding.left + padding.right,
1144 extent.max(cross + padding.top + padding.bottom),
1145 ),
1146 Axis::Vertical => Size::new(
1147 extent.max(cross + padding.left + padding.right),
1148 main + padding.top + padding.bottom,
1149 ),
1150 };
1151 let filled = match self.axis {
1152 Axis::Horizontal => Size::new(
1153 if constraints.max.width.is_finite() {
1154 constraints.max.width
1155 } else {
1156 natural.width
1157 },
1158 extent,
1159 ),
1160 Axis::Vertical => Size::new(
1161 extent,
1162 if constraints.max.height.is_finite() {
1163 constraints.max.height
1164 } else {
1165 natural.height
1166 },
1167 ),
1168 };
1169
1170 constraints.clamp(filled)
1171 }
1172
1173 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1174 let theme = self.resolved_theme();
1175 let metrics = theme.metrics;
1176 let spacing = self.resolved_spacing(metrics);
1177 let content = self.content_bounds(bounds, metrics);
1178 if self.wrap == FlexWrap::Wrap {
1179 let style = FlexStyle::new(self.axis)
1180 .wrap(FlexWrap::Wrap)
1181 .main_gap(spacing)
1182 .cross_gap(self.line_spacing.unwrap_or(spacing))
1183 .justify(FlexJustify::Start)
1184 .align_items(Alignment::Center)
1185 .align_content(FlexAlignContent::Start);
1186 let items = vec![FlexItem::new(); self.children.len()];
1187 let measured = self
1188 .children
1189 .as_slice()
1190 .iter()
1191 .map(WidgetPod::measured_size)
1192 .collect::<Vec<_>>();
1193 let layout = arrange_flex(style, &items, content.size, &measured);
1194 for (index, item) in layout.items.iter().enumerate() {
1195 self.children.arrange_child(
1196 index,
1197 ctx,
1198 item.rect.translate(content.origin.to_vector()),
1199 );
1200 }
1201 self.layout = Some(layout);
1202 return;
1203 }
1204 let content_main = toolbar_main(self.axis, content.size);
1205 let content_cross = toolbar_cross(self.axis, content.size);
1206 let mut main_offset = 0.0;
1207
1208 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1209 if index > 0 {
1210 main_offset += spacing;
1211 }
1212
1213 let measured = child.measured_size();
1214 let remaining = (content_main - main_offset).max(0.0);
1215 let child_main = toolbar_main(self.axis, measured).min(remaining);
1216 let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
1217 let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
1218 let origin = match self.axis {
1219 Axis::Horizontal => {
1220 Point::new(content.x() + main_offset, content.y() + cross_offset)
1221 }
1222 Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1223 };
1224 child.arrange(
1225 ctx,
1226 Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
1227 );
1228 main_offset += child_main;
1229 }
1230 }
1231
1232 fn paint(&self, ctx: &mut PaintCtx) {
1233 let theme = self.resolved_theme();
1234 let palette = theme.palette;
1235 let bounds = ctx.bounds();
1236 ctx.fill_bounds(self.background.unwrap_or(palette.surface));
1237 if self.divider {
1238 let divider = match self.axis {
1239 Axis::Horizontal => {
1240 Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
1241 }
1242 Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
1243 };
1244 ctx.stroke_rect(
1245 divider,
1246 palette.border.with_alpha(0.85),
1247 StrokeStyle::new(1.0),
1248 );
1249 }
1250 self.children.paint(ctx);
1251 }
1252
1253 fn semantics(&self, ctx: &mut SemanticsCtx) {
1254 if let Some(name) = &self.name {
1255 let mut node = SemanticsNode::new(
1256 ctx.widget_id(),
1257 SemanticsRole::GenericContainer,
1258 ctx.bounds(),
1259 );
1260 node.name = Some(name.clone());
1261 ctx.push(node);
1262 }
1263 self.children.semantics(ctx);
1264 }
1265
1266 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1267 self.children.visit_children(visitor);
1268 }
1269
1270 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1271 self.children.visit_children_mut(visitor);
1272 }
1273}
1274
1275pub struct CommandGroup {
1276 theme: Box<DefaultTheme>,
1277 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1278 axis: Axis,
1279 name: Option<String>,
1280 padding: Option<Insets>,
1281 spacing: Option<f32>,
1282 corner_radius: Option<f32>,
1283 background: Option<Color>,
1284 border: Option<Color>,
1285 children: WidgetChildren,
1286}
1287
1288impl CommandGroup {
1289 pub fn horizontal(name: impl Into<String>) -> Self {
1290 Self::new(Axis::Horizontal, name)
1291 }
1292
1293 pub fn vertical(name: impl Into<String>) -> Self {
1294 Self::new(Axis::Vertical, name)
1295 }
1296
1297 pub fn new(axis: Axis, name: impl Into<String>) -> Self {
1298 Self {
1299 theme: Box::new(DefaultTheme::default()),
1300 theme_reader: None,
1301 axis,
1302 name: Some(name.into()),
1303 padding: None,
1304 spacing: None,
1305 corner_radius: None,
1306 background: None,
1307 border: None,
1308 children: WidgetChildren::new(),
1309 }
1310 }
1311
1312 pub fn theme(mut self, theme: DefaultTheme) -> Self {
1313 self.theme = Box::new(theme);
1314 self.theme_reader = None;
1315 self
1316 }
1317
1318 pub fn theme_when<F>(mut self, theme: F) -> Self
1319 where
1320 F: Fn() -> DefaultTheme + 'static,
1321 {
1322 self.theme_reader = Some(Box::new(theme));
1323 self
1324 }
1325
1326 pub fn unnamed(mut self) -> Self {
1327 self.name = None;
1328 self
1329 }
1330
1331 pub fn padding(mut self, padding: Insets) -> Self {
1332 self.padding = Some(padding);
1333 self
1334 }
1335
1336 pub fn spacing(mut self, spacing: f32) -> Self {
1337 self.spacing = Some(spacing.max(0.0));
1338 self
1339 }
1340
1341 pub fn corner_radius(mut self, corner_radius: f32) -> Self {
1342 self.corner_radius = Some(corner_radius.max(0.0));
1343 self
1344 }
1345
1346 pub fn background(mut self, color: Color) -> Self {
1347 self.background = Some(color);
1348 self
1349 }
1350
1351 pub fn border(mut self, color: Color) -> Self {
1352 self.border = Some(color);
1353 self
1354 }
1355
1356 pub fn with_child<W>(mut self, child: W) -> Self
1357 where
1358 W: Widget + 'static,
1359 {
1360 self.children.push(child);
1361 self
1362 }
1363
1364 pub fn push<W>(&mut self, child: W)
1365 where
1366 W: Widget + 'static,
1367 {
1368 self.children.push(child);
1369 }
1370
1371 pub fn children(&self) -> &[sui_runtime::WidgetPod] {
1372 self.children.as_slice()
1373 }
1374
1375 pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
1376 self.children.as_mut_slice()
1377 }
1378
1379 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1380 self.padding.unwrap_or(metrics.command_group_padding)
1381 }
1382
1383 fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1384 self.spacing.unwrap_or(metrics.command_group_spacing)
1385 }
1386
1387 fn resolved_corner_radius(&self, metrics: ControlMetrics) -> f32 {
1388 self.corner_radius.unwrap_or(metrics.command_group_radius)
1389 }
1390
1391 fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1392 inset_rect(bounds, self.resolved_padding(metrics))
1393 }
1394
1395 fn resolved_theme(&self) -> DefaultTheme {
1396 self.theme_reader
1397 .as_ref()
1398 .map(|theme| theme())
1399 .unwrap_or(*self.theme)
1400 }
1401}
1402
1403impl Widget for CommandGroup {
1404 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1405 let theme = self.resolved_theme();
1406 let metrics = theme.metrics;
1407 let padding = self.resolved_padding(metrics);
1408 let spacing = self.resolved_spacing(metrics);
1409 let max_width = if constraints.max.width.is_finite() {
1410 (constraints.max.width - padding.left - padding.right).max(0.0)
1411 } else {
1412 f32::INFINITY
1413 };
1414 let max_height = if constraints.max.height.is_finite() {
1415 (constraints.max.height - padding.top - padding.bottom).max(0.0)
1416 } else {
1417 f32::INFINITY
1418 };
1419 let child_constraints = Constraints::new(Size::ZERO, Size::new(max_width, max_height));
1420
1421 let mut main: f32 = 0.0;
1422 let mut cross: f32 = 0.0;
1423 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1424 let child_size = child.measure(ctx, child_constraints);
1425 if index > 0 {
1426 main += spacing;
1427 }
1428 main += toolbar_main(self.axis, child_size);
1429 cross = cross.max(toolbar_cross(self.axis, child_size));
1430 }
1431
1432 let natural = match self.axis {
1433 Axis::Horizontal => Size::new(
1434 main + padding.left + padding.right,
1435 cross + padding.top + padding.bottom,
1436 ),
1437 Axis::Vertical => Size::new(
1438 cross + padding.left + padding.right,
1439 main + padding.top + padding.bottom,
1440 ),
1441 };
1442 constraints.clamp(natural)
1443 }
1444
1445 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1446 let theme = self.resolved_theme();
1447 let metrics = theme.metrics;
1448 let spacing = self.resolved_spacing(metrics);
1449 let content = self.content_bounds(bounds, metrics);
1450 let content_main = toolbar_main(self.axis, content.size);
1451 let content_cross = toolbar_cross(self.axis, content.size);
1452 let mut main_offset = 0.0;
1453
1454 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1455 if index > 0 {
1456 main_offset += spacing;
1457 }
1458
1459 let measured = child.measured_size();
1460 let remaining = (content_main - main_offset).max(0.0);
1461 let child_main = toolbar_main(self.axis, measured).min(remaining);
1462 let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
1463 let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
1464 let origin = match self.axis {
1465 Axis::Horizontal => {
1466 Point::new(content.x() + main_offset, content.y() + cross_offset)
1467 }
1468 Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1469 };
1470 child.arrange(
1471 ctx,
1472 Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
1473 );
1474 main_offset += child_main;
1475 }
1476 }
1477
1478 fn paint(&self, ctx: &mut PaintCtx) {
1479 let theme = self.resolved_theme();
1480 let radius = self
1481 .resolved_corner_radius(theme.metrics)
1482 .min(ctx.bounds().width().min(ctx.bounds().height()) * 0.5);
1483 let background = self.background.unwrap_or(theme.palette.surface_raised);
1484 let border = self.border.unwrap_or(theme.palette.border);
1485 let shape = rounded_rect_path(ctx.bounds(), radius);
1486 ctx.fill(shape.clone(), background);
1487 ctx.stroke(shape, border, StrokeStyle::new(physical_pixels(ctx, 1.0)));
1488 self.children.paint(ctx);
1489 }
1490
1491 fn semantics(&self, ctx: &mut SemanticsCtx) {
1492 if let Some(name) = &self.name {
1493 let mut node = SemanticsNode::new(
1494 ctx.widget_id(),
1495 SemanticsRole::GenericContainer,
1496 ctx.bounds(),
1497 );
1498 node.name = Some(name.clone());
1499 ctx.push(node);
1500 }
1501 self.children.semantics(ctx);
1502 }
1503
1504 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1505 self.children.visit_children(visitor);
1506 }
1507
1508 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1509 self.children.visit_children_mut(visitor);
1510 }
1511}
1512
1513fn toolbar_main(axis: Axis, size: Size) -> f32 {
1514 match axis {
1515 Axis::Horizontal => size.width,
1516 Axis::Vertical => size.height,
1517 }
1518}
1519
1520fn toolbar_cross(axis: Axis, size: Size) -> f32 {
1521 match axis {
1522 Axis::Horizontal => size.height,
1523 Axis::Vertical => size.width,
1524 }
1525}
1526
1527fn toolbar_size(axis: Axis, main: f32, cross: f32) -> Size {
1528 match axis {
1529 Axis::Horizontal => Size::new(main, cross),
1530 Axis::Vertical => Size::new(cross, main),
1531 }
1532}
1533
1534#[derive(Debug, Clone, PartialEq, Eq)]
1535pub struct ToolPaletteItem {
1536 icon: IconGlyph,
1537 label: String,
1538 enabled: bool,
1539}
1540
1541impl ToolPaletteItem {
1542 pub fn new(icon: IconGlyph, label: impl Into<String>) -> Self {
1543 Self {
1544 icon,
1545 label: label.into(),
1546 enabled: true,
1547 }
1548 }
1549
1550 pub fn disabled(mut self) -> Self {
1551 self.enabled = false;
1552 self
1553 }
1554
1555 pub fn label(&self) -> &str {
1556 &self.label
1557 }
1558}
1559
1560pub struct ToolPalette {
1561 theme: Box<DefaultTheme>,
1562 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1563 axis: Axis,
1564 name: String,
1565 items: Vec<ToolPaletteItem>,
1566 selected: Option<usize>,
1567 selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
1568 hovered: Option<usize>,
1569 hover_visual: Option<usize>,
1570 pressed: Option<usize>,
1571 press_visual: Option<usize>,
1572 hover_animation: AnimatedScalar,
1573 press_animation: AnimatedScalar,
1574 focus_animation: AnimatedScalar,
1575 extent: Option<f32>,
1576 padding: Option<Insets>,
1577 spacing: Option<f32>,
1578 item_size: Option<f32>,
1579 icon_size: Option<f32>,
1580 background: Option<Color>,
1581 divider: bool,
1582 on_change: Option<Box<dyn FnMut(usize, String)>>,
1583 on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String)>>,
1584}
1585
1586impl ToolPalette {
1587 pub fn vertical(name: impl Into<String>) -> Self {
1588 Self::new(Axis::Vertical, name)
1589 }
1590
1591 pub fn horizontal(name: impl Into<String>) -> Self {
1592 Self::new(Axis::Horizontal, name)
1593 }
1594
1595 pub fn new(axis: Axis, name: impl Into<String>) -> Self {
1596 Self {
1597 theme: Box::new(DefaultTheme::default()),
1598 theme_reader: None,
1599 axis,
1600 name: name.into(),
1601 items: Vec::new(),
1602 selected: None,
1603 selected_reader: None,
1604 hovered: None,
1605 hover_visual: None,
1606 pressed: None,
1607 press_visual: None,
1608 hover_animation: AnimatedScalar::new(0.0),
1609 press_animation: AnimatedScalar::new(0.0),
1610 focus_animation: AnimatedScalar::new(0.0),
1611 extent: None,
1612 padding: None,
1613 spacing: None,
1614 item_size: None,
1615 icon_size: None,
1616 background: None,
1617 divider: true,
1618 on_change: None,
1619 on_change_with_ctx: None,
1620 }
1621 }
1622
1623 pub fn theme(mut self, theme: DefaultTheme) -> Self {
1624 self.theme = Box::new(theme);
1625 self.theme_reader = None;
1626 self
1627 }
1628
1629 pub fn theme_when<F>(mut self, theme: F) -> Self
1630 where
1631 F: Fn() -> DefaultTheme + 'static,
1632 {
1633 self.theme_reader = Some(Box::new(theme));
1634 self
1635 }
1636
1637 pub fn item(mut self, item: ToolPaletteItem) -> Self {
1638 self.items.push(item);
1639 self
1640 }
1641
1642 pub fn items<I>(mut self, items: I) -> Self
1643 where
1644 I: IntoIterator<Item = ToolPaletteItem>,
1645 {
1646 self.items.extend(items);
1647 self
1648 }
1649
1650 pub fn selected(mut self, selected: usize) -> Self {
1651 self.selected = Some(selected);
1652 self.selected_reader = None;
1653 self
1654 }
1655
1656 pub fn selected_when<F>(mut self, selected: F) -> Self
1657 where
1658 F: Fn() -> Option<usize> + 'static,
1659 {
1660 self.selected_reader = Some(Box::new(selected));
1661 self
1662 }
1663
1664 pub fn extent(mut self, extent: f32) -> Self {
1665 self.extent = Some(extent.max(0.0));
1666 self
1667 }
1668
1669 pub fn padding(mut self, padding: Insets) -> Self {
1670 self.padding = Some(padding);
1671 self
1672 }
1673
1674 pub fn spacing(mut self, spacing: f32) -> Self {
1675 self.spacing = Some(spacing.max(0.0));
1676 self
1677 }
1678
1679 pub fn item_size(mut self, item_size: f32) -> Self {
1680 self.item_size = Some(item_size.max(0.0));
1681 self
1682 }
1683
1684 pub fn icon_size(mut self, icon_size: f32) -> Self {
1685 self.icon_size = Some(icon_size.max(0.0));
1686 self
1687 }
1688
1689 pub fn background(mut self, color: Color) -> Self {
1690 self.background = Some(color);
1691 self
1692 }
1693
1694 pub fn divider(mut self, divider: bool) -> Self {
1695 self.divider = divider;
1696 self
1697 }
1698
1699 pub fn on_change<F>(mut self, on_change: F) -> Self
1700 where
1701 F: FnMut(usize, String) + 'static,
1702 {
1703 self.on_change = Some(Box::new(on_change));
1704 self
1705 }
1706
1707 pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
1708 where
1709 F: FnMut(&mut EventCtx, usize, String) + 'static,
1710 {
1711 self.on_change_with_ctx = Some(Box::new(on_change));
1712 self
1713 }
1714
1715 pub fn selected_index(&self) -> Option<usize> {
1716 self.current_selected()
1717 }
1718
1719 fn current_selected(&self) -> Option<usize> {
1720 self.selected_reader
1721 .as_ref()
1722 .map(|selected| selected())
1723 .unwrap_or(self.selected)
1724 .filter(|index| *index < self.items.len())
1725 }
1726
1727 fn resolved_theme(&self) -> DefaultTheme {
1728 self.theme_reader
1729 .as_ref()
1730 .map(|theme| theme())
1731 .unwrap_or(*self.theme)
1732 }
1733
1734 fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
1735 self.extent.unwrap_or(metrics.toolbar_extent)
1736 }
1737
1738 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1739 self.padding.unwrap_or(metrics.toolbar_padding)
1740 }
1741
1742 fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1743 self.spacing.unwrap_or(metrics.toolbar_spacing)
1744 }
1745
1746 fn resolved_item_size(&self, metrics: ControlMetrics) -> f32 {
1747 self.item_size.unwrap_or(metrics.tool_palette_item_size)
1748 }
1749
1750 fn resolved_icon_size(&self, metrics: ControlMetrics) -> f32 {
1751 self.icon_size.unwrap_or(metrics.tool_palette_icon_size)
1752 }
1753
1754 fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1755 let padding = self.resolved_padding(metrics);
1756 Rect::new(
1757 bounds.x() + padding.left,
1758 bounds.y() + padding.top,
1759 (bounds.width() - padding.left - padding.right).max(0.0),
1760 (bounds.height() - padding.top - padding.bottom).max(0.0),
1761 )
1762 }
1763
1764 fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
1765 if index >= self.items.len() {
1766 return None;
1767 }
1768
1769 let metrics = self.resolved_theme().metrics;
1770 let item_size = self.resolved_item_size(metrics);
1771 let spacing = self.resolved_spacing(metrics);
1772 let content = self.content_bounds(bounds, metrics);
1773 let content_main = toolbar_main(self.axis, content.size);
1774 let content_cross = toolbar_cross(self.axis, content.size);
1775 let item_main = item_size.min(content_main);
1776 let item_cross = item_size.min(content_cross);
1777 let main_offset = index as f32 * (item_size + spacing);
1778 if main_offset >= content_main {
1779 return None;
1780 }
1781 let cross_offset = ((content_cross - item_cross) * 0.5).max(0.0);
1782 let origin = match self.axis {
1783 Axis::Horizontal => Point::new(content.x() + main_offset, content.y() + cross_offset),
1784 Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1785 };
1786 Some(Rect::from_origin_size(
1787 origin,
1788 toolbar_size(self.axis, item_main, item_cross),
1789 ))
1790 }
1791
1792 fn hit_at(&self, bounds: Rect, position: Point) -> Option<usize> {
1793 (0..self.items.len()).find(|index| {
1794 self.items[*index].enabled
1795 && self
1796 .item_rect(bounds, *index)
1797 .is_some_and(|rect| rect.contains(position))
1798 })
1799 }
1800
1801 fn select(&mut self, ctx: &mut EventCtx, index: usize) {
1802 let Some(item) = self.items.get(index) else {
1803 return;
1804 };
1805 if !item.enabled {
1806 return;
1807 }
1808
1809 self.selected = Some(index);
1810 if let Some(on_change) = &mut self.on_change {
1811 on_change(index, item.label.clone());
1812 }
1813 if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
1814 on_change_with_ctx(ctx, index, item.label.clone());
1815 }
1816 }
1817
1818 fn move_selection(&mut self, ctx: &mut EventCtx, delta: isize) {
1819 if self.items.is_empty() {
1820 return;
1821 }
1822
1823 let start = self.current_selected().unwrap_or(0);
1824 let mut index = start as isize;
1825 let last = self.items.len() as isize - 1;
1826 for _ in 0..self.items.len() {
1827 index = (index + delta).clamp(0, last);
1828 if self
1829 .items
1830 .get(index as usize)
1831 .is_some_and(|item| item.enabled)
1832 {
1833 self.select(ctx, index as usize);
1834 return;
1835 }
1836 if index == 0 || index == last {
1837 return;
1838 }
1839 }
1840 }
1841
1842 fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
1843 if self.hovered == hovered {
1844 return;
1845 }
1846 let theme = self.resolved_theme();
1847 self.hovered = hovered;
1848 if let Some(index) = hovered {
1849 self.hover_visual = Some(index);
1850 self.hover_animation = AnimatedScalar::new(0.0);
1851 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
1852 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
1853 self.hover_visual = None;
1854 }
1855 ctx.request_paint();
1856 ctx.request_semantics();
1857 }
1858
1859 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
1860 if self.pressed == pressed {
1861 return;
1862 }
1863 let theme = self.resolved_theme();
1864 self.pressed = pressed;
1865 if let Some(index) = pressed {
1866 self.press_visual = Some(index);
1867 self.press_animation = AnimatedScalar::new(0.0);
1868 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
1869 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
1870 self.press_visual = None;
1871 }
1872 ctx.request_paint();
1873 ctx.request_semantics();
1874 }
1875
1876 fn hover_amount_for(&self, index: usize) -> f32 {
1877 if self.hover_visual == Some(index) {
1878 self.hover_animation.value
1879 } else {
1880 0.0
1881 }
1882 }
1883
1884 fn press_amount_for(&self, index: usize) -> f32 {
1885 if self.press_visual == Some(index) {
1886 self.press_animation.value
1887 } else {
1888 0.0
1889 }
1890 }
1891
1892 fn advance_animations(&mut self, time: f64) -> bool {
1893 let hover_animating = self.hover_animation.advance(time);
1894 if !hover_animating
1895 && self.hovered.is_none()
1896 && self.hover_animation.value <= AnimatedScalar::EPSILON
1897 {
1898 self.hover_visual = None;
1899 }
1900
1901 let press_animating = self.press_animation.advance(time);
1902 if !press_animating
1903 && self.pressed.is_none()
1904 && self.press_animation.value <= AnimatedScalar::EPSILON
1905 {
1906 self.press_visual = None;
1907 }
1908
1909 hover_animating | press_animating | self.focus_animation.advance(time)
1910 }
1911}
1912
1913impl Widget for ToolPalette {
1914 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1915 match event {
1916 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1917 self.set_hovered(self.hit_at(ctx.bounds(), pointer.position), ctx);
1918 }
1919 Event::Pointer(pointer)
1920 if pointer.kind == PointerEventKind::Down
1921 && pointer.button == Some(PointerButton::Primary) =>
1922 {
1923 let hovered = self.hit_at(ctx.bounds(), pointer.position);
1924 self.set_hovered(hovered, ctx);
1925 self.set_pressed(hovered, ctx);
1926 if self.pressed.is_some() {
1927 ctx.request_focus();
1928 ctx.request_pointer_capture(pointer.pointer_id);
1929 ctx.set_handled();
1930 }
1931 }
1932 Event::Pointer(pointer)
1933 if pointer.kind == PointerEventKind::Up
1934 && pointer.button == Some(PointerButton::Primary) =>
1935 {
1936 let hovered = self.hit_at(ctx.bounds(), pointer.position);
1937 if let Some(index) = self
1938 .pressed
1939 .zip(hovered)
1940 .filter(|(left, right)| left == right)
1941 .map(|(index, _)| index)
1942 {
1943 self.select(ctx, index);
1944 }
1945 self.set_hovered(hovered, ctx);
1946 self.set_pressed(None, ctx);
1947 ctx.release_pointer_capture(pointer.pointer_id);
1948 ctx.set_handled();
1949 }
1950 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
1951 self.set_hovered(None, ctx);
1952 }
1953 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1954 if self.pressed.is_some() {
1955 self.set_pressed(None, ctx);
1956 self.set_hovered(None, ctx);
1957 ctx.release_pointer_capture(pointer.pointer_id);
1958 ctx.set_handled();
1959 }
1960 }
1961 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1962 match key.key.as_str() {
1963 "ArrowUp" if self.axis == Axis::Vertical => self.move_selection(ctx, -1),
1964 "ArrowDown" if self.axis == Axis::Vertical => self.move_selection(ctx, 1),
1965 "ArrowLeft" if self.axis == Axis::Horizontal => self.move_selection(ctx, -1),
1966 "ArrowRight" if self.axis == Axis::Horizontal => self.move_selection(ctx, 1),
1967 "Home" => {
1968 if let Some(index) = self.items.iter().position(|item| item.enabled) {
1969 self.select(ctx, index);
1970 }
1971 }
1972 "End" => {
1973 if let Some(index) = self.items.iter().rposition(|item| item.enabled) {
1974 self.select(ctx, index);
1975 }
1976 }
1977 "Enter" | " " => {
1978 if let Some(index) = self.current_selected() {
1979 self.select(ctx, index);
1980 }
1981 }
1982 _ => return,
1983 }
1984 ctx.request_paint();
1985 ctx.request_semantics();
1986 ctx.set_handled();
1987 }
1988 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1989 if self.advance_animations(*time) {
1990 ctx.request_animation_frame();
1991 }
1992 ctx.request_paint();
1993 }
1994 _ => {}
1995 }
1996 }
1997
1998 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1999 let theme = self.resolved_theme();
2000 let metrics = theme.metrics;
2001 let item_size = self.resolved_item_size(metrics);
2002 let spacing = self.resolved_spacing(metrics);
2003 let padding = self.resolved_padding(metrics);
2004 let extent = self.resolved_extent(metrics);
2005 let item_count = self.items.len();
2006 let main = if item_count == 0 {
2007 0.0
2008 } else {
2009 (item_size * item_count as f32) + (spacing * (item_count - 1) as f32)
2010 };
2011 let natural = match self.axis {
2012 Axis::Horizontal => Size::new(main + padding.left + padding.right, extent),
2013 Axis::Vertical => Size::new(extent, main + padding.top + padding.bottom),
2014 };
2015 let filled = match self.axis {
2016 Axis::Horizontal => Size::new(
2017 if constraints.max.width.is_finite() {
2018 constraints.max.width
2019 } else {
2020 natural.width
2021 },
2022 natural.height,
2023 ),
2024 Axis::Vertical => Size::new(
2025 natural.width,
2026 if constraints.max.height.is_finite() {
2027 constraints.max.height
2028 } else {
2029 natural.height
2030 },
2031 ),
2032 };
2033
2034 constraints.clamp(filled)
2035 }
2036
2037 fn paint(&self, ctx: &mut PaintCtx) {
2038 let theme = self.resolved_theme();
2039 let palette = theme.palette;
2040 let metrics = theme.metrics;
2041 let interaction = theme.interaction;
2042 let icon_size = self.resolved_icon_size(metrics);
2043 let bounds = ctx.bounds();
2044 ctx.fill_bounds(self.background.unwrap_or(palette.surface));
2045 if self.divider {
2046 let divider = match self.axis {
2047 Axis::Horizontal => {
2048 Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
2049 }
2050 Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
2051 };
2052 ctx.stroke_rect(
2053 divider,
2054 palette.border.with_alpha(0.85),
2055 StrokeStyle::new(1.0),
2056 );
2057 }
2058
2059 let selected = self.current_selected();
2060 for (index, item) in self.items.iter().enumerate() {
2061 let Some(rect) = self.item_rect(bounds, index) else {
2062 continue;
2063 };
2064 let selected_item = selected == Some(index);
2065 let hovered = self.hovered == Some(index);
2066 let hover_amount = self.hover_amount_for(index);
2067 let press_amount = self.press_amount_for(index);
2068 let enabled = item.enabled;
2069 let base_background = if selected_item {
2070 mix_color(palette.surface, palette.accent, interaction.selected_blend)
2071 } else {
2072 palette.surface
2073 };
2074 let background = if !enabled {
2075 mix_color(
2076 base_background,
2077 palette.surface,
2078 interaction.disabled_opacity,
2079 )
2080 } else if press_amount > 0.0 {
2081 mix_color(
2082 if hover_amount > 0.0 {
2083 mix_color(
2084 base_background,
2085 palette.control_hover,
2086 interaction.hover_blend
2087 * if selected_item { 0.35 } else { 1.0 }
2088 * hover_amount,
2089 )
2090 } else {
2091 base_background
2092 },
2093 palette.control_active,
2094 interaction.pressed_blend
2095 * if selected_item { 0.45 } else { 1.0 }
2096 * press_amount,
2097 )
2098 } else if hover_amount > 0.0 {
2099 mix_color(
2100 base_background,
2101 palette.control_hover,
2102 interaction.hover_blend * if selected_item { 0.35 } else { 1.0 } * hover_amount,
2103 )
2104 } else {
2105 base_background
2106 };
2107 let border = if !enabled {
2108 palette.border.with_alpha(0.55)
2109 } else if ctx.is_focused() && selected_item {
2110 palette.border_focus
2111 } else if selected_item {
2112 palette.accent_border
2113 } else if hovered || hover_amount > 0.0 || press_amount > 0.0 {
2114 palette.border_hover
2115 } else {
2116 palette.border
2117 };
2118 draw_control_frame(
2119 ctx,
2120 rect,
2121 metrics.corner_radius,
2122 metrics,
2123 background,
2124 border,
2125 (self.focus_animation.value > AnimatedScalar::EPSILON && selected_item).then_some(
2126 palette
2127 .focus_ring
2128 .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
2129 ),
2130 );
2131 let center = rect_center(rect);
2132 let side = icon_size.min(rect.width().min(rect.height())).max(0.0);
2133 let pressed_offset = press_amount * interaction.pressed_offset;
2134 let icon_rect = Rect::new(
2135 center.x - side * 0.5,
2136 center.y - side * 0.5 + pressed_offset,
2137 side,
2138 side,
2139 );
2140 draw_icon_glyph(
2141 ctx,
2142 item.icon,
2143 icon_rect,
2144 if !enabled {
2145 palette.text.with_alpha(0.38)
2146 } else if selected_item {
2147 palette.accent
2148 } else {
2149 palette.text
2150 },
2151 );
2152 }
2153 }
2154
2155 fn semantics(&self, ctx: &mut SemanticsCtx) {
2156 let selected = self.current_selected();
2157 let mut node = SemanticsNode::new(
2158 ctx.widget_id(),
2159 SemanticsRole::GenericContainer,
2160 ctx.bounds(),
2161 );
2162 node.name = Some(self.name.clone());
2163 node.value = selected
2164 .and_then(|index| self.items.get(index))
2165 .map(|item| SemanticsValue::Text(item.label.clone()));
2166 node.state.focused = ctx.is_focused();
2167 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2168 ctx.push(node);
2169
2170 for (index, item) in self.items.iter().enumerate() {
2171 let Some(rect) = self.item_rect(ctx.bounds(), index) else {
2172 continue;
2173 };
2174 let mut item_node = SemanticsNode::new(
2175 tool_palette_item_id(ctx.widget_id(), index),
2176 SemanticsRole::Button,
2177 rect,
2178 );
2179 item_node.parent = Some(ctx.widget_id());
2180 item_node.name = Some(item.label.clone());
2181 item_node.value = Some(SemanticsValue::Text(item.label.clone()));
2182 item_node.state.disabled = !item.enabled;
2183 item_node.state.hovered = self.hovered == Some(index);
2184 item_node.state.selected = selected == Some(index);
2185 if item.enabled {
2186 item_node.actions = vec![SemanticsAction::Activate];
2187 }
2188 ctx.push(item_node);
2189 }
2190 }
2191
2192 fn accepts_focus(&self) -> bool {
2193 self.items.iter().any(|item| item.enabled)
2194 }
2195
2196 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2197 let theme = self.resolved_theme();
2198 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2199 ctx.request_paint();
2200 ctx.request_semantics();
2201 }
2202}
2203
2204fn tool_palette_item_id(parent: WidgetId, index: usize) -> WidgetId {
2205 const TAG: u64 = 4_u64 << 50;
2206 const LOW_MASK: u64 = (1_u64 << 50) - 1;
2207
2208 WidgetId::new(
2209 TAG | (parent
2210 .get()
2211 .wrapping_mul(397)
2212 .wrapping_add(index as u64 + 1)
2213 & LOW_MASK),
2214 )
2215}
2216
2217pub struct ActionCard {
2218 theme: Box<DefaultTheme>,
2219 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2220 title: String,
2221 description: String,
2222 icon: Option<IconGlyph>,
2223 tone: SemanticTone,
2224 accent: Option<Color>,
2225 padding: Option<Insets>,
2226 min_width: Option<f32>,
2227 min_height: Option<f32>,
2228 hovered: bool,
2229 pressed: bool,
2230 hover_animation: AnimatedScalar,
2231 press_animation: AnimatedScalar,
2232 focus_animation: AnimatedScalar,
2233 title_measurement: Option<TextMeasurement>,
2234 description_measurement: Option<TextMeasurement>,
2235 enabled: bool,
2236 enabled_reader: Option<Box<dyn Fn() -> bool>>,
2237 on_press: Option<Box<dyn FnMut()>>,
2238 on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
2239}
2240
2241impl ActionCard {
2242 pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
2243 Self {
2244 theme: Box::new(DefaultTheme::default()),
2245 theme_reader: None,
2246 title: title.into(),
2247 description: description.into(),
2248 icon: None,
2249 tone: SemanticTone::Accent,
2250 accent: None,
2251 padding: None,
2252 min_width: None,
2253 min_height: None,
2254 hovered: false,
2255 pressed: false,
2256 hover_animation: AnimatedScalar::new(0.0),
2257 press_animation: AnimatedScalar::new(0.0),
2258 focus_animation: AnimatedScalar::new(0.0),
2259 title_measurement: None,
2260 description_measurement: None,
2261 enabled: true,
2262 enabled_reader: None,
2263 on_press: None,
2264 on_press_with_ctx: None,
2265 }
2266 }
2267
2268 pub fn theme(mut self, theme: DefaultTheme) -> Self {
2269 self.theme = Box::new(theme);
2270 self.theme_reader = None;
2271 self
2272 }
2273
2274 pub fn theme_when<F>(mut self, theme: F) -> Self
2275 where
2276 F: Fn() -> DefaultTheme + 'static,
2277 {
2278 self.theme_reader = Some(Box::new(theme));
2279 self
2280 }
2281
2282 pub fn icon(mut self, icon: IconGlyph) -> Self {
2283 self.icon = Some(icon);
2284 self
2285 }
2286
2287 pub fn without_icon(mut self) -> Self {
2288 self.icon = None;
2289 self
2290 }
2291
2292 pub fn accent(mut self, accent: Color) -> Self {
2293 self.accent = Some(accent);
2294 self
2295 }
2296
2297 pub fn tone(mut self, tone: SemanticTone) -> Self {
2298 self.tone = tone;
2299 self
2300 }
2301
2302 pub fn padding(mut self, padding: Insets) -> Self {
2303 self.padding = Some(padding);
2304 self
2305 }
2306
2307 pub fn min_width(mut self, width: f32) -> Self {
2308 self.min_width = Some(width.max(0.0));
2309 self
2310 }
2311
2312 pub fn min_height(mut self, height: f32) -> Self {
2313 self.min_height = Some(height.max(0.0));
2314 self
2315 }
2316
2317 pub fn enabled(mut self, enabled: bool) -> Self {
2318 self.enabled = enabled;
2319 self.enabled_reader = None;
2320 self
2321 }
2322
2323 pub fn enabled_when<F>(mut self, enabled: F) -> Self
2324 where
2325 F: Fn() -> bool + 'static,
2326 {
2327 self.enabled_reader = Some(Box::new(enabled));
2328 self
2329 }
2330
2331 pub fn on_press<F>(mut self, on_press: F) -> Self
2332 where
2333 F: FnMut() + 'static,
2334 {
2335 self.on_press = Some(Box::new(on_press));
2336 self
2337 }
2338
2339 pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
2340 where
2341 F: FnMut(&mut EventCtx) + 'static,
2342 {
2343 self.on_press_with_ctx = Some(Box::new(on_press));
2344 self
2345 }
2346
2347 fn is_enabled(&self) -> bool {
2348 self.enabled_reader
2349 .as_ref()
2350 .map(|enabled| enabled())
2351 .unwrap_or(self.enabled)
2352 }
2353
2354 fn resolved_theme(&self) -> DefaultTheme {
2355 self.theme_reader
2356 .as_ref()
2357 .map(|theme| theme())
2358 .unwrap_or(*self.theme)
2359 }
2360
2361 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
2362 self.padding.unwrap_or(metrics.action_card_padding)
2363 }
2364
2365 fn resolved_min_width(&self, metrics: ControlMetrics) -> f32 {
2366 self.min_width.unwrap_or(metrics.action_card_min_width)
2367 }
2368
2369 fn resolved_min_height(&self, metrics: ControlMetrics) -> f32 {
2370 self.min_height.unwrap_or(metrics.action_card_min_height)
2371 }
2372
2373 fn activate(&mut self, ctx: &mut EventCtx) {
2374 if !self.is_enabled() {
2375 return;
2376 }
2377 if let Some(on_press) = &mut self.on_press {
2378 on_press();
2379 }
2380 if let Some(on_press) = &mut self.on_press_with_ctx {
2381 on_press(ctx);
2382 }
2383 }
2384
2385 fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
2386 if self.hovered == hovered {
2387 return;
2388 }
2389 let theme = self.resolved_theme();
2390 self.hovered = hovered;
2391 set_action_card_hover_animation_target(
2392 &mut self.hover_animation,
2393 hovered as u8 as f32,
2394 &theme,
2395 ctx,
2396 );
2397 ctx.request_paint();
2398 ctx.request_semantics();
2399 }
2400
2401 fn advance_animations(&mut self, time: f64) -> bool {
2402 self.hover_animation.advance(time)
2403 | self.press_animation.advance(time)
2404 | self.focus_animation.advance(time)
2405 }
2406
2407 fn clear_transient_state_for_hidden_bounds(&mut self, ctx: &mut ArrangeCtx) {
2408 if !self.hovered && !self.pressed && !self.focus_animation.is_presented() {
2409 return;
2410 }
2411
2412 self.hovered = false;
2413 self.pressed = false;
2414 self.hover_animation = AnimatedScalar::new(0.0);
2415 self.press_animation = AnimatedScalar::new(0.0);
2416 self.focus_animation = AnimatedScalar::new(0.0);
2417 ctx.request_paint();
2418 ctx.request_semantics();
2419 }
2420
2421 fn resolved_title_style(&self) -> TextStyle {
2422 let theme = self.resolved_theme();
2423 TextStyle {
2424 weight: FontWeight::SEMIBOLD,
2425 ..text_token_style(&theme, theme.text.base, theme.palette.text)
2426 }
2427 }
2428
2429 fn resolved_description_style(&self) -> TextStyle {
2430 let theme = self.resolved_theme();
2431 text_token_style(&theme, theme.text.sm, theme.palette.text_muted)
2432 }
2433
2434 fn content_rect(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
2435 inset_rect(bounds, self.resolved_padding(metrics))
2436 }
2437
2438 fn text_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
2439 let content = self.content_rect(bounds, metrics);
2440 let icon_extent = self
2441 .icon
2442 .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
2443 .unwrap_or(0.0);
2444 let trailing = metrics.action_card_trailing_gap;
2445 Rect::new(
2446 content.x() + icon_extent,
2447 content.y(),
2448 (content.width() - icon_extent - trailing).max(0.0),
2449 content.height(),
2450 )
2451 }
2452}
2453
2454impl Widget for ActionCard {
2455 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2456 if !self.is_enabled() {
2457 if self.hovered || self.pressed {
2458 let theme = self.resolved_theme();
2459 self.hovered = false;
2460 self.pressed = false;
2461 set_action_card_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
2462 set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2463 ctx.request_paint();
2464 ctx.request_semantics();
2465 }
2466 return;
2467 }
2468
2469 match event {
2470 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2471 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2472 }
2473 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
2474 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2475 }
2476 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
2477 self.set_hovered(false, ctx);
2478 }
2479 Event::Pointer(pointer)
2480 if pointer.kind == PointerEventKind::Down
2481 && pointer.button == Some(PointerButton::Primary) =>
2482 {
2483 let theme = self.resolved_theme();
2484 self.pressed = true;
2485 self.hovered = true;
2486 set_action_card_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
2487 set_action_card_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
2488 ctx.request_pointer_capture(pointer.pointer_id);
2489 ctx.request_focus();
2490 ctx.request_paint();
2491 ctx.request_semantics();
2492 ctx.set_handled();
2493 }
2494 Event::Pointer(pointer)
2495 if pointer.kind == PointerEventKind::Up
2496 && pointer.button == Some(PointerButton::Primary) =>
2497 {
2498 let theme = self.resolved_theme();
2499 let hovered = ctx.bounds().contains(pointer.position);
2500 let activate = self.pressed && hovered;
2501 self.pressed = false;
2502 self.hovered = hovered;
2503 set_action_card_hover_animation_target(
2504 &mut self.hover_animation,
2505 hovered as u8 as f32,
2506 &theme,
2507 ctx,
2508 );
2509 set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2510 ctx.release_pointer_capture(pointer.pointer_id);
2511 if activate {
2512 self.activate(ctx);
2513 }
2514 ctx.request_paint();
2515 ctx.request_semantics();
2516 ctx.set_handled();
2517 }
2518 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2519 if self.pressed {
2520 let theme = self.resolved_theme();
2521 self.pressed = false;
2522 self.hovered = false;
2523 set_action_card_hover_animation_target(
2524 &mut self.hover_animation,
2525 0.0,
2526 &theme,
2527 ctx,
2528 );
2529 set_action_card_press_animation_target(
2530 &mut self.press_animation,
2531 0.0,
2532 &theme,
2533 ctx,
2534 );
2535 ctx.release_pointer_capture(pointer.pointer_id);
2536 ctx.request_paint();
2537 ctx.request_semantics();
2538 ctx.set_handled();
2539 }
2540 }
2541 Event::Keyboard(key)
2542 if key.state == KeyState::Pressed
2543 && ctx.is_focused()
2544 && matches!(key.key.as_str(), "Enter" | " ") =>
2545 {
2546 self.activate(ctx);
2547 ctx.request_paint();
2548 ctx.request_semantics();
2549 ctx.set_handled();
2550 }
2551 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
2552 if self.advance_animations(*time) {
2553 ctx.request_animation_frame();
2554 }
2555 ctx.request_paint();
2556 }
2557 _ => {}
2558 }
2559 }
2560
2561 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2562 let theme = self.resolved_theme();
2563 let metrics = theme.metrics;
2564 let padding = self.resolved_padding(metrics);
2565 let title_style = self.resolved_title_style();
2566 let description_style = self.resolved_description_style();
2567 let title = measure_text(ctx, &self.title, &title_style);
2568 let description = measure_text(ctx, &self.description, &description_style);
2569 self.title_measurement = Some(title);
2570 self.description_measurement = Some(description);
2571
2572 let icon_extent = self
2573 .icon
2574 .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
2575 .unwrap_or(0.0);
2576 let text_width = title.width.max(description.width).min(320.0);
2577 let natural = Size::new(
2578 self.resolved_min_width(metrics).max(
2579 padding.left
2580 + icon_extent
2581 + text_width
2582 + metrics.action_card_trailing_gap
2583 + padding.right,
2584 ),
2585 self.resolved_min_height(metrics).max(
2586 padding.top
2587 + title.height.max(title_style.line_height)
2588 + metrics.action_card_text_gap
2589 + description.height.max(description_style.line_height)
2590 + padding.bottom,
2591 ),
2592 );
2593 constraints.clamp(natural)
2594 }
2595
2596 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2597 if bounds.width() <= 0.0 || bounds.height() <= 0.0 {
2598 self.clear_transient_state_for_hidden_bounds(ctx);
2599 }
2600 }
2601
2602 fn paint(&self, ctx: &mut PaintCtx) {
2603 let theme = self.resolved_theme();
2604 let palette = theme.palette;
2605 let metrics = theme.metrics;
2606 let enabled = self.is_enabled();
2607 let hover = if enabled {
2608 self.hover_animation.value
2609 } else {
2610 0.0
2611 };
2612 let press = if enabled {
2613 self.press_animation.value
2614 } else {
2615 0.0
2616 };
2617 let accent = self
2618 .accent
2619 .unwrap_or_else(|| theme.semantic_tone_color(self.tone));
2620 let mut background = mix_color(palette.control, palette.control_hover, hover);
2621 background = mix_color(background, palette.control_active, press * 0.55);
2622 if !enabled {
2623 background = mix_color(background, palette.surface, 0.68).with_alpha(0.82);
2624 }
2625 let border = if !enabled {
2626 palette.border.with_alpha(0.55)
2627 } else if ctx.is_focused() {
2628 palette.border_focus
2629 } else {
2630 mix_color(palette.border, palette.border_hover, hover)
2631 };
2632
2633 if enabled {
2636 paint_theme_shadow(
2637 ctx,
2638 ctx.bounds(),
2639 [metrics.corner_radius; 4],
2640 &theme.shadows.box_shadow.md,
2641 );
2642 }
2643
2644 draw_control_frame(
2645 ctx,
2646 ctx.bounds(),
2647 metrics.corner_radius,
2648 metrics,
2649 background,
2650 border,
2651 (self.focus_animation.value > AnimatedScalar::EPSILON && enabled).then_some(
2652 palette
2653 .focus_ring
2654 .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
2655 ),
2656 );
2657
2658 let bounds = ctx.bounds();
2659 let content = self.content_rect(bounds, metrics);
2660 let accent_inset = metrics.action_card_accent_inset.min(bounds.height() * 0.5);
2661 let accent_height = (bounds.height() - accent_inset * 2.0).max(0.0);
2662 let accent_rail = Rect::new(
2663 bounds.x(),
2664 bounds.y() + accent_inset,
2665 metrics.action_card_accent_width,
2666 accent_height,
2667 );
2668 ctx.fill(
2669 rounded_rect_path(accent_rail, metrics.action_card_accent_width * 0.5),
2670 accent.with_alpha(0.78),
2671 );
2672
2673 if let Some(icon) = self.icon {
2674 let icon_box_size = metrics
2675 .action_card_icon_box_size
2676 .min(content.width())
2677 .min(content.height())
2678 .max(0.0);
2679 let icon_box = Rect::new(
2680 content.x(),
2681 content.y() + ((content.height() - icon_box_size) * 0.5),
2682 icon_box_size,
2683 icon_box_size,
2684 );
2685 ctx.fill(
2686 rounded_rect_path(icon_box, metrics.corner_radius),
2687 mix_color(background, accent, 0.14),
2688 );
2689 ctx.stroke(
2690 rounded_rect_path(icon_box, metrics.corner_radius),
2691 accent.with_alpha(if enabled { 0.42 } else { 0.22 }),
2692 StrokeStyle::new(physical_pixels(ctx, 1.0)),
2693 );
2694 let icon_size = metrics
2695 .action_card_icon_size
2696 .min(icon_box.width())
2697 .min(icon_box.height())
2698 .max(0.0);
2699 let icon_rect = Rect::new(
2700 icon_box.x() + ((icon_box.width() - icon_size) * 0.5),
2701 icon_box.y() + ((icon_box.height() - icon_size) * 0.5),
2702 icon_size,
2703 icon_size,
2704 );
2705 draw_icon_glyph(
2706 ctx,
2707 icon,
2708 icon_rect,
2709 if enabled {
2710 accent
2711 } else {
2712 palette.text.with_alpha(0.34)
2713 },
2714 );
2715 }
2716
2717 let text_bounds = self.text_bounds(bounds, metrics);
2718 let title_style = self.resolved_title_style();
2719 let description_style = self.resolved_description_style();
2720 let title_height = title_style.line_height.max(
2721 self.title_measurement
2722 .map(|measurement| measurement.height)
2723 .unwrap_or(title_style.line_height),
2724 );
2725 let description_min_height = description_style.line_height.max(
2726 self.description_measurement
2727 .map(|measurement| measurement.height)
2728 .unwrap_or(description_style.line_height),
2729 );
2730 let description_height =
2731 (text_bounds.height() - title_height - metrics.action_card_text_gap)
2732 .max(description_min_height)
2733 .min((description_style.line_height * 2.0).max(description_min_height));
2734 let text_block_height = title_height + metrics.action_card_text_gap + description_height;
2735 let text_y = text_bounds.y() + ((text_bounds.height() - text_block_height) * 0.5).max(0.0);
2736 let title_slot = Rect::new(text_bounds.x(), text_y, text_bounds.width(), title_height);
2737 let description_slot = Rect::new(
2738 text_bounds.x(),
2739 title_slot.max_y() + metrics.action_card_text_gap,
2740 text_bounds.width(),
2741 description_height,
2742 );
2743 let title_paint_style = TextStyle {
2744 color: if enabled {
2745 palette.text
2746 } else {
2747 palette.text.with_alpha(0.45)
2748 },
2749 ..title_style
2750 };
2751 let description_paint_style = TextStyle {
2752 color: if enabled {
2753 palette.placeholder
2754 } else {
2755 palette.placeholder.with_alpha(0.45)
2756 },
2757 ..description_style
2758 };
2759 let description_layout = {
2760 let mut layout_style = description_paint_style.clone();
2761 layout_style.color = Color::WHITE;
2762 ctx.shape_text(
2763 self.description.clone(),
2764 Size::new(
2765 description_slot.width().max(1.0),
2766 description_slot.height().max(1.0),
2767 ),
2768 layout_style,
2769 )
2770 .ok()
2771 };
2772 ctx.push_clip_rect(title_slot);
2773 paint_aligned_text(
2774 ctx,
2775 title_slot,
2776 &self.title,
2777 &title_paint_style,
2778 title_paint_style.line_height,
2779 0.0,
2780 );
2781 ctx.pop_clip();
2782 ctx.push_clip_rect(description_slot);
2783 if let Some(layout) = description_layout.filter(|layout| layout.lines().len() > 1) {
2784 let measurement = layout.measurement();
2785 let width = measurement.width.min(description_slot.width()).max(0.0);
2786 let height = description_paint_style
2787 .line_height
2788 .max(measurement.height)
2789 .min(description_slot.height());
2790 let description_rect = Rect::new(
2791 description_slot.x(),
2792 description_slot.y() + ((description_slot.height() - height).max(0.0) * 0.5),
2793 width,
2794 height,
2795 );
2796 ctx.draw_text_layout_with_color(
2797 description_rect.origin,
2798 &layout,
2799 description_paint_style.color,
2800 );
2801 } else {
2802 paint_aligned_text(
2803 ctx,
2804 description_slot,
2805 &self.description,
2806 &description_paint_style,
2807 description_paint_style.line_height,
2808 0.0,
2809 );
2810 }
2811 ctx.pop_clip();
2812
2813 let chevron_size = metrics
2814 .action_card_chevron_size
2815 .min(content.width())
2816 .min(content.height())
2817 .max(0.0);
2818 let chevron = Rect::new(
2819 content.max_x() - chevron_size,
2820 content.y() + ((content.height() - chevron_size) * 0.5),
2821 chevron_size,
2822 chevron_size,
2823 );
2824 draw_icon_glyph(
2825 ctx,
2826 IconGlyph::ChevronRight,
2827 chevron,
2828 if enabled {
2829 mix_color(palette.placeholder, accent, hover * 0.45).with_alpha(0.74)
2830 } else {
2831 palette.placeholder.with_alpha(0.32)
2832 },
2833 );
2834 }
2835
2836 fn semantics(&self, ctx: &mut SemanticsCtx) {
2837 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
2838 node.name = Some(self.title.clone());
2839 node.description = Some(self.description.clone());
2840 node.value = Some(SemanticsValue::Text(self.description.clone()));
2841 node.state.focused = ctx.is_focused();
2842 node.state.hovered = self.hovered && self.is_enabled();
2843 node.state.disabled = !self.is_enabled();
2844 node.actions = if self.is_enabled() {
2845 vec![SemanticsAction::Focus, SemanticsAction::Activate]
2846 } else {
2847 Vec::new()
2848 };
2849 ctx.push(node);
2850 }
2851
2852 fn accepts_focus(&self) -> bool {
2853 self.is_enabled()
2854 }
2855
2856 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2857 let theme = self.resolved_theme();
2858 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2859 ctx.request_paint();
2860 ctx.request_semantics();
2861 }
2862}
2863
2864fn set_animation_target(
2865 animation: &mut AnimatedScalar,
2866 target: f32,
2867 duration: f64,
2868 easing: crate::Easing,
2869 ctx: &mut EventCtx,
2870) -> bool {
2871 animation.set_target_event(target, duration, easing, ctx)
2872}
2873
2874fn set_hover_animation_target(
2875 animation: &mut AnimatedScalar,
2876 target: f32,
2877 theme: &DefaultTheme,
2878 ctx: &mut EventCtx,
2879) -> bool {
2880 set_animation_target(
2881 animation,
2882 target,
2883 theme.motion.hover_duration(),
2884 theme.motion.hover_easing(),
2885 ctx,
2886 )
2887}
2888
2889fn set_press_animation_target(
2890 animation: &mut AnimatedScalar,
2891 target: f32,
2892 theme: &DefaultTheme,
2893 ctx: &mut EventCtx,
2894) -> bool {
2895 set_animation_target(
2896 animation,
2897 target,
2898 theme.motion.press_duration(),
2899 theme.motion.press_easing(),
2900 ctx,
2901 )
2902}
2903
2904fn set_focus_animation_target(
2905 animation: &mut AnimatedScalar,
2906 target: f32,
2907 theme: &DefaultTheme,
2908 ctx: &mut EventCtx,
2909) -> bool {
2910 set_animation_target(
2911 animation,
2912 target,
2913 theme.motion.focus_duration(),
2914 theme.motion.focus_easing(),
2915 ctx,
2916 )
2917}
2918
2919fn set_action_card_animation_target(
2920 animation: &mut AnimatedScalar,
2921 target: f32,
2922 duration: f64,
2923 easing: crate::Easing,
2924 ctx: &mut EventCtx,
2925) {
2926 set_animation_target(animation, target, duration, easing, ctx);
2927}
2928
2929fn set_action_card_hover_animation_target(
2930 animation: &mut AnimatedScalar,
2931 target: f32,
2932 theme: &DefaultTheme,
2933 ctx: &mut EventCtx,
2934) {
2935 set_action_card_animation_target(
2936 animation,
2937 target,
2938 theme.motion.hover_duration(),
2939 theme.motion.hover_easing(),
2940 ctx,
2941 );
2942}
2943
2944fn set_action_card_press_animation_target(
2945 animation: &mut AnimatedScalar,
2946 target: f32,
2947 theme: &DefaultTheme,
2948 ctx: &mut EventCtx,
2949) {
2950 set_action_card_animation_target(
2951 animation,
2952 target,
2953 theme.motion.press_duration(),
2954 theme.motion.press_easing(),
2955 ctx,
2956 );
2957}
2958
2959#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2960pub enum PropertyRowLayout {
2961 Stacked,
2962 Inline,
2963}
2964
2965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2966enum PropertyRowDefaults {
2967 Property,
2968 Form,
2969}
2970
2971pub struct PropertyRow {
2972 theme: Box<DefaultTheme>,
2973 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2974 label: String,
2975 defaults: PropertyRowDefaults,
2976 layout: PropertyRowLayout,
2977 label_width: Option<f32>,
2978 control_width: Option<f32>,
2979 auto_control_width: bool,
2980 gap: Option<f32>,
2981 label_style: Option<TextStyle>,
2982 child: SingleChild,
2983 label_measurement: Option<TextMeasurement>,
2984}
2985
2986impl PropertyRow {
2987 pub fn new<W>(label: impl Into<String>, control: W) -> Self
2988 where
2989 W: Widget + 'static,
2990 {
2991 Self {
2992 theme: Box::new(DefaultTheme::default()),
2993 theme_reader: None,
2994 label: label.into(),
2995 defaults: PropertyRowDefaults::Property,
2996 layout: PropertyRowLayout::Stacked,
2997 label_width: None,
2998 control_width: None,
2999 auto_control_width: true,
3000 gap: None,
3001 label_style: None,
3002 child: SingleChild::new(control),
3003 label_measurement: None,
3004 }
3005 }
3006
3007 pub fn theme(mut self, theme: DefaultTheme) -> Self {
3008 self.theme = Box::new(theme);
3009 self.theme_reader = None;
3010 self
3011 }
3012
3013 pub fn theme_when<F>(mut self, theme: F) -> Self
3014 where
3015 F: Fn() -> DefaultTheme + 'static,
3016 {
3017 self.theme_reader = Some(Box::new(theme));
3018 self
3019 }
3020
3021 pub fn layout(mut self, layout: PropertyRowLayout) -> Self {
3022 self.layout = layout;
3023 self
3024 }
3025
3026 pub fn stacked(self) -> Self {
3027 self.layout(PropertyRowLayout::Stacked)
3028 }
3029
3030 pub fn inline(self) -> Self {
3031 self.layout(PropertyRowLayout::Inline)
3032 }
3033
3034 pub fn label_width(mut self, width: f32) -> Self {
3035 self.label_width = Some(width.max(0.0));
3036 self
3037 }
3038
3039 pub fn control_width(mut self, width: f32) -> Self {
3040 self.control_width = Some(width.max(0.0));
3041 self.auto_control_width = false;
3042 self
3043 }
3044
3045 pub fn auto_control_width(mut self) -> Self {
3046 self.control_width = None;
3047 self.auto_control_width = true;
3048 self
3049 }
3050
3051 pub fn gap(mut self, gap: f32) -> Self {
3052 self.gap = Some(gap.max(0.0));
3053 self
3054 }
3055
3056 pub fn label_style(mut self, style: TextStyle) -> Self {
3057 self.label_style = Some(style);
3058 self
3059 }
3060
3061 pub fn child(&self) -> &sui_runtime::WidgetPod {
3062 self.child.child()
3063 }
3064
3065 pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
3066 self.child.child_mut()
3067 }
3068
3069 fn resolved_label_style(&self) -> TextStyle {
3070 let theme = self.resolved_theme();
3071 self.label_style
3072 .clone()
3073 .unwrap_or_else(|| text_token_style(&theme, theme.text.sm, theme.palette.text_muted))
3074 }
3075
3076 fn resolved_theme(&self) -> DefaultTheme {
3077 self.theme_reader
3078 .as_ref()
3079 .map(|theme| theme())
3080 .unwrap_or(*self.theme)
3081 }
3082
3083 fn with_form_defaults(mut self) -> Self {
3084 self.defaults = PropertyRowDefaults::Form;
3085 self.auto_control_width = true;
3086 self
3087 }
3088
3089 fn resolved_label_width(&self, metrics: ControlMetrics) -> f32 {
3090 self.label_width.unwrap_or(match self.defaults {
3091 PropertyRowDefaults::Property => metrics.property_row_label_width,
3092 PropertyRowDefaults::Form => metrics.form_row_label_width,
3093 })
3094 }
3095
3096 fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
3097 self.gap.unwrap_or(match self.defaults {
3098 PropertyRowDefaults::Form => metrics.form_row_gap,
3099 PropertyRowDefaults::Property => match self.layout {
3100 PropertyRowLayout::Stacked => metrics.property_row_stacked_gap,
3101 PropertyRowLayout::Inline => metrics.property_row_inline_gap,
3102 },
3103 })
3104 }
3105
3106 fn resolved_control_width(&self, metrics: ControlMetrics) -> Option<f32> {
3107 if self.auto_control_width {
3108 None
3109 } else {
3110 self.control_width.or_else(|| {
3111 matches!(self.defaults, PropertyRowDefaults::Form)
3112 .then_some(metrics.form_row_control_width)
3113 })
3114 }
3115 }
3116
3117 fn label_height(&self, style: &TextStyle) -> f32 {
3118 self.label_measurement
3119 .map(|measurement| measurement.height)
3120 .unwrap_or(style.line_height)
3121 .max(style.line_height)
3122 }
3123
3124 fn child_constraints(
3125 &self,
3126 constraints: Constraints,
3127 label_extent: f32,
3128 metrics: ControlMetrics,
3129 ) -> Constraints {
3130 let max_width = constraints.max.width;
3131 let gap = self.resolved_gap(metrics);
3132 let available = match self.layout {
3133 PropertyRowLayout::Stacked => max_width,
3134 PropertyRowLayout::Inline => {
3135 if max_width.is_finite() {
3136 (max_width - label_extent - gap).max(0.0)
3137 } else {
3138 f32::INFINITY
3139 }
3140 }
3141 };
3142 let width = self
3143 .resolved_control_width(metrics)
3144 .map(|width| width.min(available).max(0.0));
3145
3146 match width {
3147 Some(width) => Constraints::new(
3148 Size::new(width, 0.0),
3149 Size::new(width, constraints.max.height),
3150 ),
3151 None => Constraints::new(Size::ZERO, Size::new(available, constraints.max.height)),
3152 }
3153 }
3154
3155 fn child_width_for_bounds(
3156 &self,
3157 bounds: Rect,
3158 label_extent: f32,
3159 metrics: ControlMetrics,
3160 ) -> f32 {
3161 let gap = self.resolved_gap(metrics);
3162 let available = match self.layout {
3163 PropertyRowLayout::Stacked => bounds.width(),
3164 PropertyRowLayout::Inline => (bounds.width() - label_extent - gap).max(0.0),
3165 };
3166 self.resolved_control_width(metrics)
3167 .unwrap_or(available)
3168 .min(available)
3169 .max(0.0)
3170 }
3171}
3172
3173impl Widget for PropertyRow {
3174 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3175 let theme = self.resolved_theme();
3176 let metrics = theme.metrics;
3177 let gap = self.resolved_gap(metrics);
3178 let label_style = self.resolved_label_style();
3179 let label_measurement = measure_text(ctx, &self.label, &label_style);
3180 self.label_measurement = Some(label_measurement);
3181 let label_height = self.label_height(&label_style);
3182 let label_extent = match self.layout {
3183 PropertyRowLayout::Stacked => label_measurement.width,
3184 PropertyRowLayout::Inline => self
3185 .resolved_label_width(metrics)
3186 .max(label_measurement.width),
3187 };
3188 let child_size = self.child.measure(
3189 ctx,
3190 self.child_constraints(constraints, label_extent, metrics),
3191 );
3192 let natural = match self.layout {
3193 PropertyRowLayout::Stacked => Size::new(
3194 label_measurement.width.max(child_size.width),
3195 label_height + gap + child_size.height,
3196 ),
3197 PropertyRowLayout::Inline => Size::new(
3198 label_extent + gap + child_size.width,
3199 label_height.max(child_size.height),
3200 ),
3201 };
3202
3203 constraints.clamp(natural)
3204 }
3205
3206 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3207 let theme = self.resolved_theme();
3208 let metrics = theme.metrics;
3209 let gap = self.resolved_gap(metrics);
3210 let label_style = self.resolved_label_style();
3211 let label_height = self.label_height(&label_style);
3212 let label_width = match self.layout {
3213 PropertyRowLayout::Stacked => bounds.width(),
3214 PropertyRowLayout::Inline => self
3215 .resolved_label_width(metrics)
3216 .min(bounds.width())
3217 .max(0.0),
3218 };
3219 let child_measured = self.child.child().measured_size();
3220 let child_width = self.child_width_for_bounds(bounds, label_width, metrics);
3221 let child_height = child_measured.height.min(bounds.height()).max(0.0);
3222
3223 let child_bounds = match self.layout {
3224 PropertyRowLayout::Stacked => Rect::new(
3225 bounds.x(),
3226 bounds.y() + label_height + gap,
3227 child_width,
3228 child_height.min((bounds.height() - label_height - gap).max(0.0)),
3229 ),
3230 PropertyRowLayout::Inline => Rect::new(
3231 bounds.x() + label_width + gap,
3232 bounds.y() + ((bounds.height() - child_height) * 0.5).max(0.0),
3233 child_width,
3234 child_height,
3235 ),
3236 };
3237 self.child.arrange(ctx, child_bounds);
3238 }
3239
3240 fn paint(&self, ctx: &mut PaintCtx) {
3241 let theme = self.resolved_theme();
3242 let metrics = theme.metrics;
3243 let label_style = self.resolved_label_style();
3244 let label_height = self.label_height(&label_style);
3245 let bounds = ctx.bounds();
3246 let label_rect = match self.layout {
3247 PropertyRowLayout::Stacked => {
3248 Rect::new(bounds.x(), bounds.y(), bounds.width(), label_height)
3249 }
3250 PropertyRowLayout::Inline => Rect::new(
3251 bounds.x(),
3252 bounds.y() + ((bounds.height() - label_height) * 0.5).max(0.0),
3253 self.resolved_label_width(metrics)
3254 .min(bounds.width())
3255 .max(0.0),
3256 label_height,
3257 ),
3258 };
3259 ctx.push_clip_rect(label_rect);
3260 paint_single_line_aligned_text(
3261 ctx,
3262 label_rect,
3263 &self.label,
3264 &label_style,
3265 label_height,
3266 0.0,
3267 );
3268 ctx.pop_clip();
3269 self.child.paint(ctx);
3270 }
3271
3272 fn semantics(&self, ctx: &mut SemanticsCtx) {
3273 let theme = self.resolved_theme();
3274 let metrics = theme.metrics;
3275 let mut row = SemanticsNode::new(
3276 ctx.widget_id(),
3277 SemanticsRole::GenericContainer,
3278 ctx.bounds(),
3279 );
3280 row.name = Some(self.label.clone());
3281 ctx.push(row);
3282
3283 let label_style = self.resolved_label_style();
3284 let label_height = self.label_height(&label_style);
3285 let label_bounds = match self.layout {
3286 PropertyRowLayout::Stacked => Rect::new(
3287 ctx.bounds().x(),
3288 ctx.bounds().y(),
3289 ctx.bounds().width(),
3290 label_height,
3291 ),
3292 PropertyRowLayout::Inline => Rect::new(
3293 ctx.bounds().x(),
3294 ctx.bounds().y() + ((ctx.bounds().height() - label_height) * 0.5).max(0.0),
3295 self.resolved_label_width(metrics)
3296 .min(ctx.bounds().width())
3297 .max(0.0),
3298 label_height,
3299 ),
3300 };
3301 let mut label = SemanticsNode::new(
3302 property_row_label_id(ctx.widget_id()),
3303 SemanticsRole::Text,
3304 label_bounds,
3305 );
3306 label.parent = Some(ctx.widget_id());
3307 label.name = Some(self.label.clone());
3308 label.value = Some(SemanticsValue::Text(self.label.clone()));
3309 ctx.push(label);
3310
3311 self.child.semantics(ctx);
3312 }
3313
3314 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3315 self.child.visit_children(visitor);
3316 }
3317
3318 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3319 self.child.visit_children_mut(visitor);
3320 }
3321}
3322
3323fn property_row_label_id(parent: WidgetId) -> WidgetId {
3324 const TAG: u64 = 1_u64 << 51;
3325 const LOW_MASK: u64 = (1_u64 << 51) - 1;
3326
3327 WidgetId::new(TAG | (parent.get().wrapping_mul(271).wrapping_add(1) & LOW_MASK))
3328}
3329
3330pub struct SectionLabel {
3331 theme: Box<DefaultTheme>,
3332 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3333 label: String,
3334 semantic_name: Option<String>,
3335 color: Option<Color>,
3336}
3337
3338impl SectionLabel {
3339 pub fn new(label: impl Into<String>) -> Self {
3340 Self {
3341 theme: Box::new(DefaultTheme::default()),
3342 theme_reader: None,
3343 label: label.into(),
3344 semantic_name: None,
3345 color: None,
3346 }
3347 }
3348
3349 pub fn theme(mut self, theme: DefaultTheme) -> Self {
3350 self.theme = Box::new(theme);
3351 self.theme_reader = None;
3352 self
3353 }
3354
3355 pub fn theme_when<F>(mut self, theme: F) -> Self
3356 where
3357 F: Fn() -> DefaultTheme + 'static,
3358 {
3359 self.theme_reader = Some(Box::new(theme));
3360 self
3361 }
3362
3363 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
3364 self.semantic_name = Some(name.into());
3365 self
3366 }
3367
3368 pub fn color(mut self, color: Color) -> Self {
3369 self.color = Some(color);
3370 self
3371 }
3372
3373 fn resolved_theme(&self) -> DefaultTheme {
3374 self.theme_reader
3375 .as_ref()
3376 .map(|theme| theme())
3377 .unwrap_or(*self.theme)
3378 }
3379
3380 fn display_text(&self) -> String {
3381 self.label.to_uppercase()
3382 }
3383
3384 fn text_style(&self, theme: &DefaultTheme) -> TextStyle {
3385 section_label_text_style(theme, self.color)
3386 }
3387}
3388
3389impl Widget for SectionLabel {
3390 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3391 let theme = self.resolved_theme();
3392 let style = self.text_style(&theme);
3393 let text = self.display_text();
3394 let measured = measure_text(ctx, &text, &style);
3395 constraints.clamp(Size::new(measured.width, style.line_height))
3396 }
3397
3398 fn paint(&self, ctx: &mut PaintCtx) {
3399 let theme = self.resolved_theme();
3400 let style = self.text_style(&theme);
3401 let text = self.display_text();
3402 ctx.push_clip_rect(ctx.bounds());
3403 paint_single_line_aligned_text(ctx, ctx.bounds(), &text, &style, style.line_height, 0.0);
3404 ctx.pop_clip();
3405 }
3406
3407 fn semantics(&self, ctx: &mut SemanticsCtx) {
3408 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
3409 let name = self
3410 .semantic_name
3411 .clone()
3412 .unwrap_or_else(|| self.label.clone());
3413 node.name = Some(name.clone());
3414 node.value = Some(SemanticsValue::Text(name));
3415 ctx.push(node);
3416 }
3417}
3418
3419#[derive(Debug, Clone, Copy, Default)]
3420pub struct SectionLabelPaint {
3421 color: Option<Color>,
3422}
3423
3424impl SectionLabelPaint {
3425 pub const fn new() -> Self {
3426 Self { color: None }
3427 }
3428
3429 pub const fn color(mut self, color: Color) -> Self {
3430 self.color = Some(color);
3431 self
3432 }
3433}
3434
3435pub fn paint_section_label(
3436 ctx: &mut PaintCtx,
3437 theme: &DefaultTheme,
3438 rect: Rect,
3439 label: &str,
3440 paint: SectionLabelPaint,
3441) {
3442 let style = section_label_text_style(theme, paint.color);
3443 let text = label.to_uppercase();
3444 ctx.push_clip_rect(rect);
3445 paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
3446 ctx.pop_clip();
3447}
3448
3449pub fn paint_section_label_detail(
3450 ctx: &mut PaintCtx,
3451 theme: &DefaultTheme,
3452 rect: Rect,
3453 label: &str,
3454 detail: &str,
3455 paint: SectionLabelPaint,
3456) {
3457 let style = section_label_text_style(theme, paint.color);
3458 let text = if detail.trim().is_empty() {
3459 label.to_uppercase()
3460 } else {
3461 format!("{} · {detail}", label.to_uppercase())
3462 };
3463 ctx.push_clip_rect(rect);
3464 paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
3465 ctx.pop_clip();
3466}
3467
3468fn section_label_text_style(theme: &DefaultTheme, color: Option<Color>) -> TextStyle {
3469 let mut style = text_token_style(
3470 theme,
3471 theme.text.xs,
3472 color.unwrap_or(theme.surfaces.text_faint),
3473 );
3474 style.weight = FontWeight::SEMIBOLD;
3475 style
3476}
3477
3478pub struct DetailRow {
3479 theme: Box<DefaultTheme>,
3480 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3481 label: String,
3482 label_reader: Option<Box<dyn Fn() -> String>>,
3483 value: String,
3484 value_reader: Option<Box<dyn Fn() -> String>>,
3485 max_value_lines: Option<usize>,
3486}
3487
3488impl DetailRow {
3489 pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
3490 Self {
3491 theme: Box::new(DefaultTheme::default()),
3492 theme_reader: None,
3493 label: label.into(),
3494 label_reader: None,
3495 value: value.into(),
3496 value_reader: None,
3497 max_value_lines: None,
3498 }
3499 }
3500
3501 pub fn theme(mut self, theme: DefaultTheme) -> Self {
3502 self.theme = Box::new(theme);
3503 self.theme_reader = None;
3504 self
3505 }
3506
3507 pub fn theme_when<F>(mut self, theme: F) -> Self
3508 where
3509 F: Fn() -> DefaultTheme + 'static,
3510 {
3511 self.theme_reader = Some(Box::new(theme));
3512 self
3513 }
3514
3515 pub fn label_when<F>(mut self, label: F) -> Self
3516 where
3517 F: Fn() -> String + 'static,
3518 {
3519 self.label_reader = Some(Box::new(label));
3520 self
3521 }
3522
3523 pub fn value_when<F>(mut self, value: F) -> Self
3524 where
3525 F: Fn() -> String + 'static,
3526 {
3527 self.value_reader = Some(Box::new(value));
3528 self
3529 }
3530
3531 pub fn max_value_lines(mut self, max_lines: usize) -> Self {
3532 self.max_value_lines = Some(max_lines.max(1));
3533 self
3534 }
3535
3536 fn label(&self) -> String {
3537 self.label_reader
3538 .as_ref()
3539 .map(|reader| reader())
3540 .unwrap_or_else(|| self.label.clone())
3541 }
3542
3543 fn value(&self) -> String {
3544 self.value_reader
3545 .as_ref()
3546 .map(|reader| reader())
3547 .unwrap_or_else(|| self.value.clone())
3548 }
3549
3550 fn resolved_theme(&self) -> DefaultTheme {
3551 self.theme_reader
3552 .as_ref()
3553 .map(|theme| theme())
3554 .unwrap_or(*self.theme)
3555 }
3556}
3557
3558impl Widget for DetailRow {
3559 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3560 let theme = self.resolved_theme();
3561 let label_style = detail_row_label_style(&theme);
3562 let value_style = detail_row_value_style(&theme);
3563 let width = if constraints.max.width.is_finite() {
3564 constraints.max.width.max(0.0)
3565 } else {
3566 let label = measure_text(ctx, &self.label().to_uppercase(), &label_style);
3567 let value = measure_text(ctx, &self.value(), &value_style);
3568 label.width.max(value.width)
3569 };
3570 let value = self.value();
3571 let lines = wrap_detail_row_value(&value, width, self.max_value_lines, |text| {
3572 measure_text(ctx, text, &value_style).width
3573 });
3574 constraints.clamp(Size::new(width, detail_row_height(&theme, lines.len())))
3575 }
3576
3577 fn paint(&self, ctx: &mut PaintCtx) {
3578 let theme = self.resolved_theme();
3579 paint_detail_row_at(
3580 ctx,
3581 &theme,
3582 Point::new(ctx.bounds().x(), ctx.bounds().y()),
3583 ctx.bounds().width(),
3584 &self.label(),
3585 &self.value(),
3586 self.max_value_lines,
3587 );
3588 }
3589
3590 fn semantics(&self, ctx: &mut SemanticsCtx) {
3591 let mut node = SemanticsNode::new(
3592 ctx.widget_id(),
3593 SemanticsRole::GenericContainer,
3594 ctx.bounds(),
3595 );
3596 node.name = Some(self.label());
3597 node.value = Some(SemanticsValue::Text(self.value()));
3598 ctx.push(node);
3599 }
3600}
3601
3602pub fn paint_detail_row_at(
3603 ctx: &mut PaintCtx,
3604 theme: &DefaultTheme,
3605 origin: Point,
3606 width: f32,
3607 label: &str,
3608 value: &str,
3609 max_value_lines: Option<usize>,
3610) -> f32 {
3611 let width = width.max(0.0);
3612 let label_style = detail_row_label_style(theme);
3613 let value_style = detail_row_value_style(theme);
3614 let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
3615 ctx.measure_text(text.to_string(), value_style.clone())
3616 .map(|measurement| measurement.width)
3617 .unwrap_or(0.0)
3618 });
3619 let height = detail_row_height(theme, lines.len());
3620 let clip = Rect::new(origin.x, origin.y, width, height);
3621
3622 ctx.push_clip_rect(clip);
3623 paint_aligned_text(
3624 ctx,
3625 Rect::new(origin.x, origin.y, width, label_style.line_height),
3626 &label.to_uppercase(),
3627 &label_style,
3628 label_style.line_height,
3629 0.0,
3630 );
3631
3632 let mut y = origin.y + label_style.line_height + detail_row_label_value_gap(theme);
3633 for line in lines {
3634 paint_aligned_text(
3635 ctx,
3636 Rect::new(origin.x, y, width, value_style.line_height),
3637 &line,
3638 &value_style,
3639 value_style.line_height,
3640 0.0,
3641 );
3642 y += value_style.line_height;
3643 }
3644 ctx.pop_clip();
3645 height
3646}
3647
3648pub fn detail_row_height_for_value(
3649 ctx: &PaintCtx,
3650 theme: &DefaultTheme,
3651 width: f32,
3652 value: &str,
3653 max_value_lines: Option<usize>,
3654) -> f32 {
3655 let width = width.max(0.0);
3656 let value_style = detail_row_value_style(theme);
3657 let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
3658 ctx.measure_text(text.to_string(), value_style.clone())
3659 .map(|measurement| measurement.width)
3660 .unwrap_or(0.0)
3661 });
3662 detail_row_height(theme, lines.len())
3663}
3664
3665fn detail_row_label_style(theme: &DefaultTheme) -> TextStyle {
3666 let mut style = text_token_style(theme, theme.text.xs, theme.palette.text_muted);
3667 style.weight = FontWeight::SEMIBOLD;
3668 style
3669}
3670
3671fn detail_row_value_style(theme: &DefaultTheme) -> TextStyle {
3672 text_token_style(theme, theme.text.sm, theme.palette.text)
3673}
3674
3675fn detail_row_label_value_gap(theme: &DefaultTheme) -> f32 {
3676 (theme.metrics.icon_label_gap * 0.35).max(2.0)
3677}
3678
3679fn detail_row_bottom_gap(theme: &DefaultTheme) -> f32 {
3680 theme.metrics.property_row_stacked_gap.max(6.0)
3681}
3682
3683fn detail_row_height(theme: &DefaultTheme, value_lines: usize) -> f32 {
3684 let label_style = detail_row_label_style(theme);
3685 let value_style = detail_row_value_style(theme);
3686 label_style.line_height
3687 + detail_row_label_value_gap(theme)
3688 + value_style.line_height * value_lines.max(1) as f32
3689 + detail_row_bottom_gap(theme)
3690}
3691
3692fn wrap_detail_row_value<F>(
3693 value: &str,
3694 width: f32,
3695 max_lines: Option<usize>,
3696 mut measure: F,
3697) -> Vec<String>
3698where
3699 F: FnMut(&str) -> f32,
3700{
3701 let max_lines = max_lines.unwrap_or(usize::MAX).max(1);
3702 let width = width.max(1.0);
3703 let mut lines = Vec::new();
3704
3705 for paragraph in value.split('\n') {
3706 if lines.len() >= max_lines {
3707 break;
3708 }
3709 let mut current = String::new();
3710 for word in paragraph.split_whitespace() {
3711 let candidate = if current.is_empty() {
3712 word.to_string()
3713 } else {
3714 format!("{current} {word}")
3715 };
3716 if current.is_empty() || measure(&candidate) <= width {
3717 current = candidate;
3718 } else {
3719 lines.push(std::mem::take(&mut current));
3720 if lines.len() >= max_lines {
3721 break;
3722 }
3723 current = word.to_string();
3724 }
3725 }
3726 if lines.len() < max_lines {
3727 lines.push(current);
3728 }
3729 }
3730
3731 if lines.is_empty() {
3732 lines.push(String::new());
3733 }
3734 lines
3735}
3736
3737pub struct FormRow {
3738 row: PropertyRow,
3739}
3740
3741impl FormRow {
3742 pub fn new<W>(label: impl Into<String>, control: W) -> Self
3743 where
3744 W: Widget + 'static,
3745 {
3746 Self {
3747 row: PropertyRow::new(label, control)
3748 .inline()
3749 .with_form_defaults(),
3750 }
3751 }
3752
3753 pub fn theme(mut self, theme: DefaultTheme) -> Self {
3754 self.row = self.row.theme(theme);
3755 self
3756 }
3757
3758 pub fn theme_when<F>(mut self, theme: F) -> Self
3759 where
3760 F: Fn() -> DefaultTheme + 'static,
3761 {
3762 self.row = self.row.theme_when(theme);
3763 self
3764 }
3765
3766 pub fn stacked(mut self) -> Self {
3767 self.row = self.row.stacked();
3768 self
3769 }
3770
3771 pub fn inline(mut self) -> Self {
3772 self.row = self.row.inline();
3773 self
3774 }
3775
3776 pub fn label_width(mut self, width: f32) -> Self {
3777 self.row = self.row.label_width(width);
3778 self
3779 }
3780
3781 pub fn control_width(mut self, width: f32) -> Self {
3782 self.row = self.row.control_width(width);
3783 self
3784 }
3785
3786 pub fn auto_control_width(mut self) -> Self {
3787 self.row = self.row.auto_control_width();
3788 self
3789 }
3790
3791 pub fn gap(mut self, gap: f32) -> Self {
3792 self.row = self.row.gap(gap);
3793 self
3794 }
3795
3796 pub fn label_style(mut self, style: TextStyle) -> Self {
3797 self.row = self.row.label_style(style);
3798 self
3799 }
3800
3801 pub fn child(&self) -> &sui_runtime::WidgetPod {
3802 self.row.child()
3803 }
3804
3805 pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
3806 self.row.child_mut()
3807 }
3808}
3809
3810impl Widget for FormRow {
3811 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3812 self.row.measure(ctx, constraints)
3813 }
3814
3815 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3816 self.row.arrange(ctx, bounds);
3817 }
3818
3819 fn paint(&self, ctx: &mut PaintCtx) {
3820 self.row.paint(ctx);
3821 }
3822
3823 fn semantics(&self, ctx: &mut SemanticsCtx) {
3824 self.row.semantics(ctx);
3825 }
3826
3827 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3828 self.row.visit_children(visitor);
3829 }
3830
3831 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3832 self.row.visit_children_mut(visitor);
3833 }
3834}
3835
3836pub struct FieldGroup {
3837 theme: Box<DefaultTheme>,
3838 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3839 children: WidgetChildren,
3840 spacing: Option<f32>,
3841 padding: Insets,
3842 max_width: Option<f32>,
3843 fill_width: bool,
3844}
3845
3846impl FieldGroup {
3847 pub fn new() -> Self {
3848 Self {
3849 theme: Box::new(DefaultTheme::default()),
3850 theme_reader: None,
3851 children: WidgetChildren::new(),
3852 spacing: None,
3853 padding: Insets::ZERO,
3854 max_width: None,
3855 fill_width: false,
3856 }
3857 }
3858
3859 pub fn theme(mut self, theme: DefaultTheme) -> Self {
3860 self.theme = Box::new(theme);
3861 self.theme_reader = None;
3862 self
3863 }
3864
3865 pub fn theme_when<F>(mut self, theme: F) -> Self
3866 where
3867 F: Fn() -> DefaultTheme + 'static,
3868 {
3869 self.theme_reader = Some(Box::new(theme));
3870 self
3871 }
3872
3873 pub fn with_child<W>(mut self, child: W) -> Self
3874 where
3875 W: Widget + 'static,
3876 {
3877 self.children.push(child);
3878 self
3879 }
3880
3881 pub fn push<W>(&mut self, child: W)
3882 where
3883 W: Widget + 'static,
3884 {
3885 self.children.push(child);
3886 }
3887
3888 pub fn spacing(mut self, spacing: f32) -> Self {
3889 self.spacing = Some(spacing.max(0.0));
3890 self
3891 }
3892
3893 pub fn padding(mut self, padding: Insets) -> Self {
3894 self.padding = padding;
3895 self
3896 }
3897
3898 pub fn max_width(mut self, width: f32) -> Self {
3899 self.max_width = Some(width.max(0.0));
3900 self
3901 }
3902
3903 pub fn auto_width(mut self) -> Self {
3904 self.max_width = None;
3905 self
3906 }
3907
3908 pub fn fill_width(mut self) -> Self {
3909 self.fill_width = true;
3910 self
3911 }
3912
3913 pub fn children(&self) -> &[sui_runtime::WidgetPod] {
3914 self.children.as_slice()
3915 }
3916
3917 pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
3918 self.children.as_mut_slice()
3919 }
3920
3921 fn content_max_width(&self, constraints: Constraints) -> f32 {
3922 let available = if constraints.max.width.is_finite() {
3923 (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
3924 } else {
3925 f32::INFINITY
3926 };
3927 self.max_width
3928 .map(|width| width.min(available))
3929 .unwrap_or(available)
3930 }
3931
3932 fn content_rect(&self, bounds: Rect) -> Rect {
3933 let inset = inset_rect(bounds, self.padding);
3934 let width = self
3935 .max_width
3936 .map(|max_width| max_width.min(inset.width()))
3937 .unwrap_or(inset.width())
3938 .max(0.0);
3939 Rect::new(inset.x(), inset.y(), width, inset.height())
3940 }
3941
3942 fn resolved_theme(&self) -> DefaultTheme {
3943 self.theme_reader
3944 .as_ref()
3945 .map(|theme| theme())
3946 .unwrap_or(*self.theme)
3947 }
3948
3949 fn resolved_spacing(&self) -> f32 {
3950 self.spacing
3951 .unwrap_or_else(|| self.resolved_theme().metrics.field_group_spacing)
3952 }
3953}
3954
3955impl Default for FieldGroup {
3956 fn default() -> Self {
3957 Self::new()
3958 }
3959}
3960
3961impl Widget for FieldGroup {
3962 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3963 let spacing = self.resolved_spacing();
3964 let content_max_width = self.content_max_width(constraints);
3965 let mut y: f32 = 0.0;
3966 let mut width: f32 = 0.0;
3967 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
3968 if index > 0 {
3969 y += spacing;
3970 }
3971 let child_size = child.measure(
3972 ctx,
3973 Constraints::new(
3974 Size::ZERO,
3975 Size::new(content_max_width, constraints.max.height),
3976 ),
3977 );
3978 y += child_size.height;
3979 width = width.max(child_size.width);
3980 }
3981
3982 if self.fill_width && content_max_width.is_finite() {
3983 width = content_max_width;
3984 }
3985
3986 constraints.clamp(Size::new(
3987 width + self.padding.left + self.padding.right,
3988 y + self.padding.top + self.padding.bottom,
3989 ))
3990 }
3991
3992 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3993 let spacing = self.resolved_spacing();
3994 let content = self.content_rect(bounds);
3995 let mut y = content.y();
3996 for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
3997 if index > 0 {
3998 y += spacing;
3999 }
4000 let measured = child.measured_size();
4001 let width = if self.fill_width {
4002 content.width()
4003 } else {
4004 measured.width.min(content.width())
4005 };
4006 child.arrange(ctx, Rect::new(content.x(), y, width, measured.height));
4007 y += measured.height;
4008 }
4009 }
4010
4011 fn paint(&self, ctx: &mut PaintCtx) {
4012 self.children.paint(ctx);
4013 }
4014
4015 fn semantics(&self, ctx: &mut SemanticsCtx) {
4016 self.children.semantics(ctx);
4017 }
4018
4019 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4020 self.children.visit_children(visitor);
4021 }
4022
4023 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4024 self.children.visit_children_mut(visitor);
4025 }
4026}
4027
4028pub struct FormSection {
4029 theme: Box<DefaultTheme>,
4030 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
4031 title: String,
4032 description: Option<String>,
4033 title_style: Option<TextStyle>,
4034 description_style: Option<TextStyle>,
4035 header_action: Option<SingleChild>,
4036 child: SingleChild,
4037 padding: Option<Insets>,
4038 body_gap: Option<f32>,
4039 header_gap: Option<f32>,
4040 description_gap: Option<f32>,
4041 max_width: Option<f32>,
4042 auto_width: bool,
4043 radius: Option<f32>,
4044 elevation: SurfaceElevation,
4045 fill_width: bool,
4046 title_measurement: Option<TextMeasurement>,
4047 description_measurement: Option<TextMeasurement>,
4048}
4049
4050impl FormSection {
4051 pub fn new<W>(title: impl Into<String>, child: W) -> Self
4052 where
4053 W: Widget + 'static,
4054 {
4055 Self {
4056 theme: Box::new(DefaultTheme::default()),
4057 theme_reader: None,
4058 title: title.into(),
4059 description: None,
4060 title_style: None,
4061 description_style: None,
4062 header_action: None,
4063 child: SingleChild::new(child),
4064 padding: None,
4065 body_gap: None,
4066 header_gap: None,
4067 description_gap: None,
4068 max_width: None,
4069 auto_width: false,
4070 radius: None,
4071 elevation: SurfaceElevation::Small,
4072 fill_width: false,
4073 title_measurement: None,
4074 description_measurement: None,
4075 }
4076 }
4077
4078 pub fn theme(mut self, theme: DefaultTheme) -> Self {
4079 self.theme = Box::new(theme);
4080 self.theme_reader = None;
4081 self
4082 }
4083
4084 pub fn theme_when<F>(mut self, theme: F) -> Self
4085 where
4086 F: Fn() -> DefaultTheme + 'static,
4087 {
4088 self.theme_reader = Some(Box::new(theme));
4089 self
4090 }
4091
4092 pub fn description(mut self, description: impl Into<String>) -> Self {
4093 self.description = Some(description.into());
4094 self
4095 }
4096
4097 pub fn title_style(mut self, style: TextStyle) -> Self {
4098 self.title_style = Some(style);
4099 self
4100 }
4101
4102 pub fn description_style(mut self, style: TextStyle) -> Self {
4103 self.description_style = Some(style);
4104 self
4105 }
4106
4107 pub fn header_action<W>(mut self, action: W) -> Self
4108 where
4109 W: Widget + 'static,
4110 {
4111 self.header_action = Some(SingleChild::new(action));
4112 self
4113 }
4114
4115 pub fn padding(mut self, padding: Insets) -> Self {
4116 self.padding = Some(padding);
4117 self
4118 }
4119
4120 pub fn body_gap(mut self, gap: f32) -> Self {
4121 self.body_gap = Some(gap.max(0.0));
4122 self
4123 }
4124
4125 pub fn header_gap(mut self, gap: f32) -> Self {
4126 self.header_gap = Some(gap.max(0.0));
4127 self
4128 }
4129
4130 pub fn max_width(mut self, width: f32) -> Self {
4131 self.max_width = Some(width.max(0.0));
4132 self.auto_width = false;
4133 self
4134 }
4135
4136 pub fn auto_width(mut self) -> Self {
4137 self.max_width = None;
4138 self.auto_width = true;
4139 self
4140 }
4141
4142 pub fn fill_width(mut self) -> Self {
4143 self.fill_width = true;
4144 self
4145 }
4146
4147 pub fn radius(mut self, radius: f32) -> Self {
4148 self.radius = Some(radius.max(0.0));
4149 self
4150 }
4151
4152 pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
4153 self.elevation = elevation;
4154 self
4155 }
4156
4157 pub fn child(&self) -> &sui_runtime::WidgetPod {
4158 self.child.child()
4159 }
4160
4161 pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
4162 self.child.child_mut()
4163 }
4164
4165 fn resolved_theme(&self) -> DefaultTheme {
4166 self.theme_reader
4167 .as_ref()
4168 .map(|theme| theme())
4169 .unwrap_or(*self.theme)
4170 }
4171
4172 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
4173 self.padding.unwrap_or(metrics.form_section_padding)
4174 }
4175
4176 fn resolved_body_gap(&self, metrics: ControlMetrics) -> f32 {
4177 self.body_gap.unwrap_or(metrics.form_section_body_gap)
4178 }
4179
4180 fn resolved_header_gap(&self, metrics: ControlMetrics) -> f32 {
4181 self.header_gap.unwrap_or(metrics.form_section_header_gap)
4182 }
4183
4184 fn resolved_description_gap(&self, metrics: ControlMetrics) -> f32 {
4185 self.description_gap
4186 .unwrap_or(metrics.form_section_description_gap)
4187 }
4188
4189 fn resolved_max_width(&self, metrics: ControlMetrics) -> Option<f32> {
4190 if self.auto_width {
4191 None
4192 } else {
4193 Some(self.max_width.unwrap_or(metrics.form_section_max_width))
4194 }
4195 }
4196
4197 fn resolved_radius(&self, metrics: ControlMetrics) -> f32 {
4198 self.radius.unwrap_or(metrics.form_section_radius).max(0.0)
4199 }
4200
4201 fn resolved_title_style(&self) -> TextStyle {
4202 let theme = self.resolved_theme();
4203 self.title_style.clone().unwrap_or_else(|| TextStyle {
4204 weight: FontWeight::SEMIBOLD,
4205 ..text_token_style(&theme, theme.text.sm, theme.surfaces.text)
4206 })
4207 }
4208
4209 fn resolved_description_style(&self) -> TextStyle {
4210 let theme = self.resolved_theme();
4211 self.description_style
4212 .clone()
4213 .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.surfaces.text_muted))
4214 }
4215
4216 fn title_height(&self, style: &TextStyle) -> f32 {
4217 self.title_measurement
4218 .map(|measurement| measurement.height)
4219 .unwrap_or(style.line_height)
4220 .max(style.line_height)
4221 }
4222
4223 fn description_height(&self, style: &TextStyle) -> f32 {
4224 if self.description.is_some() {
4225 self.description_measurement
4226 .map(|measurement| measurement.height)
4227 .unwrap_or(style.line_height)
4228 .max(style.line_height)
4229 } else {
4230 0.0
4231 }
4232 }
4233
4234 fn text_block_height(&self, title_style: &TextStyle, description_style: &TextStyle) -> f32 {
4235 let title = self.title_height(title_style);
4236 let description = self.description_height(description_style);
4237 if description > 0.0 {
4238 let metrics = self.resolved_theme().metrics;
4239 title + self.resolved_description_gap(metrics) + description
4240 } else {
4241 title
4242 }
4243 }
4244
4245 fn content_max_width(&self, available_width: f32) -> f32 {
4246 let theme = self.resolved_theme();
4247 let metrics = theme.metrics;
4248 let padding = self.resolved_padding(metrics);
4249 let available = if available_width.is_finite() {
4250 (available_width - padding.left - padding.right).max(0.0)
4251 } else {
4252 f32::INFINITY
4253 };
4254 self.resolved_max_width(metrics)
4255 .map(|width| width.min(available))
4256 .unwrap_or(available)
4257 }
4258
4259 fn card_rect(&self, bounds: Rect) -> Rect {
4260 let theme = self.resolved_theme();
4261 let metrics = theme.metrics;
4262 let padding = self.resolved_padding(metrics);
4263 let width = if self.fill_width {
4264 bounds.width()
4265 } else {
4266 self.resolved_max_width(metrics)
4267 .map(|max_width| (max_width + padding.left + padding.right).min(bounds.width()))
4268 .unwrap_or(bounds.width())
4269 }
4270 .max(0.0);
4271 let x = if self.fill_width || width >= bounds.width() {
4272 bounds.x()
4273 } else {
4274 bounds.x() + ((bounds.width() - width) * 0.5)
4275 };
4276 Rect::new(x, bounds.y(), width, bounds.height())
4277 }
4278
4279 fn content_rect(&self, bounds: Rect) -> Rect {
4280 let theme = self.resolved_theme();
4281 inset_rect(self.card_rect(bounds), self.resolved_padding(theme.metrics))
4282 }
4283
4284 fn header_height(&self, title_style: &TextStyle, description_style: &TextStyle) -> f32 {
4285 let text_height = self.text_block_height(title_style, description_style);
4286 let action_height = self
4287 .header_action
4288 .as_ref()
4289 .map(|action| action.child().measured_size().height)
4290 .unwrap_or(0.0);
4291 text_height.max(action_height)
4292 }
4293}
4294
4295impl Widget for FormSection {
4296 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4297 let theme = self.resolved_theme();
4298 let metrics = theme.metrics;
4299 let padding = self.resolved_padding(metrics);
4300 let body_gap = self.resolved_body_gap(metrics);
4301 let header_gap = self.resolved_header_gap(metrics);
4302 let title_style = self.resolved_title_style();
4303 let description_style = self.resolved_description_style();
4304 let title = measure_text(ctx, &self.title, &title_style);
4305 self.title_measurement = Some(title);
4306 let description = self
4307 .description
4308 .as_ref()
4309 .map(|description| measure_text(ctx, description, &description_style));
4310 self.description_measurement = description;
4311
4312 let content_max_width = self.content_max_width(constraints.max.width);
4313 let action_size = self
4314 .header_action
4315 .as_mut()
4316 .map(|action| {
4317 action.measure(
4318 ctx,
4319 Constraints::new(
4320 Size::ZERO,
4321 Size::new(content_max_width, constraints.max.height),
4322 ),
4323 )
4324 })
4325 .unwrap_or(Size::ZERO);
4326 let action_extent = if self.header_action.is_some() {
4327 action_size.width + header_gap
4328 } else {
4329 0.0
4330 };
4331 let text_width = title.width.max(
4332 description
4333 .map(|measurement| measurement.width)
4334 .unwrap_or(0.0),
4335 );
4336 let header_width = (text_width + action_extent).min(content_max_width);
4337 let child_size = self.child.measure(
4338 ctx,
4339 Constraints::new(
4340 Size::ZERO,
4341 Size::new(content_max_width, constraints.max.height),
4342 ),
4343 );
4344 let content_width = header_width.max(child_size.width).min(content_max_width);
4345 let header_height = self.header_height(&title_style, &description_style);
4346
4347 let mut width = content_width + padding.left + padding.right;
4348 if self.fill_width && constraints.max.width.is_finite() {
4349 width = constraints.max.width;
4350 }
4351 let height = padding.top + header_height + body_gap + child_size.height + padding.bottom;
4352 constraints.clamp(Size::new(width, height))
4353 }
4354
4355 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4356 let theme = self.resolved_theme();
4357 let metrics = theme.metrics;
4358 let body_gap = self.resolved_body_gap(metrics);
4359 let content = self.content_rect(bounds);
4360 let title_style = self.resolved_title_style();
4361 let description_style = self.resolved_description_style();
4362 let header_height = self.header_height(&title_style, &description_style);
4363
4364 if let Some(action) = &mut self.header_action {
4365 let action_size = action.child().measured_size();
4366 action.arrange(
4367 ctx,
4368 Rect::new(
4369 content.max_x() - action_size.width,
4370 content.y() + ((header_height - action_size.height) * 0.5).max(0.0),
4371 action_size.width,
4372 action_size.height,
4373 ),
4374 );
4375 }
4376
4377 let child_size = self.child.child().measured_size();
4378 self.child.arrange(
4379 ctx,
4380 Rect::new(
4381 content.x(),
4382 content.y() + header_height + body_gap,
4383 child_size.width.min(content.width()),
4384 child_size.height,
4385 ),
4386 );
4387 }
4388
4389 fn paint(&self, ctx: &mut PaintCtx) {
4390 let theme = self.resolved_theme();
4391 let metrics = theme.metrics;
4392 let card = self.card_rect(ctx.bounds());
4393 let radius = self
4394 .resolved_radius(metrics)
4395 .min(card.width().min(card.height()) * 0.5);
4396 let shadow = match self.elevation {
4397 SurfaceElevation::None => None,
4398 SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
4399 SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
4400 SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
4401 };
4402 if let Some(shadow) = shadow {
4403 paint_theme_shadow(ctx, card, [radius; 4], shadow);
4404 }
4405
4406 let background = theme.surfaces.panel;
4407 let border = theme.surfaces.border;
4408 let shape = rounded_rect_path(card, radius);
4409 ctx.fill(shape.clone(), background);
4410 ctx.stroke(
4411 shape,
4412 border,
4413 StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
4414 );
4415
4416 let content = inset_rect(card, self.resolved_padding(metrics));
4417 let title_style = self.resolved_title_style();
4418 let description_style = self.resolved_description_style();
4419 let title_height = self.title_height(&title_style);
4420 let description_height = self.description_height(&description_style);
4421 let header_gap = self.resolved_header_gap(metrics);
4422 let description_gap = self.resolved_description_gap(metrics);
4423 let action_width = self
4424 .header_action
4425 .as_ref()
4426 .map(|action| action.child().measured_size().width + header_gap)
4427 .unwrap_or(0.0)
4428 .min(content.width());
4429 let text_width = (content.width() - action_width).max(0.0);
4430 let text_block_height = self.text_block_height(&title_style, &description_style);
4431 let header_height = self.header_height(&title_style, &description_style);
4432 let text_y = content.y() + ((header_height - text_block_height) * 0.5).max(0.0);
4433 let title_slot = Rect::new(content.x(), text_y, text_width, title_height);
4434 ctx.push_clip_rect(title_slot);
4435 paint_aligned_text(
4436 ctx,
4437 title_slot,
4438 &self.title,
4439 &title_style,
4440 title_style.line_height,
4441 0.0,
4442 );
4443 ctx.pop_clip();
4444 if let Some(description) = &self.description {
4445 let description_slot = Rect::new(
4446 content.x(),
4447 title_slot.max_y() + description_gap,
4448 text_width,
4449 description_height,
4450 );
4451 ctx.push_clip_rect(description_slot);
4452 paint_aligned_text(
4453 ctx,
4454 description_slot,
4455 description,
4456 &description_style,
4457 description_style.line_height,
4458 0.0,
4459 );
4460 ctx.pop_clip();
4461 }
4462
4463 if let Some(action) = &self.header_action {
4464 action.paint(ctx);
4465 }
4466 self.child.paint(ctx);
4467 }
4468
4469 fn semantics(&self, ctx: &mut SemanticsCtx) {
4470 let card = self.card_rect(ctx.bounds());
4471 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::GenericContainer, card);
4472 node.name = Some(self.title.clone());
4473 node.description = self.description.clone();
4474 ctx.push(node);
4475 if let Some(action) = &self.header_action {
4476 action.semantics(ctx);
4477 }
4478 self.child.semantics(ctx);
4479 }
4480
4481 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4482 if let Some(action) = &self.header_action {
4483 action.visit_children(visitor);
4484 }
4485 self.child.visit_children(visitor);
4486 }
4487
4488 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4489 if let Some(action) = &mut self.header_action {
4490 action.visit_children_mut(visitor);
4491 }
4492 self.child.visit_children_mut(visitor);
4493 }
4494}
4495
4496pub struct PanelSection {
4497 theme: Box<DefaultTheme>,
4498 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
4499 title: String,
4500 gap: Option<f32>,
4501 action_gap: Option<f32>,
4502 title_style: Option<TextStyle>,
4503 header_action: Option<SingleChild>,
4504 child: SingleChild,
4505 title_measurement: Option<TextMeasurement>,
4506 collapsible: bool,
4507 expanded: bool,
4508 hovered_header: bool,
4509 pressed_header: bool,
4510 hover_animation: AnimatedScalar,
4511 press_animation: AnimatedScalar,
4512 focus_animation: AnimatedScalar,
4513}
4514
4515impl PanelSection {
4516 pub fn new<W>(title: impl Into<String>, child: W) -> Self
4517 where
4518 W: Widget + 'static,
4519 {
4520 Self {
4521 theme: Box::new(DefaultTheme::default()),
4522 theme_reader: None,
4523 title: title.into(),
4524 gap: None,
4525 action_gap: None,
4526 title_style: None,
4527 header_action: None,
4528 child: SingleChild::new(child),
4529 title_measurement: None,
4530 collapsible: false,
4531 expanded: true,
4532 hovered_header: false,
4533 pressed_header: false,
4534 hover_animation: AnimatedScalar::new(0.0),
4535 press_animation: AnimatedScalar::new(0.0),
4536 focus_animation: AnimatedScalar::new(0.0),
4537 }
4538 }
4539
4540 pub fn theme(mut self, theme: DefaultTheme) -> Self {
4541 self.theme = Box::new(theme);
4542 self.theme_reader = None;
4543 self
4544 }
4545
4546 pub fn theme_when<F>(mut self, theme: F) -> Self
4547 where
4548 F: Fn() -> DefaultTheme + 'static,
4549 {
4550 self.theme_reader = Some(Box::new(theme));
4551 self
4552 }
4553
4554 pub fn gap(mut self, gap: f32) -> Self {
4555 self.gap = Some(gap.max(0.0));
4556 self
4557 }
4558
4559 pub fn title_style(mut self, style: TextStyle) -> Self {
4560 self.title_style = Some(style);
4561 self
4562 }
4563
4564 pub fn header_action<W>(mut self, action: W) -> Self
4565 where
4566 W: Widget + 'static,
4567 {
4568 self.header_action = Some(SingleChild::new(action));
4569 self
4570 }
4571
4572 pub fn action_gap(mut self, gap: f32) -> Self {
4573 self.action_gap = Some(gap.max(0.0));
4574 self
4575 }
4576
4577 pub fn collapsible(mut self, collapsible: bool) -> Self {
4578 self.collapsible = collapsible;
4579 self
4580 }
4581
4582 pub fn expanded(mut self, expanded: bool) -> Self {
4583 self.expanded = expanded;
4584 self
4585 }
4586
4587 pub fn collapsed(mut self) -> Self {
4588 self.expanded = false;
4589 self
4590 }
4591
4592 pub fn child(&self) -> &sui_runtime::WidgetPod {
4593 self.child.child()
4594 }
4595
4596 pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
4597 self.child.child_mut()
4598 }
4599
4600 fn resolved_title_style(&self) -> TextStyle {
4601 let theme = self.resolved_theme();
4602 self.title_style
4603 .clone()
4604 .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.palette.text_muted))
4605 }
4606
4607 fn resolved_theme(&self) -> DefaultTheme {
4608 self.theme_reader
4609 .as_ref()
4610 .map(|theme| theme())
4611 .unwrap_or(*self.theme)
4612 }
4613
4614 fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
4615 self.gap.unwrap_or(metrics.panel_section_gap)
4616 }
4617
4618 fn resolved_action_gap(&self, metrics: ControlMetrics) -> f32 {
4619 self.action_gap.unwrap_or(metrics.panel_section_action_gap)
4620 }
4621
4622 fn title_height(&self, style: &TextStyle) -> f32 {
4623 self.title_measurement
4624 .map(|measurement| measurement.height)
4625 .unwrap_or(style.line_height)
4626 .max(style.line_height)
4627 }
4628
4629 fn header_height(&self, title_style: &TextStyle) -> f32 {
4630 let action_height = self
4631 .header_action
4632 .as_ref()
4633 .map(|action| action.child().measured_size().height)
4634 .unwrap_or(0.0);
4635 self.title_height(title_style).max(action_height)
4636 }
4637
4638 fn is_expanded(&self) -> bool {
4639 !self.collapsible || self.expanded
4640 }
4641
4642 fn disclosure_width(&self, metrics: ControlMetrics) -> f32 {
4643 if self.collapsible {
4644 metrics.panel_section_disclosure_size
4645 } else {
4646 0.0
4647 }
4648 }
4649
4650 fn title_rect(&self, bounds: Rect, header_height: f32, title_height: f32) -> Rect {
4651 let metrics = self.resolved_theme().metrics;
4652 let action_width = self
4653 .header_action
4654 .as_ref()
4655 .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
4656 .unwrap_or(0.0)
4657 .min(bounds.width());
4658 let disclosure_width = self.disclosure_width(metrics);
4659 Rect::new(
4660 bounds.x() + disclosure_width,
4661 bounds.y() + ((header_height - title_height) * 0.5).max(0.0),
4662 (bounds.width() - action_width - disclosure_width).max(0.0),
4663 title_height,
4664 )
4665 }
4666
4667 fn header_rect(&self, bounds: Rect) -> Rect {
4668 let title_style = self.resolved_title_style();
4669 let header_height = self.header_height(&title_style);
4670 Rect::new(bounds.x(), bounds.y(), bounds.width(), header_height)
4671 }
4672
4673 fn header_hit_rect(&self, bounds: Rect) -> Rect {
4674 let metrics = self.resolved_theme().metrics;
4675 let header = self.header_rect(bounds);
4676 let action_width = self
4677 .header_action
4678 .as_ref()
4679 .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
4680 .unwrap_or(0.0)
4681 .min(header.width());
4682 Rect::new(
4683 header.x(),
4684 header.y(),
4685 (header.width() - action_width).max(0.0),
4686 header.height(),
4687 )
4688 }
4689
4690 fn toggle(&mut self, ctx: &mut EventCtx) {
4691 if !self.collapsible {
4692 return;
4693 }
4694
4695 self.expanded = !self.expanded;
4696 self.set_pressed_header(false, ctx);
4697 ctx.request_measure();
4698 ctx.request_paint();
4699 ctx.request_semantics();
4700 }
4701
4702 fn set_hovered_header(&mut self, hovered: bool, ctx: &mut EventCtx) {
4703 if self.hovered_header == hovered {
4704 return;
4705 }
4706 let theme = self.resolved_theme();
4707 self.hovered_header = hovered;
4708 set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
4709 ctx.request_paint();
4710 ctx.request_semantics();
4711 }
4712
4713 fn set_pressed_header(&mut self, pressed: bool, ctx: &mut EventCtx) {
4714 if self.pressed_header == pressed {
4715 return;
4716 }
4717 let theme = self.resolved_theme();
4718 self.pressed_header = pressed;
4719 set_press_animation_target(&mut self.press_animation, pressed as u8 as f32, &theme, ctx);
4720 ctx.request_paint();
4721 ctx.request_semantics();
4722 }
4723
4724 fn advance_animations(&mut self, time: f64) -> bool {
4725 self.hover_animation.advance(time)
4726 | self.press_animation.advance(time)
4727 | self.focus_animation.advance(time)
4728 }
4729}
4730
4731impl Widget for PanelSection {
4732 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4733 if !self.collapsible {
4734 return;
4735 }
4736
4737 match event {
4738 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
4739 let hovered = self
4740 .header_hit_rect(ctx.bounds())
4741 .contains(pointer.position);
4742 self.set_hovered_header(hovered, ctx);
4743 }
4744 Event::Pointer(pointer)
4745 if pointer.kind == PointerEventKind::Down
4746 && pointer.button == Some(PointerButton::Primary)
4747 && self
4748 .header_hit_rect(ctx.bounds())
4749 .contains(pointer.position) =>
4750 {
4751 self.set_hovered_header(true, ctx);
4752 self.set_pressed_header(true, ctx);
4753 ctx.request_focus();
4754 ctx.request_pointer_capture(pointer.pointer_id);
4755 ctx.set_handled();
4756 }
4757 Event::Pointer(pointer)
4758 if pointer.kind == PointerEventKind::Up
4759 && pointer.button == Some(PointerButton::Primary)
4760 && self.pressed_header =>
4761 {
4762 let hovered = self
4763 .header_hit_rect(ctx.bounds())
4764 .contains(pointer.position);
4765 if hovered {
4766 self.toggle(ctx);
4767 }
4768 self.set_hovered_header(hovered, ctx);
4769 self.set_pressed_header(false, ctx);
4770 ctx.release_pointer_capture(pointer.pointer_id);
4771 ctx.set_handled();
4772 }
4773 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
4774 self.set_hovered_header(false, ctx);
4775 }
4776 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
4777 if self.pressed_header || self.hovered_header {
4778 self.set_hovered_header(false, ctx);
4779 self.set_pressed_header(false, ctx);
4780 ctx.release_pointer_capture(pointer.pointer_id);
4781 ctx.set_handled();
4782 }
4783 }
4784 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
4785 match key.key.as_str() {
4786 "Enter" | " " => {
4787 self.toggle(ctx);
4788 ctx.set_handled();
4789 }
4790 _ => {}
4791 }
4792 }
4793 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
4794 if self.advance_animations(*time) {
4795 ctx.request_animation_frame();
4796 }
4797 ctx.request_paint();
4798 }
4799 _ => {}
4800 }
4801 }
4802
4803 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4804 let theme = self.resolved_theme();
4805 let metrics = theme.metrics;
4806 let gap = self.resolved_gap(metrics);
4807 let action_gap = self.resolved_action_gap(metrics);
4808 let title_style = self.resolved_title_style();
4809 let title_measurement = measure_text(ctx, &self.title, &title_style);
4810 self.title_measurement = Some(title_measurement);
4811 let action_size = self
4812 .header_action
4813 .as_mut()
4814 .map(|action| {
4815 action.measure(
4816 ctx,
4817 Constraints::new(Size::ZERO, Size::new(constraints.max.width, f32::INFINITY)),
4818 )
4819 })
4820 .unwrap_or(Size::ZERO);
4821 let header_height = self.title_height(&title_style).max(action_size.height);
4822 let child_size = if self.is_expanded() {
4823 self.child.measure(ctx, constraints)
4824 } else {
4825 Size::ZERO
4826 };
4827 let header_width = if self.header_action.is_some() {
4828 self.disclosure_width(metrics)
4829 + title_measurement.width
4830 + action_gap
4831 + action_size.width
4832 } else {
4833 self.disclosure_width(metrics) + title_measurement.width
4834 };
4835 let natural = Size::new(
4836 header_width.max(child_size.width),
4837 header_height
4838 + if self.is_expanded() && child_size.height > 0.0 {
4839 gap + child_size.height
4840 } else {
4841 0.0
4842 },
4843 );
4844
4845 constraints.clamp(natural)
4846 }
4847
4848 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4849 let theme = self.resolved_theme();
4850 let metrics = theme.metrics;
4851 let gap = self.resolved_gap(metrics);
4852 let title_style = self.resolved_title_style();
4853 let header_height = self.header_height(&title_style);
4854 if let Some(action) = &mut self.header_action {
4855 let action_size = action.child().measured_size();
4856 action.arrange(
4857 ctx,
4858 Rect::new(
4859 bounds.max_x() - action_size.width.min(bounds.width()),
4860 bounds.y() + ((header_height - action_size.height) * 0.5).max(0.0),
4861 action_size.width.min(bounds.width()).max(0.0),
4862 action_size.height,
4863 ),
4864 );
4865 }
4866 let child_size = if self.is_expanded() {
4867 self.child.child().measured_size()
4868 } else {
4869 Size::ZERO
4870 };
4871 let child_height = if self.is_expanded() {
4872 child_size
4873 .height
4874 .min((bounds.height() - header_height - gap).max(0.0))
4875 } else {
4876 0.0
4877 };
4878 self.child.arrange(
4879 ctx,
4880 Rect::new(
4881 bounds.x(),
4882 bounds.y() + header_height + gap,
4883 bounds.width().min(child_size.width).max(0.0),
4884 child_height,
4885 ),
4886 );
4887 }
4888
4889 fn paint(&self, ctx: &mut PaintCtx) {
4890 let theme = self.resolved_theme();
4891 let metrics = theme.metrics;
4892 let title_style = self.resolved_title_style();
4893 let title_height = self.title_height(&title_style);
4894 let header_height = self.header_height(&title_style);
4895 let title_slot = self.title_rect(ctx.bounds(), header_height, title_height);
4896 if self.collapsible {
4897 let header_hit = self.header_hit_rect(ctx.bounds());
4898 let hover_amount = self.hover_animation.value;
4899 let press_amount = self.press_animation.value;
4900 let focus_amount = self.focus_animation.value;
4901 if focus_amount > AnimatedScalar::EPSILON {
4902 let outset = physical_pixels(ctx, metrics.focus_ring_outset);
4903 ctx.stroke(
4904 rounded_rect_path(
4905 header_hit.inflate(outset, outset),
4906 metrics.indicator_corner_radius + outset,
4907 ),
4908 theme
4909 .palette
4910 .focus_ring
4911 .with_alpha(theme.palette.focus_ring.alpha * focus_amount),
4912 StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
4913 );
4914 }
4915 let hover_alpha = (theme.interaction.hover_blend * 0.07 * hover_amount).min(0.08);
4916 let press_alpha = (theme.interaction.selected_blend * 0.48 * press_amount).min(0.14);
4917 let header_fill = if press_alpha > 0.0 {
4918 theme.palette.accent.with_alpha(press_alpha)
4919 } else if hover_alpha > 0.0 {
4920 theme.palette.accent.with_alpha(hover_alpha)
4921 } else {
4922 theme.palette.surface.with_alpha(0.001)
4923 };
4924 ctx.fill(
4925 rounded_rect_path(header_hit, metrics.indicator_corner_radius),
4926 header_fill,
4927 );
4928 paint_panel_section_disclosure(
4929 ctx,
4930 self.header_rect(ctx.bounds()),
4931 self.expanded,
4932 hover_amount,
4933 press_amount,
4934 &theme,
4935 metrics.panel_section_disclosure_size,
4936 );
4937 }
4938 ctx.push_clip_rect(title_slot);
4939 paint_aligned_text(
4940 ctx,
4941 title_slot,
4942 &self.title,
4943 &title_style,
4944 title_style.line_height,
4945 0.0,
4946 );
4947 ctx.pop_clip();
4948 if let Some(action) = &self.header_action {
4949 action.paint(ctx);
4950 }
4951 if self.is_expanded() {
4952 self.child.paint(ctx);
4953 }
4954 }
4955
4956 fn semantics(&self, ctx: &mut SemanticsCtx) {
4957 let mut section = SemanticsNode::new(
4958 ctx.widget_id(),
4959 SemanticsRole::GenericContainer,
4960 ctx.bounds(),
4961 );
4962 section.name = Some(self.title.clone());
4963 section.state.focused = ctx.is_focused();
4964 section.state.hovered = self.hovered_header;
4965 if self.collapsible {
4966 section.state.expanded = Some(self.expanded);
4967 section.actions = vec![
4968 SemanticsAction::Focus,
4969 SemanticsAction::Expand,
4970 SemanticsAction::Collapse,
4971 ];
4972 }
4973 ctx.push(section);
4974
4975 let title_style = self.resolved_title_style();
4976 let title_height = self.title_height(&title_style);
4977 let header_height = self.header_height(&title_style);
4978 let mut title = SemanticsNode::new(
4979 panel_section_title_id(ctx.widget_id()),
4980 SemanticsRole::Text,
4981 self.title_rect(ctx.bounds(), header_height, title_height),
4982 );
4983 title.parent = Some(ctx.widget_id());
4984 title.name = Some(self.title.clone());
4985 title.value = Some(SemanticsValue::Text(self.title.clone()));
4986 ctx.push(title);
4987
4988 if let Some(action) = &self.header_action {
4989 action.semantics(ctx);
4990 }
4991 if self.is_expanded() {
4992 self.child.semantics(ctx);
4993 }
4994 }
4995
4996 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4997 if let Some(action) = &self.header_action {
4998 action.visit_children(visitor);
4999 }
5000 if self.is_expanded() {
5001 self.child.visit_children(visitor);
5002 }
5003 }
5004
5005 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5006 if let Some(action) = &mut self.header_action {
5007 action.visit_children_mut(visitor);
5008 }
5009 if self.is_expanded() {
5010 self.child.visit_children_mut(visitor);
5011 }
5012 }
5013
5014 fn accepts_focus(&self) -> bool {
5015 self.collapsible
5016 }
5017
5018 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
5019 if self.collapsible {
5020 let theme = self.resolved_theme();
5021 set_focus_animation_target(
5022 &mut self.focus_animation,
5023 focused as u8 as f32,
5024 &theme,
5025 ctx,
5026 );
5027 ctx.request_paint();
5028 ctx.request_semantics();
5029 }
5030 }
5031}
5032
5033fn panel_section_title_id(parent: WidgetId) -> WidgetId {
5034 const TAG: u64 = 3_u64 << 50;
5035 const LOW_MASK: u64 = (1_u64 << 50) - 1;
5036
5037 WidgetId::new(TAG | (parent.get().wrapping_mul(431).wrapping_add(7) & LOW_MASK))
5038}
5039
5040fn paint_panel_section_disclosure(
5041 ctx: &mut PaintCtx,
5042 header: Rect,
5043 expanded: bool,
5044 hover_amount: f32,
5045 press_amount: f32,
5046 theme: &DefaultTheme,
5047 disclosure_size: f32,
5048) {
5049 let palette = theme.palette;
5050 let center = Point::new(
5051 header.x() + disclosure_size * 0.5,
5052 header.y() + header.height() * 0.5,
5053 );
5054 let half = disclosure_size * 0.25;
5055 let tip = disclosure_size * 0.22;
5056 let base_color = palette.text.with_alpha(0.68);
5057 let hover_color = mix_color(base_color, palette.text, hover_amount);
5058 let color = mix_color(hover_color, palette.accent, press_amount);
5059 let mut builder = PathBuilder::new();
5060 if expanded {
5061 builder
5062 .move_to(Point::new(center.x - half, center.y - tip * 0.55))
5063 .line_to(Point::new(center.x + half, center.y - tip * 0.55))
5064 .line_to(Point::new(center.x, center.y + tip));
5065 } else {
5066 builder
5067 .move_to(Point::new(center.x - tip * 0.55, center.y - half))
5068 .line_to(Point::new(center.x + tip, center.y))
5069 .line_to(Point::new(center.x - tip * 0.55, center.y + half));
5070 }
5071 ctx.fill(builder.build(), color);
5072}
5073
5074pub struct DockPanel {
5075 theme: Box<DefaultTheme>,
5076 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5077 name: Option<String>,
5078 title: String,
5079 header_height: Option<f32>,
5080 padding: Option<Insets>,
5081 background: Option<Color>,
5082 header_background: Option<Color>,
5083 child: SingleChild,
5084 title_measurement: Option<TextMeasurement>,
5085}
5086
5087impl DockPanel {
5088 pub fn new<W>(title: impl Into<String>, child: W) -> Self
5089 where
5090 W: Widget + 'static,
5091 {
5092 Self {
5093 theme: Box::new(DefaultTheme::default()),
5094 theme_reader: None,
5095 name: None,
5096 title: title.into(),
5097 header_height: None,
5098 padding: None,
5099 background: None,
5100 header_background: None,
5101 child: SingleChild::new(child),
5102 title_measurement: None,
5103 }
5104 }
5105
5106 pub fn theme(mut self, theme: DefaultTheme) -> Self {
5107 self.theme = Box::new(theme);
5108 self.theme_reader = None;
5109 self
5110 }
5111
5112 pub fn theme_when<F>(mut self, theme: F) -> Self
5113 where
5114 F: Fn() -> DefaultTheme + 'static,
5115 {
5116 self.theme_reader = Some(Box::new(theme));
5117 self
5118 }
5119
5120 pub fn name(mut self, name: impl Into<String>) -> Self {
5121 self.name = Some(name.into());
5122 self
5123 }
5124
5125 pub fn header_height(mut self, height: f32) -> Self {
5126 self.header_height = Some(height.max(0.0));
5127 self
5128 }
5129
5130 pub fn padding(mut self, padding: Insets) -> Self {
5131 self.padding = Some(padding);
5132 self
5133 }
5134
5135 pub fn background(mut self, color: Color) -> Self {
5136 self.background = Some(color);
5137 self
5138 }
5139
5140 pub fn header_background(mut self, color: Color) -> Self {
5141 self.header_background = Some(color);
5142 self
5143 }
5144
5145 pub fn child(&self) -> &sui_runtime::WidgetPod {
5146 self.child.child()
5147 }
5148
5149 pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
5150 self.child.child_mut()
5151 }
5152
5153 fn resolved_title_style(&self) -> TextStyle {
5154 let theme = self.resolved_theme();
5155 text_token_style(&theme, theme.text.sm, theme.palette.text)
5156 }
5157
5158 fn resolved_theme(&self) -> DefaultTheme {
5159 self.theme_reader
5160 .as_ref()
5161 .map(|theme| theme())
5162 .unwrap_or(*self.theme)
5163 }
5164
5165 fn resolved_header_height(&self, metrics: ControlMetrics) -> f32 {
5166 self.header_height
5167 .unwrap_or(metrics.dock_panel_header_height)
5168 }
5169
5170 fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
5171 self.padding.unwrap_or(metrics.dock_panel_padding)
5172 }
5173
5174 fn title_height(&self, style: &TextStyle) -> f32 {
5175 self.title_measurement
5176 .map(|measurement| measurement.height)
5177 .unwrap_or(style.line_height)
5178 .max(style.line_height)
5179 }
5180
5181 fn header_rect(&self, bounds: Rect) -> Rect {
5182 let theme = self.resolved_theme();
5183 Rect::new(
5184 bounds.x(),
5185 bounds.y(),
5186 bounds.width(),
5187 self.resolved_header_height(theme.metrics),
5188 )
5189 }
5190
5191 fn content_rect(&self, bounds: Rect) -> Rect {
5192 let theme = self.resolved_theme();
5193 let metrics = theme.metrics;
5194 let header_height = self.resolved_header_height(metrics);
5195 inset_rect(
5196 Rect::new(
5197 bounds.x(),
5198 bounds.y() + header_height,
5199 bounds.width(),
5200 (bounds.height() - header_height).max(0.0),
5201 ),
5202 self.resolved_padding(metrics),
5203 )
5204 }
5205
5206 fn child_constraints(&self, constraints: Constraints) -> Constraints {
5207 let theme = self.resolved_theme();
5208 let metrics = theme.metrics;
5209 let padding = self.resolved_padding(metrics);
5210 let header_height = self.resolved_header_height(metrics);
5211 let width = if constraints.max.width.is_finite() {
5212 (constraints.max.width - padding.left - padding.right).max(0.0)
5213 } else {
5214 f32::INFINITY
5215 };
5216 let height = if constraints.max.height.is_finite() {
5217 (constraints.max.height - header_height - padding.top - padding.bottom).max(0.0)
5218 } else {
5219 f32::INFINITY
5220 };
5221 Constraints::new(Size::ZERO, Size::new(width, height))
5222 }
5223}
5224
5225impl Widget for DockPanel {
5226 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5227 let theme = self.resolved_theme();
5228 let metrics = theme.metrics;
5229 let padding = self.resolved_padding(metrics);
5230 let header_height = self.resolved_header_height(metrics);
5231 let title_style = self.resolved_title_style();
5232 let title_measurement = measure_text(ctx, &self.title, &title_style);
5233 self.title_measurement = Some(title_measurement);
5234 let child_size = self.child.measure(ctx, self.child_constraints(constraints));
5235 let natural = Size::new(
5236 (title_measurement.width + padding.left + padding.right)
5237 .max(child_size.width + padding.left + padding.right),
5238 header_height + padding.top + child_size.height + padding.bottom,
5239 );
5240
5241 constraints.clamp(natural)
5242 }
5243
5244 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5245 self.child.arrange(ctx, self.content_rect(bounds));
5246 }
5247
5248 fn paint(&self, ctx: &mut PaintCtx) {
5249 let theme = self.resolved_theme();
5250 let palette = theme.palette;
5251 let metrics = theme.metrics;
5252 let padding = self.resolved_padding(metrics);
5253 let bounds = ctx.bounds();
5254 let header = self.header_rect(bounds);
5255 let title_style = self.resolved_title_style();
5256 let title_height = self.title_height(&title_style);
5257 let title_slot = Rect::new(
5258 header.x() + padding.left,
5259 header.y() + ((header.height() - title_height) * 0.5).max(0.0),
5260 (header.width() - padding.left - padding.right).max(0.0),
5261 title_height,
5262 );
5263 let divider_height = physical_pixels(ctx, 1.0);
5264
5265 ctx.fill_rect(bounds, self.background.unwrap_or(palette.surface));
5266 ctx.fill_rect(
5267 header,
5268 self.header_background
5269 .unwrap_or_else(|| palette.surface_raised.with_alpha(0.72)),
5270 );
5271 ctx.fill_rect(
5272 Rect::new(
5273 header.x(),
5274 header.max_y() - divider_height,
5275 header.width(),
5276 divider_height,
5277 ),
5278 palette.border,
5279 );
5280 ctx.push_clip_rect(title_slot);
5281 paint_aligned_text(
5282 ctx,
5283 title_slot,
5284 &self.title,
5285 &title_style,
5286 title_style.line_height,
5287 0.0,
5288 );
5289 ctx.pop_clip();
5290
5291 self.child.paint(ctx);
5292 }
5293
5294 fn semantics(&self, ctx: &mut SemanticsCtx) {
5295 let theme = self.resolved_theme();
5296 let padding = self.resolved_padding(theme.metrics);
5297 let mut panel = SemanticsNode::new(
5298 ctx.widget_id(),
5299 SemanticsRole::GenericContainer,
5300 ctx.bounds(),
5301 );
5302 panel.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
5303 ctx.push(panel);
5304
5305 let title_style = self.resolved_title_style();
5306 let title_height = self.title_height(&title_style);
5307 let header = self.header_rect(ctx.bounds());
5308 let mut title = SemanticsNode::new(
5309 dock_panel_title_id(ctx.widget_id()),
5310 SemanticsRole::Text,
5311 Rect::new(
5312 header.x() + padding.left,
5313 header.y() + ((header.height() - title_height) * 0.5).max(0.0),
5314 (header.width() - padding.left - padding.right).max(0.0),
5315 title_height,
5316 ),
5317 );
5318 title.parent = Some(ctx.widget_id());
5319 title.name = Some(self.title.clone());
5320 title.value = Some(SemanticsValue::Text(self.title.clone()));
5321 ctx.push(title);
5322
5323 self.child.semantics(ctx);
5324 }
5325
5326 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5327 self.child.visit_children(visitor);
5328 }
5329
5330 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5331 self.child.visit_children_mut(visitor);
5332 }
5333}
5334
5335fn dock_panel_title_id(parent: WidgetId) -> WidgetId {
5336 const TAG: u64 = 5_u64 << 50;
5337 const LOW_MASK: u64 = (1_u64 << 50) - 1;
5338
5339 WidgetId::new(TAG | (parent.get().wrapping_mul(467).wrapping_add(11) & LOW_MASK))
5340}
5341
5342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5343pub enum HairlineEdge {
5344 Top,
5345 Right,
5346 Bottom,
5347 Left,
5348}
5349
5350pub fn paint_rounded_rect(ctx: &mut PaintCtx, rect: Rect, color: Color, radius: f32) {
5351 if rect.width() <= 0.0 || rect.height() <= 0.0 {
5352 return;
5353 }
5354 let radius = radius
5355 .min(rect.width() * 0.5)
5356 .min(rect.height() * 0.5)
5357 .max(0.0);
5358 if radius <= 0.5 {
5359 ctx.fill_rect(rect, color);
5360 } else {
5361 ctx.fill(Path::rounded_rect(rect, radius), color);
5362 }
5363}
5364
5365pub fn paint_rounded_panel(
5366 ctx: &mut PaintCtx,
5367 rect: Rect,
5368 fill: Color,
5369 border: Color,
5370 radius: f32,
5371) {
5372 paint_rounded_rect(ctx, rect, border, radius);
5373 paint_rounded_rect(ctx, rect.inflate(-1.0, -1.0), fill, (radius - 1.0).max(0.0));
5374}
5375
5376pub fn paint_hairline(ctx: &mut PaintCtx, rect: Rect, edge: HairlineEdge, color: Color) {
5377 let line = match edge {
5378 HairlineEdge::Top => Rect::new(rect.x(), rect.y(), rect.width(), 1.0),
5379 HairlineEdge::Right => Rect::new(rect.max_x() - 1.0, rect.y(), 1.0, rect.height()),
5380 HairlineEdge::Bottom => Rect::new(rect.x(), rect.max_y() - 1.0, rect.width(), 1.0),
5381 HairlineEdge::Left => Rect::new(rect.x(), rect.y(), 1.0, rect.height()),
5382 };
5383 ctx.fill_rect(line, color);
5384}
5385
5386pub fn paint_border(ctx: &mut PaintCtx, rect: Rect, color: Color) {
5387 paint_hairline(ctx, rect, HairlineEdge::Top, color);
5388 paint_hairline(ctx, rect, HairlineEdge::Right, color);
5389 paint_hairline(ctx, rect, HairlineEdge::Bottom, color);
5390 paint_hairline(ctx, rect, HairlineEdge::Left, color);
5391}
5392
5393fn centered_text_slot(bounds: Rect, center_y: f32, line_height: f32) -> Rect {
5394 let height = line_height.max(1.0) * 2.0;
5395 Rect::new(bounds.x(), center_y - height * 0.5, bounds.width(), height)
5396}
5397
5398#[derive(Clone, Copy)]
5399pub struct EmptyStatePaint<'a> {
5400 icon: Option<IconGlyph>,
5401 title: &'a str,
5402 description: &'a str,
5403 detail: Option<&'a str>,
5404 background: Option<Color>,
5405 center_offset_y: f32,
5406 reserve_action_space: bool,
5407}
5408
5409impl<'a> EmptyStatePaint<'a> {
5410 pub const fn new(title: &'a str, description: &'a str) -> Self {
5411 Self {
5412 icon: None,
5413 title,
5414 description,
5415 detail: None,
5416 background: None,
5417 center_offset_y: 0.0,
5418 reserve_action_space: false,
5419 }
5420 }
5421
5422 pub const fn icon(mut self, icon: IconGlyph) -> Self {
5423 self.icon = Some(icon);
5424 self
5425 }
5426
5427 pub const fn detail(mut self, detail: &'a str) -> Self {
5428 self.detail = Some(detail);
5429 self
5430 }
5431
5432 pub const fn background(mut self, color: Color) -> Self {
5433 self.background = Some(color);
5434 self
5435 }
5436
5437 pub const fn center_offset_y(mut self, offset: f32) -> Self {
5438 self.center_offset_y = offset;
5439 self
5440 }
5441
5442 pub const fn reserve_action_space(mut self, reserve: bool) -> Self {
5443 self.reserve_action_space = reserve;
5444 self
5445 }
5446}
5447
5448pub fn paint_empty_state(
5449 ctx: &mut PaintCtx,
5450 theme: &DefaultTheme,
5451 bounds: Rect,
5452 paint: EmptyStatePaint<'_>,
5453) {
5454 if let Some(background) = paint.background {
5455 ctx.fill_rect(bounds, background);
5456 }
5457
5458 let cy = bounds.y() + bounds.height() * 0.5
5459 - if paint.reserve_action_space {
5460 18.0
5461 } else {
5462 0.0
5463 }
5464 + paint.center_offset_y;
5465 let icon_color = theme.surfaces.text_faint;
5466 if let Some(icon) = paint.icon {
5467 let side = 40.0;
5468 let cx = bounds.x() + bounds.width() * 0.5;
5469 draw_icon_glyph(
5470 ctx,
5471 icon,
5472 Rect::new(cx - side * 0.5, cy - 46.0 - side * 0.5, side, side),
5473 icon_color,
5474 );
5475 }
5476
5477 let mut title_style = text_token_style(theme, theme.text.lg, theme.surfaces.text_muted);
5478 title_style.weight = FontWeight::SEMIBOLD;
5479 paint_single_line_aligned_text(
5480 ctx,
5481 centered_text_slot(bounds, cy + 4.0, title_style.line_height),
5482 paint.title,
5483 &title_style,
5484 title_style.line_height,
5485 0.5,
5486 );
5487
5488 let description_style = text_token_style(theme, theme.text.sm, theme.surfaces.text_faint);
5489 paint_single_line_aligned_text(
5490 ctx,
5491 centered_text_slot(bounds, cy + 30.0, description_style.line_height),
5492 paint.description,
5493 &description_style,
5494 description_style.line_height,
5495 0.5,
5496 );
5497
5498 if let Some(detail) = paint.detail {
5499 let mut detail_style = text_token_style(theme, theme.text.xs, theme.surfaces.text_muted);
5500 detail_style.weight = FontWeight::MEDIUM;
5501 paint_single_line_aligned_text(
5502 ctx,
5503 centered_text_slot(bounds, cy + 48.0, detail_style.line_height),
5504 detail,
5505 &detail_style,
5506 detail_style.line_height,
5507 0.5,
5508 );
5509 }
5510}
5511
5512pub struct EmptyState {
5513 theme: Box<DefaultTheme>,
5514 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5515 name: Option<String>,
5516 icon: Option<IconGlyph>,
5517 title: String,
5518 description: String,
5519 detail: Option<String>,
5520 action: Option<SingleChild>,
5521 action_height: f32,
5522 action_max_width: f32,
5523 background: Option<Color>,
5524}
5525
5526impl EmptyState {
5527 pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
5528 Self {
5529 theme: Box::new(DefaultTheme::default()),
5530 theme_reader: None,
5531 name: None,
5532 icon: None,
5533 title: title.into(),
5534 description: description.into(),
5535 detail: None,
5536 action: None,
5537 action_height: 32.0,
5538 action_max_width: 360.0,
5539 background: None,
5540 }
5541 }
5542
5543 pub fn theme(mut self, theme: DefaultTheme) -> Self {
5544 self.theme = Box::new(theme);
5545 self.theme_reader = None;
5546 self
5547 }
5548
5549 pub fn theme_when<F>(mut self, theme: F) -> Self
5550 where
5551 F: Fn() -> DefaultTheme + 'static,
5552 {
5553 self.theme_reader = Some(Box::new(theme));
5554 self
5555 }
5556
5557 pub fn name(mut self, name: impl Into<String>) -> Self {
5558 self.name = Some(name.into());
5559 self
5560 }
5561
5562 pub fn icon(mut self, icon: IconGlyph) -> Self {
5563 self.icon = Some(icon);
5564 self
5565 }
5566
5567 pub fn detail(mut self, detail: impl Into<String>) -> Self {
5568 self.detail = Some(detail.into());
5569 self
5570 }
5571
5572 pub fn action<W>(mut self, action: W) -> Self
5573 where
5574 W: Widget + 'static,
5575 {
5576 self.action = Some(SingleChild::new(action));
5577 self
5578 }
5579
5580 pub fn action_height(mut self, height: f32) -> Self {
5581 self.action_height = height.max(32.0);
5582 self
5583 }
5584
5585 pub fn action_max_width(mut self, width: f32) -> Self {
5586 self.action_max_width = width.max(0.0);
5587 self
5588 }
5589
5590 pub fn background(mut self, color: Color) -> Self {
5591 self.background = Some(color);
5592 self
5593 }
5594
5595 pub fn transparent(mut self) -> Self {
5596 self.background = Some(Color::TRANSPARENT);
5597 self
5598 }
5599
5600 pub fn action_child(&self) -> Option<&WidgetPod> {
5601 self.action.as_ref().map(SingleChild::child)
5602 }
5603
5604 pub fn action_child_mut(&mut self) -> Option<&mut WidgetPod> {
5605 self.action.as_mut().map(SingleChild::child_mut)
5606 }
5607
5608 fn resolved_theme(&self) -> DefaultTheme {
5609 self.theme_reader
5610 .as_ref()
5611 .map(|reader| reader())
5612 .unwrap_or(*self.theme)
5613 }
5614
5615 fn action_rect(
5616 bounds: Rect,
5617 action_size: Size,
5618 action_max_width: f32,
5619 action_height: f32,
5620 ) -> Rect {
5621 let max_width = action_max_width.min((bounds.width() - 32.0).max(0.0));
5622 let width = action_size.width.min(max_width).max(0.0);
5623 let height = action_size.height.max(action_height);
5624 let cx = bounds.x() + bounds.width() * 0.5;
5625 let cy = bounds.y() + bounds.height() * 0.5 - 18.0;
5626 Rect::new(cx - width * 0.5, cy + 54.0, width, height)
5627 }
5628}
5629
5630impl Widget for EmptyState {
5631 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5632 let width = if constraints.max.width.is_finite() {
5633 constraints.max.width
5634 } else {
5635 constraints.min.width.max(self.action_max_width + 32.0)
5636 };
5637 let action_height = if let Some(action) = &mut self.action {
5638 let action_width = self.action_max_width.min((width - 32.0).max(0.0));
5639 let action_size = action.measure(
5640 ctx,
5641 Constraints::new(
5642 Size::new(0.0, self.action_height),
5643 Size::new(action_width, f32::INFINITY),
5644 ),
5645 );
5646 action_size.height.max(self.action_height)
5647 } else {
5648 0.0
5649 };
5650 let height = if constraints.max.height.is_finite() {
5651 constraints.max.height
5652 } else {
5653 constraints
5654 .min
5655 .height
5656 .max(142.0 + action_height + if action_height > 0.0 { 12.0 } else { 0.0 })
5657 };
5658 constraints.clamp(Size::new(width, height))
5659 }
5660
5661 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5662 let action_max_width = self.action_max_width;
5663 let action_height = self.action_height;
5664 if let Some(action) = &mut self.action {
5665 let action_rect = Self::action_rect(
5666 bounds,
5667 action.child().measured_size(),
5668 action_max_width,
5669 action_height,
5670 );
5671 action.arrange(ctx, action_rect);
5672 }
5673 }
5674
5675 fn paint(&self, ctx: &mut PaintCtx) {
5676 let theme = self.resolved_theme();
5677 let bounds = ctx.bounds();
5678 let mut paint = EmptyStatePaint::new(&self.title, &self.description)
5679 .background(self.background.unwrap_or(theme.surfaces.window))
5680 .reserve_action_space(self.action.is_some());
5681 if let Some(icon) = self.icon {
5682 paint = paint.icon(icon);
5683 }
5684 if let Some(detail) = self.detail.as_deref() {
5685 paint = paint.detail(detail);
5686 }
5687 ctx.push_clip_rect(bounds);
5688 paint_empty_state(ctx, &theme, bounds, paint);
5689
5690 if let Some(action) = &self.action {
5691 action.paint(ctx);
5692 }
5693 ctx.pop_clip();
5694 }
5695
5696 fn semantics(&self, ctx: &mut SemanticsCtx) {
5697 let mut node = SemanticsNode::new(
5698 ctx.widget_id(),
5699 SemanticsRole::GenericContainer,
5700 ctx.bounds(),
5701 );
5702 node.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
5703 node.description = Some(match &self.detail {
5704 Some(detail)
5705 if matches!(
5706 self.description.chars().last(),
5707 Some('.') | Some('!') | Some('?')
5708 ) =>
5709 {
5710 format!("{} {}", self.description, detail)
5711 }
5712 Some(detail) => format!("{}. {}", self.description, detail),
5713 None => self.description.clone(),
5714 });
5715 ctx.push(node);
5716 if let Some(action) = &self.action {
5717 action.semantics(ctx);
5718 }
5719 }
5720
5721 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5722 if let Some(action) = &self.action {
5723 action.visit_children(visitor);
5724 }
5725 }
5726
5727 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5728 if let Some(action) = &mut self.action {
5729 action.visit_children_mut(visitor);
5730 }
5731 }
5732}
5733
5734pub struct PresetStrip {
5735 theme: Box<DefaultTheme>,
5736 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5737 name: String,
5738 presets: Vec<String>,
5739 selected: Option<usize>,
5740 selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
5741 hovered: Option<usize>,
5742 hover_visual: Option<usize>,
5743 pressed: Option<usize>,
5744 press_visual: Option<usize>,
5745 hover_animation: AnimatedScalar,
5746 press_animation: AnimatedScalar,
5747 focus_animation: AnimatedScalar,
5748 item_width: Option<f32>,
5749 item_height: Option<f32>,
5750 gap: Option<f32>,
5751 label_measurements: Vec<TextMeasurement>,
5752 item_widths: Vec<f32>,
5753 on_change: Option<Box<dyn FnMut(usize, String)>>,
5754}
5755
5756impl PresetStrip {
5757 pub fn new(name: impl Into<String>) -> Self {
5758 Self {
5759 theme: Box::new(DefaultTheme::default()),
5760 theme_reader: None,
5761 name: name.into(),
5762 presets: Vec::new(),
5763 selected: None,
5764 selected_reader: None,
5765 hovered: None,
5766 hover_visual: None,
5767 pressed: None,
5768 press_visual: None,
5769 hover_animation: AnimatedScalar::new(0.0),
5770 press_animation: AnimatedScalar::new(0.0),
5771 focus_animation: AnimatedScalar::new(0.0),
5772 item_width: None,
5773 item_height: None,
5774 gap: None,
5775 label_measurements: Vec::new(),
5776 item_widths: Vec::new(),
5777 on_change: None,
5778 }
5779 }
5780
5781 pub fn theme(mut self, theme: DefaultTheme) -> Self {
5782 self.theme = Box::new(theme);
5783 self.theme_reader = None;
5784 self
5785 }
5786
5787 pub fn theme_when<F>(mut self, theme: F) -> Self
5788 where
5789 F: Fn() -> DefaultTheme + 'static,
5790 {
5791 self.theme_reader = Some(Box::new(theme));
5792 self
5793 }
5794
5795 pub fn preset(mut self, preset: impl Into<String>) -> Self {
5796 self.presets.push(preset.into());
5797 self
5798 }
5799
5800 pub fn presets<I, S>(mut self, presets: I) -> Self
5801 where
5802 I: IntoIterator<Item = S>,
5803 S: Into<String>,
5804 {
5805 self.presets.extend(presets.into_iter().map(Into::into));
5806 self
5807 }
5808
5809 pub fn selected(mut self, selected: usize) -> Self {
5810 self.selected = Some(selected);
5811 self.selected_reader = None;
5812 self
5813 }
5814
5815 pub fn selected_when<F>(mut self, selected: F) -> Self
5816 where
5817 F: Fn() -> Option<usize> + 'static,
5818 {
5819 self.selected_reader = Some(Box::new(selected));
5820 self
5821 }
5822
5823 pub fn item_width(mut self, width: f32) -> Self {
5824 self.item_width = Some(width.max(0.0));
5825 self
5826 }
5827
5828 pub fn item_height(mut self, height: f32) -> Self {
5829 self.item_height = Some(height.max(20.0));
5830 self
5831 }
5832
5833 pub fn gap(mut self, gap: f32) -> Self {
5834 self.gap = Some(gap.max(0.0));
5835 self
5836 }
5837
5838 pub fn on_change<F>(mut self, on_change: F) -> Self
5839 where
5840 F: FnMut(usize, String) + 'static,
5841 {
5842 self.on_change = Some(Box::new(on_change));
5843 self
5844 }
5845
5846 pub fn selected_index(&self) -> Option<usize> {
5847 self.current_selected()
5848 }
5849
5850 fn current_selected(&self) -> Option<usize> {
5851 self.selected_reader
5852 .as_ref()
5853 .map(|selected| selected())
5854 .unwrap_or(self.selected)
5855 .filter(|index| *index < self.presets.len())
5856 }
5857
5858 fn resolved_theme(&self) -> DefaultTheme {
5859 self.theme_reader
5860 .as_ref()
5861 .map(|theme| theme())
5862 .unwrap_or(*self.theme)
5863 }
5864
5865 fn resolved_item_height(&self, metrics: ControlMetrics) -> f32 {
5866 self.item_height.unwrap_or(metrics.preset_strip_item_height)
5867 }
5868
5869 fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
5870 self.gap.unwrap_or(metrics.preset_strip_gap)
5871 }
5872
5873 fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
5874 if index >= self.presets.len() || self.item_widths.len() != self.presets.len() {
5875 return None;
5876 }
5877
5878 let metrics = self.resolved_theme().metrics;
5879 let item_height = self.resolved_item_height(metrics);
5880 let gap = self.resolved_gap(metrics);
5881 let mut x = bounds.x();
5882 for (current, width) in self.item_widths.iter().enumerate() {
5883 let available = (bounds.max_x() - x).max(0.0);
5884 let rect = Rect::new(x, bounds.y(), width.min(available), item_height);
5885 if current == index {
5886 return (!rect.is_empty()).then_some(rect);
5887 }
5888 x += *width + gap;
5889 }
5890
5891 None
5892 }
5893
5894 fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
5895 self.presets.iter().enumerate().find_map(|(index, _)| {
5896 self.item_rect(bounds, index)
5897 .filter(|rect| rect.contains(position))
5898 .map(|_| index)
5899 })
5900 }
5901
5902 fn activate(&mut self, index: usize) {
5903 if self.presets.is_empty() {
5904 return;
5905 }
5906
5907 let index = index.min(self.presets.len() - 1);
5908 self.selected = Some(index);
5909 if let Some(on_change) = &mut self.on_change {
5910 on_change(index, self.presets[index].clone());
5911 }
5912 }
5913
5914 fn move_selection(&mut self, delta: isize) {
5915 if self.presets.is_empty() {
5916 return;
5917 }
5918
5919 let current = self.current_selected().unwrap_or(0) as isize;
5920 let last = self.presets.len() as isize - 1;
5921 let next = (current + delta).clamp(0, last) as usize;
5922 self.hovered = Some(next);
5923 self.activate(next);
5924 }
5925
5926 fn selected_text(&self) -> Option<String> {
5927 self.current_selected()
5928 .and_then(|index| self.presets.get(index).cloned())
5929 }
5930
5931 fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
5932 if self.hovered == hovered {
5933 return;
5934 }
5935 let theme = self.resolved_theme();
5936 self.hovered = hovered;
5937 if let Some(index) = hovered {
5938 self.hover_visual = Some(index);
5939 self.hover_animation = AnimatedScalar::new(0.0);
5940 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
5941 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
5942 self.hover_visual = None;
5943 }
5944 ctx.request_paint();
5945 ctx.request_semantics();
5946 }
5947
5948 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
5949 if self.pressed == pressed {
5950 return;
5951 }
5952 let theme = self.resolved_theme();
5953 self.pressed = pressed;
5954 if let Some(index) = pressed {
5955 self.press_visual = Some(index);
5956 self.press_animation = AnimatedScalar::new(0.0);
5957 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
5958 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
5959 self.press_visual = None;
5960 }
5961 ctx.request_paint();
5962 ctx.request_semantics();
5963 }
5964
5965 fn hover_amount_for(&self, index: usize) -> f32 {
5966 if self.hover_visual == Some(index) {
5967 self.hover_animation.value
5968 } else {
5969 0.0
5970 }
5971 }
5972
5973 fn press_amount_for(&self, index: usize) -> f32 {
5974 if self.press_visual == Some(index) {
5975 self.press_animation.value
5976 } else {
5977 0.0
5978 }
5979 }
5980
5981 fn advance_animations(&mut self, time: f64) -> bool {
5982 let hover_animating = self.hover_animation.advance(time);
5983 if !hover_animating
5984 && self.hovered.is_none()
5985 && self.hover_animation.value <= AnimatedScalar::EPSILON
5986 {
5987 self.hover_visual = None;
5988 }
5989
5990 let press_animating = self.press_animation.advance(time);
5991 if !press_animating
5992 && self.pressed.is_none()
5993 && self.press_animation.value <= AnimatedScalar::EPSILON
5994 {
5995 self.press_visual = None;
5996 }
5997
5998 hover_animating | press_animating | self.focus_animation.advance(time)
5999 }
6000}
6001
6002impl Widget for PresetStrip {
6003 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6004 match event {
6005 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
6006 self.set_hovered(self.item_at(ctx.bounds(), pointer.position), ctx);
6007 }
6008 Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
6009 self.set_hovered(None, ctx);
6010 }
6011 Event::Pointer(pointer)
6012 if pointer.kind == PointerEventKind::Down
6013 && pointer.button == Some(PointerButton::Primary) =>
6014 {
6015 let hovered = self.item_at(ctx.bounds(), pointer.position);
6016 self.set_hovered(hovered, ctx);
6017 self.set_pressed(hovered, ctx);
6018 if self.hovered.is_some() {
6019 ctx.request_focus();
6020 ctx.request_pointer_capture(pointer.pointer_id);
6021 ctx.set_handled();
6022 }
6023 }
6024 Event::Pointer(pointer)
6025 if pointer.kind == PointerEventKind::Up
6026 && pointer.button == Some(PointerButton::Primary) =>
6027 {
6028 let hovered = self.item_at(ctx.bounds(), pointer.position);
6029 if let Some(index) = self
6030 .pressed
6031 .zip(hovered)
6032 .filter(|(left, right)| left == right)
6033 .map(|(index, _)| index)
6034 {
6035 self.activate(index);
6036 }
6037 self.set_hovered(hovered, ctx);
6038 self.set_pressed(None, ctx);
6039 ctx.release_pointer_capture(pointer.pointer_id);
6040 ctx.set_handled();
6041 }
6042 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
6043 if self.pressed.is_some() {
6044 self.set_pressed(None, ctx);
6045 self.set_hovered(None, ctx);
6046 ctx.release_pointer_capture(pointer.pointer_id);
6047 ctx.set_handled();
6048 }
6049 }
6050 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
6051 match key.key.as_str() {
6052 "ArrowLeft" | "ArrowUp" => self.move_selection(-1),
6053 "ArrowRight" | "ArrowDown" => self.move_selection(1),
6054 "Home" => self.activate(0),
6055 "End" if !self.presets.is_empty() => self.activate(self.presets.len() - 1),
6056 "Enter" | " " => {
6057 if let Some(selected) = self.current_selected().or(Some(0)) {
6058 self.activate(selected);
6059 }
6060 }
6061 _ => return,
6062 }
6063 ctx.request_paint();
6064 ctx.request_semantics();
6065 ctx.set_handled();
6066 }
6067 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
6068 if self.advance_animations(*time) {
6069 ctx.request_animation_frame();
6070 }
6071 ctx.request_paint();
6072 }
6073 _ => {}
6074 }
6075 }
6076
6077 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6078 let theme = self.resolved_theme();
6079 let metrics = theme.metrics;
6080 let item_height = self.resolved_item_height(metrics);
6081 let gap = self.resolved_gap(metrics);
6082 let style = theme.text_style(theme.palette.text);
6083 self.label_measurements = self
6084 .presets
6085 .iter()
6086 .map(|preset| measure_text(ctx, preset, &style))
6087 .collect();
6088 self.item_widths = self
6089 .label_measurements
6090 .iter()
6091 .map(|measurement| {
6092 self.item_width.unwrap_or(
6093 (measurement.width
6094 + metrics.preset_strip_item_padding.left
6095 + metrics.preset_strip_item_padding.right)
6096 .max(metrics.preset_strip_item_min_width),
6097 )
6098 })
6099 .collect();
6100
6101 let width = self.item_widths.iter().sum::<f32>()
6102 + (gap * self.presets.len().saturating_sub(1) as f32);
6103 constraints.clamp(Size::new(width, item_height))
6104 }
6105
6106 fn paint(&self, ctx: &mut PaintCtx) {
6107 let theme = self.resolved_theme();
6108 let palette = theme.palette;
6109 let metrics = theme.metrics;
6110 let interaction = theme.interaction;
6111 let selected = self.current_selected();
6112 let style = theme.text_style(palette.text);
6113
6114 if self.focus_animation.value > AnimatedScalar::EPSILON {
6115 ctx.stroke(
6116 rounded_rect_path(ctx.bounds().inflate(2.0, 2.0), metrics.corner_radius + 2.0),
6117 palette
6118 .focus_ring
6119 .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
6120 StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
6121 );
6122 }
6123
6124 for (index, preset) in self.presets.iter().enumerate() {
6125 let Some(rect) = self.item_rect(ctx.bounds(), index) else {
6126 continue;
6127 };
6128 let is_selected = selected == Some(index);
6129 let is_hovered = self.hovered == Some(index);
6130 let hover_amount = self.hover_amount_for(index);
6131 let press_amount = self.press_amount_for(index);
6132 let base_background = if is_selected {
6133 palette.accent
6134 } else {
6135 palette.surface
6136 };
6137 let hover_background = if hover_amount > 0.0 {
6138 mix_color(
6139 base_background,
6140 palette.control_hover,
6141 interaction.hover_blend * if is_selected { 0.35 } else { 1.0 } * hover_amount,
6142 )
6143 } else {
6144 base_background
6145 };
6146 let background = if press_amount > 0.0 {
6147 mix_color(
6148 hover_background,
6149 palette.control_active,
6150 interaction.pressed_blend * if is_selected { 0.45 } else { 1.0 } * press_amount,
6151 )
6152 } else {
6153 hover_background
6154 };
6155 let border = if is_selected {
6156 palette.accent_border
6157 } else if is_hovered || hover_amount > 0.0 || press_amount > 0.0 {
6158 palette.border_hover
6159 } else {
6160 palette.border
6161 };
6162 let text_color = if is_selected {
6163 palette.accent_text
6164 } else {
6165 palette.text
6166 };
6167
6168 draw_control_shape(
6169 ctx,
6170 rect,
6171 metrics.corner_radius,
6172 physical_pixels(ctx, metrics.border_width),
6173 background,
6174 border,
6175 );
6176
6177 let text_slot = inset_rect(rect, metrics.preset_strip_label_padding);
6178 let pressed_offset = press_amount * interaction.pressed_offset;
6179 let text_style = TextStyle {
6180 color: text_color,
6181 ..style.clone()
6182 };
6183 ctx.push_clip_rect(text_slot);
6184 paint_aligned_text(
6185 ctx,
6186 text_slot.translate(Vector::new(0.0, pressed_offset)),
6187 preset,
6188 &text_style,
6189 text_style.line_height,
6190 0.5,
6191 );
6192 ctx.pop_clip();
6193 }
6194 }
6195
6196 fn semantics(&self, ctx: &mut SemanticsCtx) {
6197 let mut node = SemanticsNode::new(
6198 ctx.widget_id(),
6199 SemanticsRole::GenericContainer,
6200 ctx.bounds(),
6201 );
6202 node.name = Some(self.name.clone());
6203 node.value = self.selected_text().map(SemanticsValue::Text);
6204 node.state.focused = ctx.is_focused();
6205 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
6206 ctx.push(node);
6207
6208 let selected = self.current_selected();
6209 for (index, preset) in self.presets.iter().enumerate() {
6210 let Some(rect) = self.item_rect(ctx.bounds(), index) else {
6211 continue;
6212 };
6213 let mut item = SemanticsNode::new(
6214 preset_strip_item_id(ctx.widget_id(), index),
6215 SemanticsRole::Button,
6216 rect,
6217 );
6218 item.parent = Some(ctx.widget_id());
6219 item.name = Some(preset.clone());
6220 item.value = Some(SemanticsValue::Text(preset.clone()));
6221 item.state.hovered = self.hovered == Some(index);
6222 item.state.selected = selected == Some(index);
6223 item.actions = vec![SemanticsAction::Activate];
6224 ctx.push(item);
6225 }
6226 }
6227
6228 fn accepts_focus(&self) -> bool {
6229 !self.presets.is_empty()
6230 }
6231
6232 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
6233 let theme = self.resolved_theme();
6234 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
6235 ctx.request_paint();
6236 ctx.request_semantics();
6237 }
6238}
6239
6240fn preset_strip_item_id(parent: WidgetId, index: usize) -> WidgetId {
6241 const TAG: u64 = 6_u64 << 50;
6242 const LOW_MASK: u64 = (1_u64 << 50) - 1;
6243
6244 WidgetId::new(
6245 TAG | (parent
6246 .get()
6247 .wrapping_mul(487)
6248 .wrapping_add(index as u64 + 1)
6249 & LOW_MASK),
6250 )
6251}
6252
6253pub struct StatusBarSegment {
6254 text: String,
6255 reader: Option<Box<dyn Fn() -> String>>,
6256 min_width: Option<f32>,
6257 tone: SemanticTone,
6258 expand: bool,
6259}
6260
6261impl StatusBarSegment {
6262 pub fn new(text: impl Into<String>) -> Self {
6263 Self {
6264 text: text.into(),
6265 reader: None,
6266 min_width: None,
6267 tone: SemanticTone::Neutral,
6268 expand: false,
6269 }
6270 }
6271
6272 pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
6273 where
6274 F: Fn() -> String + 'static,
6275 {
6276 Self {
6277 text: fallback.into(),
6278 reader: Some(Box::new(reader)),
6279 min_width: None,
6280 tone: SemanticTone::Neutral,
6281 expand: false,
6282 }
6283 }
6284
6285 pub fn min_width(mut self, min_width: f32) -> Self {
6286 self.min_width = Some(min_width.max(0.0));
6287 self
6288 }
6289
6290 pub fn tone(mut self, tone: SemanticTone) -> Self {
6291 self.tone = tone;
6292 self
6293 }
6294
6295 pub fn expand(mut self, expand: bool) -> Self {
6296 self.expand = expand;
6297 self
6298 }
6299
6300 fn text(&self) -> String {
6301 self.reader
6302 .as_ref()
6303 .map(|reader| reader())
6304 .unwrap_or_else(|| self.text.clone())
6305 }
6306}
6307
6308pub struct StatusBar {
6309 theme: Box<DefaultTheme>,
6310 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
6311 name: Option<String>,
6312 description: Option<String>,
6313 description_reader: Option<Box<dyn Fn() -> String>>,
6314 height: Option<f32>,
6315 segments: Vec<StatusBarSegment>,
6316 measured_widths: Vec<f32>,
6317}
6318
6319impl StatusBar {
6320 pub fn new() -> Self {
6321 Self {
6322 theme: Box::new(DefaultTheme::default()),
6323 theme_reader: None,
6324 name: None,
6325 description: None,
6326 description_reader: None,
6327 height: None,
6328 segments: Vec::new(),
6329 measured_widths: Vec::new(),
6330 }
6331 }
6332
6333 pub fn theme(mut self, theme: DefaultTheme) -> Self {
6334 self.theme = Box::new(theme);
6335 self.theme_reader = None;
6336 self
6337 }
6338
6339 pub fn theme_when<F>(mut self, theme: F) -> Self
6340 where
6341 F: Fn() -> DefaultTheme + 'static,
6342 {
6343 self.theme_reader = Some(Box::new(theme));
6344 self
6345 }
6346
6347 pub fn name(mut self, name: impl Into<String>) -> Self {
6348 self.name = Some(name.into());
6349 self
6350 }
6351
6352 pub fn description(mut self, description: impl Into<String>) -> Self {
6353 self.description = Some(description.into());
6354 self.description_reader = None;
6355 self
6356 }
6357
6358 pub fn description_when<F>(mut self, description: F) -> Self
6359 where
6360 F: Fn() -> String + 'static,
6361 {
6362 self.description_reader = Some(Box::new(description));
6363 self
6364 }
6365
6366 pub fn height(mut self, height: f32) -> Self {
6367 self.height = Some(height.max(18.0));
6368 self
6369 }
6370
6371 pub fn segment(mut self, segment: StatusBarSegment) -> Self {
6372 self.segments.push(segment);
6373 self
6374 }
6375
6376 pub fn text_segment(self, text: impl Into<String>) -> Self {
6377 self.segment(StatusBarSegment::new(text))
6378 }
6379
6380 pub fn dynamic_segment<F>(self, fallback: impl Into<String>, reader: F) -> Self
6381 where
6382 F: Fn() -> String + 'static,
6383 {
6384 self.segment(StatusBarSegment::dynamic(fallback, reader))
6385 }
6386
6387 fn text_style(&self) -> TextStyle {
6388 let theme = self.resolved_theme();
6389 text_token_style(&theme, theme.text.xs, theme.palette.placeholder)
6390 }
6391
6392 fn resolved_theme(&self) -> DefaultTheme {
6393 self.theme_reader
6394 .as_ref()
6395 .map(|theme| theme())
6396 .unwrap_or(*self.theme)
6397 }
6398
6399 fn resolved_height(&self, metrics: ControlMetrics) -> f32 {
6400 self.height.unwrap_or(metrics.status_bar_height)
6401 }
6402
6403 fn description_text(&self) -> Option<String> {
6404 self.description_reader
6405 .as_ref()
6406 .map(|reader| reader())
6407 .or_else(|| self.description.clone())
6408 }
6409
6410 fn resolved_segment_min_width(segment: &StatusBarSegment, metrics: ControlMetrics) -> f32 {
6411 segment
6412 .min_width
6413 .unwrap_or(metrics.status_bar_segment_min_width)
6414 }
6415
6416 fn segment_widths(&self, metrics: ControlMetrics) -> Vec<f32> {
6417 if self.measured_widths.len() == self.segments.len() {
6418 self.measured_widths.clone()
6419 } else {
6420 self.segments
6421 .iter()
6422 .map(|segment| Self::resolved_segment_min_width(segment, metrics))
6423 .collect()
6424 }
6425 }
6426
6427 fn segment_rects(&self, bounds: Rect, metrics: ControlMetrics) -> Vec<Rect> {
6428 let mut widths = self.segment_widths(metrics);
6429 let expandable = self
6430 .segments
6431 .iter()
6432 .filter(|segment| segment.expand)
6433 .count();
6434 if expandable > 0 {
6435 let fixed: f32 = widths.iter().sum();
6436 let extra = (bounds.width() - fixed).max(0.0) / expandable as f32;
6437 for (index, segment) in self.segments.iter().enumerate() {
6438 if segment.expand {
6439 widths[index] += extra;
6440 }
6441 }
6442 }
6443
6444 let mut x = bounds.x();
6445 widths
6446 .into_iter()
6447 .map(|width| {
6448 let available = (bounds.max_x() - x).max(0.0);
6449 let rect = Rect::new(x, bounds.y(), width.min(available), bounds.height());
6450 x = rect.max_x();
6451 rect
6452 })
6453 .collect()
6454 }
6455}
6456
6457impl Default for StatusBar {
6458 fn default() -> Self {
6459 Self::new()
6460 }
6461}
6462
6463pub struct StatusBarHost {
6464 content: SingleChild,
6465 status_bar: SingleChild,
6466}
6467
6468impl StatusBarHost {
6469 pub fn new<C, S>(content: C, status_bar: S) -> Self
6470 where
6471 C: Widget + 'static,
6472 S: Widget + 'static,
6473 {
6474 Self {
6475 content: SingleChild::new(content),
6476 status_bar: SingleChild::new(status_bar),
6477 }
6478 }
6479
6480 pub fn content(&self) -> &sui_runtime::WidgetPod {
6481 self.content.child()
6482 }
6483
6484 pub fn content_mut(&mut self) -> &mut sui_runtime::WidgetPod {
6485 self.content.child_mut()
6486 }
6487
6488 pub fn status_bar(&self) -> &sui_runtime::WidgetPod {
6489 self.status_bar.child()
6490 }
6491
6492 pub fn status_bar_mut(&mut self) -> &mut sui_runtime::WidgetPod {
6493 self.status_bar.child_mut()
6494 }
6495}
6496
6497impl Widget for StatusBarHost {
6498 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6499 let max = constraints.max;
6500 let status_size = self.status_bar.measure(
6501 ctx,
6502 Constraints::new(Size::ZERO, Size::new(max.width, max.height)),
6503 );
6504 let content_max_height = if max.height.is_finite() {
6505 (max.height - status_size.height).max(0.0)
6506 } else {
6507 f32::INFINITY
6508 };
6509 let content_size = self.content.measure(
6510 ctx,
6511 Constraints::new(Size::ZERO, Size::new(max.width, content_max_height)),
6512 );
6513
6514 constraints.clamp(Size::new(
6515 content_size.width.max(status_size.width),
6516 content_size.height + status_size.height,
6517 ))
6518 }
6519
6520 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
6521 let status_height = self
6522 .status_bar
6523 .child()
6524 .measured_size()
6525 .height
6526 .min(bounds.height())
6527 .max(0.0);
6528 let content_height = (bounds.height() - status_height).max(0.0);
6529
6530 self.content.arrange(
6531 ctx,
6532 Rect::new(bounds.x(), bounds.y(), bounds.width(), content_height),
6533 );
6534 self.status_bar.arrange(
6535 ctx,
6536 Rect::new(
6537 bounds.x(),
6538 bounds.y() + content_height,
6539 bounds.width(),
6540 status_height,
6541 ),
6542 );
6543 }
6544
6545 fn paint(&self, ctx: &mut PaintCtx) {
6546 self.content.paint(ctx);
6547 self.status_bar.paint(ctx);
6548 }
6549
6550 fn semantics(&self, ctx: &mut SemanticsCtx) {
6551 self.content.semantics(ctx);
6552 self.status_bar.semantics(ctx);
6553 }
6554
6555 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
6556 self.content.visit_children(visitor);
6557 self.status_bar.visit_children(visitor);
6558 }
6559
6560 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
6561 self.content.visit_children_mut(visitor);
6562 self.status_bar.visit_children_mut(visitor);
6563 }
6564}
6565
6566impl Widget for StatusBar {
6567 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6568 let theme = self.resolved_theme();
6569 let metrics = theme.metrics;
6570 let text_style = self.text_style();
6571 self.measured_widths = self
6572 .segments
6573 .iter()
6574 .map(|segment| {
6575 let text = segment.text();
6576 let segment_style = numeric_text_style_if_numeric(&text, text_style.clone());
6577 let measured = measure_text(ctx, &text, &segment_style).width
6578 + metrics.status_bar_segment_padding * 2.0;
6579 Self::resolved_segment_min_width(segment, metrics).max(measured.ceil())
6580 })
6581 .collect();
6582 let natural_width: f32 = self.measured_widths.iter().sum();
6583 constraints.clamp(Size::new(
6584 if constraints.max.width.is_finite() {
6585 constraints.max.width
6586 } else {
6587 natural_width
6588 },
6589 self.resolved_height(metrics),
6590 ))
6591 }
6592
6593 fn paint(&self, ctx: &mut PaintCtx) {
6594 let theme = self.resolved_theme();
6595 let palette = theme.palette;
6596 let metrics = theme.metrics;
6597 let bounds = ctx.bounds();
6598 ctx.fill_bounds(palette.surface);
6599 ctx.stroke_rect(
6600 Rect::new(bounds.x(), bounds.y(), bounds.width(), 1.0),
6601 palette.border,
6602 StrokeStyle::new(theme.metrics.border_width.max(1.0)),
6603 );
6604
6605 let text_style = self.text_style();
6606 for (index, (segment, rect)) in self
6607 .segments
6608 .iter()
6609 .zip(self.segment_rects(bounds, metrics))
6610 .enumerate()
6611 {
6612 if rect.is_empty() {
6613 continue;
6614 }
6615 if index > 0 {
6616 let inset = metrics.status_bar_separator_inset.min(rect.height() * 0.5);
6617 ctx.stroke_rect(
6618 Rect::new(
6619 rect.x(),
6620 rect.y() + inset,
6621 1.0,
6622 (rect.height() - inset * 2.0).max(0.0),
6623 ),
6624 palette.border.with_alpha(0.7),
6625 StrokeStyle::new(1.0),
6626 );
6627 }
6628 let segment_text = segment.text();
6629 let segment_style = if segment.tone == SemanticTone::Neutral {
6630 text_style.clone()
6631 } else {
6632 let tone = theme.semantic_tone_color(segment.tone);
6633 let pill = Rect::new(
6634 rect.x() + metrics.status_bar_separator_inset.min(rect.width() * 0.5),
6635 rect.y() + metrics.status_bar_separator_inset.min(rect.height() * 0.5),
6636 (rect.width() - metrics.status_bar_separator_inset * 2.0).max(0.0),
6637 (rect.height() - metrics.status_bar_separator_inset * 2.0).max(0.0),
6638 );
6639 if !pill.is_empty() {
6640 ctx.fill(
6641 rounded_rect_path(pill, metrics.indicator_corner_radius),
6642 tone.with_alpha(0.12),
6643 );
6644 }
6645 TextStyle {
6646 color: tone,
6647 ..text_style.clone()
6648 }
6649 };
6650 let segment_style = numeric_text_style_if_numeric(&segment_text, segment_style);
6651 let content_rect = Rect::new(
6652 rect.x() + metrics.status_bar_segment_padding,
6653 rect.y(),
6654 (rect.width() - metrics.status_bar_segment_padding * 2.0).max(0.0),
6655 rect.height(),
6656 );
6657 ctx.push_clip_rect(content_rect);
6658 paint_aligned_text(
6659 ctx,
6660 content_rect,
6661 &segment_text,
6662 &segment_style,
6663 segment_style.line_height,
6664 0.0,
6665 );
6666 ctx.pop_clip();
6667 }
6668 }
6669
6670 fn semantics(&self, ctx: &mut SemanticsCtx) {
6671 let theme = self.resolved_theme();
6672 let metrics = theme.metrics;
6673 let mut node = SemanticsNode::new(
6674 ctx.widget_id(),
6675 SemanticsRole::GenericContainer,
6676 ctx.bounds(),
6677 );
6678 node.name = self.name.clone();
6679 if let Some(description) = self.description_text() {
6680 node.value = Some(SemanticsValue::Text(description.clone()));
6681 node.description = Some(description);
6682 }
6683 ctx.push(node);
6684
6685 for (index, (segment, rect)) in self
6686 .segments
6687 .iter()
6688 .zip(self.segment_rects(ctx.bounds(), metrics))
6689 .enumerate()
6690 {
6691 let text = segment.text();
6692 let mut child = SemanticsNode::new(
6693 status_bar_segment_id(ctx.widget_id(), index),
6694 SemanticsRole::Text,
6695 rect,
6696 );
6697 child.parent = Some(ctx.widget_id());
6698 child.name = Some(text.clone());
6699 child.value = Some(SemanticsValue::Text(text));
6700 ctx.push(child);
6701 }
6702 }
6703}
6704
6705fn status_bar_segment_id(parent: WidgetId, index: usize) -> WidgetId {
6706 const TAG: u64 = 2_u64 << 51;
6707 const LOW_MASK: u64 = (1_u64 << 51) - 1;
6708
6709 WidgetId::new(
6710 TAG | (parent
6711 .get()
6712 .wrapping_mul(263)
6713 .wrapping_add(index as u64 + 1)
6714 & LOW_MASK),
6715 )
6716}
6717
6718type SegmentedControlChange = Box<dyn FnMut(usize, String)>;
6719type SegmentedControlContextChange = Box<dyn FnMut(usize, String, &mut EventCtx)>;
6720
6721fn segmented_control_item_id(parent: WidgetId, index: usize) -> WidgetId {
6722 const TAG: u64 = 3_u64 << 51;
6723 const LOW_MASK: u64 = (1_u64 << 51) - 1;
6724
6725 WidgetId::new(
6726 TAG | (parent
6727 .get()
6728 .wrapping_mul(269)
6729 .wrapping_add(index as u64 + 1)
6730 & LOW_MASK),
6731 )
6732}
6733
6734pub struct StatusBadge {
6735 theme: Box<DefaultTheme>,
6736 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
6737 label: String,
6738 label_reader: Option<Box<dyn Fn() -> String>>,
6739 icon: Option<IconGlyph>,
6740 tone: SemanticTone,
6741 tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
6742 min_width: Option<f32>,
6743}
6744
6745impl StatusBadge {
6746 pub fn new(label: impl Into<String>) -> Self {
6747 Self {
6748 theme: Box::new(DefaultTheme::default()),
6749 theme_reader: None,
6750 label: label.into(),
6751 label_reader: None,
6752 icon: None,
6753 tone: SemanticTone::Neutral,
6754 tone_reader: None,
6755 min_width: None,
6756 }
6757 }
6758
6759 pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
6760 where
6761 F: Fn() -> String + 'static,
6762 {
6763 Self {
6764 label: fallback.into(),
6765 label_reader: Some(Box::new(reader)),
6766 ..Self::new("")
6767 }
6768 }
6769
6770 pub fn theme(mut self, theme: DefaultTheme) -> Self {
6771 self.theme = Box::new(theme);
6772 self.theme_reader = None;
6773 self
6774 }
6775
6776 pub fn theme_when<F>(mut self, theme: F) -> Self
6777 where
6778 F: Fn() -> DefaultTheme + 'static,
6779 {
6780 self.theme_reader = Some(Box::new(theme));
6781 self
6782 }
6783
6784 pub fn icon(mut self, icon: IconGlyph) -> Self {
6785 self.icon = Some(icon);
6786 self
6787 }
6788
6789 pub fn tone(mut self, tone: SemanticTone) -> Self {
6790 self.tone = tone;
6791 self.tone_reader = None;
6792 self
6793 }
6794
6795 pub fn tone_when<F>(mut self, tone: F) -> Self
6796 where
6797 F: Fn() -> SemanticTone + 'static,
6798 {
6799 self.tone_reader = Some(Box::new(tone));
6800 self
6801 }
6802
6803 pub fn min_width(mut self, min_width: f32) -> Self {
6804 self.min_width = Some(min_width.max(0.0));
6805 self
6806 }
6807
6808 fn resolved_theme(&self) -> DefaultTheme {
6809 self.theme_reader
6810 .as_ref()
6811 .map(|theme| theme())
6812 .unwrap_or(*self.theme)
6813 }
6814
6815 fn label(&self) -> String {
6816 self.label_reader
6817 .as_ref()
6818 .map(|reader| reader())
6819 .unwrap_or_else(|| self.label.clone())
6820 }
6821
6822 fn resolved_tone(&self) -> SemanticTone {
6823 self.tone_reader
6824 .as_ref()
6825 .map(|reader| reader())
6826 .unwrap_or(self.tone)
6827 }
6828
6829 fn text_style(&self, theme: &DefaultTheme, label: &str, tone: SemanticTone) -> TextStyle {
6830 let (_, tone_ink) = theme.semantic_tone_soft_colors(tone);
6833 let style = semibold_control_text_style(theme, tone_ink);
6834 numeric_text_style_if_numeric(label, style)
6835 }
6836
6837 fn metrics(&self, theme: &DefaultTheme) -> (f32, f32, f32, f32) {
6838 let height = (theme.metrics.min_height - 2.0).max(22.0);
6839 let icon_size = (height - 13.0).clamp(11.0, 15.0);
6840 let gap = theme.metrics.icon_label_gap.max(4.0);
6841 let padding = theme.metrics.button_padding.left.max(8.0);
6842 (height, icon_size, gap, padding)
6843 }
6844}
6845
6846pub fn paint_status_badge(
6847 ctx: &mut PaintCtx,
6848 rect: Rect,
6849 theme: &DefaultTheme,
6850 label: &str,
6851 icon: Option<IconGlyph>,
6852 tone: SemanticTone,
6853) {
6854 if rect.width() <= 0.0 || rect.height() <= 0.0 {
6855 return;
6856 }
6857
6858 let (tone_soft, tone_ink) = theme.semantic_tone_soft_colors(tone);
6862 let icon_size = (rect.height() - 13.0).clamp(11.0, 15.0);
6863 let gap = theme.metrics.icon_label_gap.max(4.0);
6864 let padding = theme.metrics.button_padding.left.max(6.0);
6865 let radius = theme.radius.sm.min(rect.height() * 0.5);
6866
6867 ctx.fill(rounded_rect_path(rect, radius), tone_soft);
6868
6869 let mut x = rect.x() + padding.min(rect.width() * 0.5);
6870 if let Some(icon) = icon {
6871 let icon_rect = Rect::new(
6872 x,
6873 rect.y() + (rect.height() - icon_size) * 0.5,
6874 icon_size,
6875 icon_size,
6876 );
6877 draw_icon_glyph(ctx, icon, icon_rect, tone_ink);
6878 x = icon_rect.max_x() + gap;
6879 }
6880 let content_rect = Rect::new(
6881 x,
6882 rect.y(),
6883 (rect.max_x() - x - padding * 0.5).max(0.0),
6884 rect.height(),
6885 );
6886 if content_rect.width() <= 0.0 {
6887 return;
6888 }
6889
6890 let style = semibold_control_text_style(theme, tone_ink);
6891 let style = numeric_text_style_if_numeric(label, style);
6892 ctx.push_clip_rect(content_rect);
6893 paint_aligned_text_contained(ctx, content_rect, label, &style, style.line_height, 0.0);
6894 ctx.pop_clip();
6895}
6896
6897#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6898pub enum CommandButtonFill {
6899 Surface,
6900 Filled,
6901}
6902
6903#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6904pub struct CommandButtonPaint {
6905 pub tone: SemanticTone,
6906 pub icon_tone: Option<SemanticTone>,
6907 pub fill: CommandButtonFill,
6908 pub hovered: bool,
6909 pub pressed: bool,
6910}
6911
6912impl CommandButtonPaint {
6913 pub const fn neutral() -> Self {
6914 Self {
6915 tone: SemanticTone::Neutral,
6916 icon_tone: None,
6917 fill: CommandButtonFill::Surface,
6918 hovered: false,
6919 pressed: false,
6920 }
6921 }
6922
6923 pub const fn tonal(tone: SemanticTone) -> Self {
6924 Self {
6925 tone,
6926 icon_tone: None,
6927 fill: CommandButtonFill::Surface,
6928 hovered: false,
6929 pressed: false,
6930 }
6931 }
6932
6933 pub const fn filled(tone: SemanticTone) -> Self {
6934 Self {
6935 tone,
6936 icon_tone: None,
6937 fill: CommandButtonFill::Filled,
6938 hovered: false,
6939 pressed: false,
6940 }
6941 }
6942
6943 pub const fn icon_tone(mut self, tone: SemanticTone) -> Self {
6944 self.icon_tone = Some(tone);
6945 self
6946 }
6947
6948 pub const fn hovered(mut self, hovered: bool) -> Self {
6949 self.hovered = hovered;
6950 self
6951 }
6952
6953 pub const fn pressed(mut self, pressed: bool) -> Self {
6954 self.pressed = pressed;
6955 self
6956 }
6957}
6958
6959impl Default for CommandButtonPaint {
6960 fn default() -> Self {
6961 Self::neutral()
6962 }
6963}
6964
6965#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6966pub struct DisclosureButtonPaint {
6967 pub command: CommandButtonPaint,
6968}
6969
6970impl DisclosureButtonPaint {
6971 pub const fn new() -> Self {
6972 Self {
6973 command: CommandButtonPaint::tonal(SemanticTone::Accent)
6974 .icon_tone(SemanticTone::Accent),
6975 }
6976 }
6977
6978 pub const fn command(mut self, command: CommandButtonPaint) -> Self {
6979 self.command = command;
6980 self
6981 }
6982
6983 pub const fn tone(mut self, tone: SemanticTone) -> Self {
6984 self.command = CommandButtonPaint::tonal(tone).icon_tone(tone);
6985 self
6986 }
6987
6988 pub const fn hovered(mut self, hovered: bool) -> Self {
6989 self.command = self.command.hovered(hovered);
6990 self
6991 }
6992
6993 pub const fn pressed(mut self, pressed: bool) -> Self {
6994 self.command = self.command.pressed(pressed);
6995 self
6996 }
6997}
6998
6999impl Default for DisclosureButtonPaint {
7000 fn default() -> Self {
7001 Self::new()
7002 }
7003}
7004
7005pub fn paint_command_button(
7006 ctx: &mut PaintCtx,
7007 theme: &DefaultTheme,
7008 rect: Rect,
7009 label: &str,
7010 icon: Option<IconGlyph>,
7011 style: CommandButtonPaint,
7012) {
7013 if rect.width() <= 0.0 || rect.height() <= 0.0 {
7014 return;
7015 }
7016
7017 let (tone_color, tone_text) = theme.semantic_tone_colors(style.tone);
7018 let (base_fill, border, label_color) = match style.fill {
7019 CommandButtonFill::Surface => {
7020 let label_color = if style.tone == SemanticTone::Neutral {
7021 theme.palette.text
7022 } else {
7023 tone_color
7024 };
7025 let border = if style.tone == SemanticTone::Neutral {
7026 theme.palette.border
7027 } else {
7028 tone_color.with_alpha(0.72)
7029 };
7030 (theme.surfaces.field, border, label_color)
7031 }
7032 CommandButtonFill::Filled => (tone_color, tone_color, tone_text),
7033 };
7034 let fill = match style.fill {
7035 CommandButtonFill::Surface if style.pressed => theme.palette.control_active,
7036 CommandButtonFill::Surface if style.hovered => theme.palette.control_hover,
7037 CommandButtonFill::Filled
7038 if style.pressed && matches!(style.tone, SemanticTone::Accent) =>
7039 {
7040 theme.palette.accent_pressed
7041 }
7042 CommandButtonFill::Filled
7043 if style.hovered && matches!(style.tone, SemanticTone::Accent) =>
7044 {
7045 theme.palette.accent_hover
7046 }
7047 _ => base_fill,
7048 };
7049 let icon_color = style
7050 .icon_tone
7051 .map(|tone| {
7052 if style.fill == CommandButtonFill::Filled && tone == style.tone {
7053 theme.semantic_tone_text_color(tone)
7054 } else if tone == SemanticTone::Neutral {
7055 theme.palette.text_muted
7056 } else {
7057 theme.semantic_tone_color(tone)
7058 }
7059 })
7060 .unwrap_or_else(|| match style.fill {
7061 CommandButtonFill::Surface => {
7062 if style.tone == SemanticTone::Neutral {
7063 theme.palette.text_muted
7064 } else {
7065 tone_color
7066 }
7067 }
7068 CommandButtonFill::Filled => tone_text,
7069 });
7070
7071 let radius = theme
7072 .metrics
7073 .corner_radius
7074 .min(rect.height() * 0.35)
7075 .max(0.0);
7076 ctx.fill(rounded_rect_path(rect, radius), fill);
7077 ctx.stroke(
7078 rounded_rect_path(rect, radius),
7079 border,
7080 StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7081 );
7082
7083 let icon_size = (rect.height() - 14.0).clamp(12.0, 16.0);
7084 let padding = theme
7085 .metrics
7086 .button_padding
7087 .left
7088 .max(8.0)
7089 .min(rect.width() * 0.4);
7090 let gap = theme.metrics.icon_label_gap.max(5.0);
7091 let mut text_x = rect.x() + padding;
7092 if let Some(icon) = icon {
7093 let icon_rect = Rect::new(
7094 rect.x() + padding,
7095 rect.y() + (rect.height() - icon_size) * 0.5,
7096 icon_size,
7097 icon_size,
7098 );
7099 draw_icon_glyph(ctx, icon, icon_rect, icon_color);
7100 text_x = icon_rect.max_x() + gap;
7101 }
7102
7103 let label_rect = Rect::new(
7104 text_x,
7105 rect.y(),
7106 (rect.max_x() - text_x - padding * 0.75).max(0.0),
7107 rect.height(),
7108 );
7109 if label_rect.width() <= 0.0 {
7110 return;
7111 }
7112
7113 let mut text_style = text_token_style(theme, theme.text.sm, label_color);
7114 text_style.weight = FontWeight::SEMIBOLD;
7115 let text_style = numeric_text_style_if_numeric(label, text_style);
7116 ctx.push_clip_rect(label_rect);
7117 paint_single_line_aligned_text(
7118 ctx,
7119 label_rect,
7120 label,
7121 &text_style,
7122 text_style.line_height,
7123 0.0,
7124 );
7125 ctx.pop_clip();
7126}
7127
7128pub fn paint_disclosure_button(
7129 ctx: &mut PaintCtx,
7130 theme: &DefaultTheme,
7131 rect: Rect,
7132 label: &str,
7133 expanded: bool,
7134 paint: DisclosureButtonPaint,
7135) {
7136 paint_command_button(
7137 ctx,
7138 theme,
7139 rect,
7140 label,
7141 Some(if expanded {
7142 IconGlyph::ChevronUp
7143 } else {
7144 IconGlyph::ChevronDown
7145 }),
7146 paint.command,
7147 );
7148}
7149
7150#[derive(Clone, Copy, Debug, PartialEq)]
7151pub struct ActionTilePaint {
7152 pub tone: SemanticTone,
7153 pub highlighted: bool,
7154 pub hovered: bool,
7155 pub pressed: bool,
7156 pub enabled: bool,
7157 pub background: Option<Color>,
7158 pub border: Option<Color>,
7159 pub title_color: Option<Color>,
7160 pub subtitle_color: Option<Color>,
7161 pub icon_color: Option<Color>,
7162 pub leading_tone_dot: Option<SemanticTone>,
7163 pub radius: Option<f32>,
7164 pub padding_x: Option<f32>,
7165 pub leading_width: f32,
7166 pub trailing_width: f32,
7167}
7168
7169impl ActionTilePaint {
7170 pub const fn neutral() -> Self {
7171 Self {
7172 tone: SemanticTone::Neutral,
7173 highlighted: false,
7174 hovered: false,
7175 pressed: false,
7176 enabled: true,
7177 background: None,
7178 border: None,
7179 title_color: None,
7180 subtitle_color: None,
7181 icon_color: None,
7182 leading_tone_dot: None,
7183 radius: None,
7184 padding_x: None,
7185 leading_width: 0.0,
7186 trailing_width: 0.0,
7187 }
7188 }
7189
7190 pub const fn tonal(tone: SemanticTone) -> Self {
7191 Self {
7192 tone,
7193 highlighted: true,
7194 hovered: false,
7195 pressed: false,
7196 enabled: true,
7197 background: None,
7198 border: None,
7199 title_color: None,
7200 subtitle_color: None,
7201 icon_color: None,
7202 leading_tone_dot: None,
7203 radius: None,
7204 padding_x: None,
7205 leading_width: 0.0,
7206 trailing_width: 0.0,
7207 }
7208 }
7209
7210 pub const fn highlighted(mut self, highlighted: bool) -> Self {
7211 self.highlighted = highlighted;
7212 self
7213 }
7214
7215 pub const fn hovered(mut self, hovered: bool) -> Self {
7216 self.hovered = hovered;
7217 self
7218 }
7219
7220 pub const fn pressed(mut self, pressed: bool) -> Self {
7221 self.pressed = pressed;
7222 self
7223 }
7224
7225 pub const fn enabled(mut self, enabled: bool) -> Self {
7226 self.enabled = enabled;
7227 self
7228 }
7229
7230 pub const fn background(mut self, background: Color) -> Self {
7231 self.background = Some(background);
7232 self
7233 }
7234
7235 pub const fn border(mut self, border: Color) -> Self {
7236 self.border = Some(border);
7237 self
7238 }
7239
7240 pub const fn title_color(mut self, title_color: Color) -> Self {
7241 self.title_color = Some(title_color);
7242 self
7243 }
7244
7245 pub const fn subtitle_color(mut self, subtitle_color: Color) -> Self {
7246 self.subtitle_color = Some(subtitle_color);
7247 self
7248 }
7249
7250 pub const fn icon_color(mut self, icon_color: Color) -> Self {
7251 self.icon_color = Some(icon_color);
7252 self
7253 }
7254
7255 pub const fn leading_tone_dot(mut self, tone: SemanticTone) -> Self {
7256 self.leading_tone_dot = Some(tone);
7257 self
7258 }
7259
7260 pub const fn radius(mut self, radius: f32) -> Self {
7261 self.radius = Some(radius);
7262 self
7263 }
7264
7265 pub const fn padding_x(mut self, padding_x: f32) -> Self {
7266 self.padding_x = Some(padding_x);
7267 self
7268 }
7269
7270 pub const fn leading_width(mut self, leading_width: f32) -> Self {
7271 self.leading_width = leading_width;
7272 self
7273 }
7274
7275 pub const fn trailing_width(mut self, trailing_width: f32) -> Self {
7276 self.trailing_width = trailing_width;
7277 self
7278 }
7279}
7280
7281impl Default for ActionTilePaint {
7282 fn default() -> Self {
7283 Self::neutral()
7284 }
7285}
7286
7287#[derive(Clone, Copy, Debug, PartialEq)]
7288pub struct CalloutPaint {
7289 pub tone: SemanticTone,
7290 pub fill: Option<Color>,
7291 pub border: Option<Color>,
7292 pub rail_color: Option<Color>,
7293 pub icon_color: Option<Color>,
7294 pub title_color: Option<Color>,
7295 pub body_color: Option<Color>,
7296 pub radius: Option<f32>,
7297 pub padding: Insets,
7298 pub icon_size: f32,
7299 pub icon_gap: f32,
7300 pub rail_width: f32,
7301 pub reserved_bottom: f32,
7302}
7303
7304impl CalloutPaint {
7305 pub const fn new(tone: SemanticTone) -> Self {
7306 Self {
7307 tone,
7308 fill: None,
7309 border: None,
7310 rail_color: None,
7311 icon_color: None,
7312 title_color: None,
7313 body_color: None,
7314 radius: None,
7315 padding: Insets {
7316 left: 12.0,
7317 top: 10.0,
7318 right: 12.0,
7319 bottom: 10.0,
7320 },
7321 icon_size: 15.0,
7322 icon_gap: 9.0,
7323 rail_width: 2.0,
7324 reserved_bottom: 0.0,
7325 }
7326 }
7327
7328 pub const fn fill(mut self, fill: Color) -> Self {
7329 self.fill = Some(fill);
7330 self
7331 }
7332
7333 pub const fn border(mut self, border: Color) -> Self {
7334 self.border = Some(border);
7335 self
7336 }
7337
7338 pub const fn rail_color(mut self, rail_color: Color) -> Self {
7339 self.rail_color = Some(rail_color);
7340 self
7341 }
7342
7343 pub const fn icon_color(mut self, icon_color: Color) -> Self {
7344 self.icon_color = Some(icon_color);
7345 self
7346 }
7347
7348 pub const fn title_color(mut self, title_color: Color) -> Self {
7349 self.title_color = Some(title_color);
7350 self
7351 }
7352
7353 pub const fn body_color(mut self, body_color: Color) -> Self {
7354 self.body_color = Some(body_color);
7355 self
7356 }
7357
7358 pub const fn radius(mut self, radius: f32) -> Self {
7359 self.radius = Some(radius);
7360 self
7361 }
7362
7363 pub const fn padding(mut self, padding: Insets) -> Self {
7364 self.padding = padding;
7365 self
7366 }
7367
7368 pub const fn icon_size(mut self, icon_size: f32) -> Self {
7369 self.icon_size = icon_size;
7370 self
7371 }
7372
7373 pub const fn icon_gap(mut self, icon_gap: f32) -> Self {
7374 self.icon_gap = icon_gap;
7375 self
7376 }
7377
7378 pub const fn rail_width(mut self, rail_width: f32) -> Self {
7379 self.rail_width = rail_width;
7380 self
7381 }
7382
7383 pub const fn reserved_bottom(mut self, reserved_bottom: f32) -> Self {
7384 self.reserved_bottom = reserved_bottom;
7385 self
7386 }
7387}
7388
7389impl Default for CalloutPaint {
7390 fn default() -> Self {
7391 Self::new(SemanticTone::Info)
7392 }
7393}
7394
7395pub fn paint_callout(
7396 ctx: &mut PaintCtx,
7397 theme: &DefaultTheme,
7398 rect: Rect,
7399 icon: Option<IconGlyph>,
7400 title: Option<&str>,
7401 body: &str,
7402 style: CalloutPaint,
7403) {
7404 if rect.width() <= 0.0 || rect.height() <= 0.0 {
7405 return;
7406 }
7407
7408 let palette = theme.palette;
7409 let (tone_color, _) = theme.semantic_tone_colors(style.tone);
7410 let (tone_soft, tone_ink) = theme.semantic_tone_soft_colors(style.tone);
7413 let fill = style.fill.unwrap_or(tone_soft);
7414 let border = style.border.unwrap_or(palette.border);
7415 let rail = style.rail_color.unwrap_or(tone_color);
7416 let radius = style.radius.unwrap_or(theme.radius.md).max(0.0);
7417
7418 ctx.fill(rounded_rect_path(rect, radius), fill);
7419 ctx.stroke(
7420 rounded_rect_path(rect, radius),
7421 border,
7422 StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7423 );
7424
7425 let rail_width = style.rail_width.max(0.0).min(rect.width());
7426 if rail_width > 0.0 {
7427 let rail_rect = Rect::new(rect.x(), rect.y(), rail_width, rect.height());
7428 ctx.fill(rounded_rect_path(rail_rect, rail_width * 0.5), rail);
7429 }
7430
7431 let padding = style.padding;
7432 let content_bottom = (rect.max_y() - padding.bottom.max(0.0) - style.reserved_bottom.max(0.0))
7433 .max(rect.y() + padding.top.max(0.0));
7434 let content = Rect::new(
7435 rect.x() + padding.left.max(0.0),
7436 rect.y() + padding.top.max(0.0),
7437 (rect.width() - padding.left.max(0.0) - padding.right.max(0.0)).max(0.0),
7438 (content_bottom - rect.y() - padding.top.max(0.0)).max(0.0),
7439 );
7440 if content.width() <= 0.0 || content.height() <= 0.0 {
7441 return;
7442 }
7443
7444 let icon_size = style
7445 .icon_size
7446 .max(0.0)
7447 .min(content.height())
7448 .min(content.width());
7449 let mut text_x = content.x();
7450 if let Some(icon) = icon.filter(|_| icon_size > 0.0) {
7451 let icon_rect = Rect::new(
7452 content.x(),
7453 content.y() + 2.0_f32.min((content.height() - icon_size).max(0.0)),
7454 icon_size,
7455 icon_size,
7456 );
7457 draw_icon_glyph(ctx, icon, icon_rect, style.icon_color.unwrap_or(tone_ink));
7458 text_x = icon_rect.max_x() + style.icon_gap.max(0.0);
7459 }
7460
7461 let text_rect = Rect::new(
7462 text_x,
7463 content.y(),
7464 (content.max_x() - text_x).max(0.0),
7465 content.height(),
7466 );
7467 if text_rect.width() <= 0.0 || text_rect.height() <= 0.0 {
7468 return;
7469 }
7470
7471 let title_line = if title.is_some() {
7472 theme.text.sm.line_height
7473 } else {
7474 0.0
7475 };
7476 if let Some(title) = title {
7477 let mut title_style = text_token_style(
7478 theme,
7479 theme.text.sm,
7480 style.title_color.unwrap_or(palette.text),
7481 );
7482 title_style.weight = FontWeight::SEMIBOLD;
7483 let title_rect = Rect::new(text_rect.x(), text_rect.y(), text_rect.width(), title_line);
7484 ctx.push_clip_rect(title_rect);
7485 paint_single_line_aligned_text(
7486 ctx,
7487 title_rect,
7488 title,
7489 &title_style,
7490 title_style.line_height,
7491 0.0,
7492 );
7493 ctx.pop_clip();
7494 }
7495
7496 if body.trim().is_empty() {
7497 return;
7498 }
7499 let body_y = text_rect.y() + title_line + if title.is_some() { 4.0 } else { 0.0 };
7500 let body_rect = Rect::new(
7501 text_rect.x(),
7502 body_y,
7503 text_rect.width(),
7504 (text_rect.max_y() - body_y).max(0.0),
7505 );
7506 if body_rect.width() <= 0.0 || body_rect.height() <= 0.0 {
7507 return;
7508 }
7509
7510 let color = style.body_color.unwrap_or(palette.text_muted);
7511 let mut layout_style = text_token_style(theme, theme.text.sm, color);
7512 layout_style.color = Color::WHITE;
7513 let mut document = TextDocument::from_plain_text(body.to_string(), layout_style);
7514 for paragraph in &mut document.paragraphs {
7515 paragraph.style.align = TextAlign::Start;
7516 paragraph.style.wrap = TextWrap::Word;
7517 }
7518
7519 ctx.push_clip_rect(body_rect);
7520 if let Ok(layout) = ctx.layout_text_document(TextLayoutRequest::new(document).with_box_size(
7521 Size::new(body_rect.width().max(1.0), body_rect.height().max(1.0)),
7522 )) {
7523 ctx.draw_text_layout_with_color(body_rect.origin, &layout, color);
7524 } else {
7525 let fallback_style = text_token_style(theme, theme.text.sm, color);
7526 ctx.draw_text(body_rect, body.to_string(), fallback_style);
7527 }
7528 ctx.pop_clip();
7529}
7530
7531pub fn paint_action_tile(
7532 ctx: &mut PaintCtx,
7533 theme: &DefaultTheme,
7534 rect: Rect,
7535 title: &str,
7536 subtitle: Option<&str>,
7537 icon: Option<IconGlyph>,
7538 style: ActionTilePaint,
7539) {
7540 if rect.width() <= 0.0 || rect.height() <= 0.0 {
7541 return;
7542 }
7543
7544 let palette = theme.palette;
7545 let tone_color = theme.semantic_tone_color(style.tone);
7546 let effective_tone = if style.tone == SemanticTone::Neutral {
7547 palette.text_muted
7548 } else {
7549 tone_color
7550 };
7551 let base_background = if !style.enabled {
7552 mix_color(palette.control, palette.surface, 0.68).with_alpha(0.82)
7553 } else if style.pressed {
7554 palette.control_active
7555 } else if style.hovered {
7556 palette.control_hover
7557 } else {
7558 palette.control
7559 };
7560 let background = style.background.unwrap_or(base_background);
7561 let base_border = if !style.enabled {
7562 palette.border.with_alpha(0.55)
7563 } else if style.highlighted {
7564 effective_tone.with_alpha(0.84)
7565 } else if style.hovered {
7566 palette.border_hover
7567 } else {
7568 palette.border
7569 };
7570 let border = style.border.unwrap_or(base_border);
7571 let radius = theme
7572 .metrics
7573 .corner_radius
7574 .min(rect.height() * 0.28)
7575 .max(0.0);
7576 let radius = style.radius.unwrap_or(radius).max(0.0);
7577 ctx.fill(rounded_rect_path(rect, radius), background);
7578 ctx.stroke(
7579 rounded_rect_path(rect, radius),
7580 border,
7581 StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7582 );
7583
7584 let padding_x = style
7585 .padding_x
7586 .unwrap_or_else(|| theme.metrics.button_padding.left.max(10.0))
7587 .max(0.0)
7588 .min(rect.width() * 0.45);
7589 let compact = rect.height() <= 46.0 || subtitle.is_none();
7590 let base_icon_side: f32 = if compact { 14.0 } else { 17.0 };
7591 let icon_side = base_icon_side
7592 .min((rect.height() - 14.0).max(10.0))
7593 .max(0.0);
7594 let icon_y = if compact {
7595 rect.y() + (rect.height() - icon_side) * 0.5
7596 } else {
7597 rect.y() + 12.0
7598 };
7599 let mut text_x = rect.x() + padding_x;
7600 if let Some(icon) = icon {
7601 let icon_rect = Rect::new(rect.x() + padding_x, icon_y, icon_side, icon_side);
7602 let icon_color = style.icon_color.unwrap_or_else(|| {
7603 if style.enabled {
7604 if style.highlighted || style.hovered {
7605 effective_tone
7606 } else {
7607 palette.text_muted
7608 }
7609 } else {
7610 palette.text.with_alpha(0.34)
7611 }
7612 });
7613 draw_icon_glyph(ctx, icon, icon_rect, icon_color);
7614 text_x = icon_rect.max_x() + theme.metrics.icon_label_gap.max(7.0);
7615 } else if let Some(dot_tone) = style.leading_tone_dot {
7616 let dot_side = 8.0_f32.min((rect.height() - 12.0).max(4.0)).max(4.0);
7617 let leading_width = style
7618 .leading_width
7619 .max(dot_side + theme.metrics.icon_label_gap.max(7.0));
7620 let dot_rect = Rect::new(
7621 rect.x() + padding_x,
7622 if compact {
7623 rect.y() + (rect.height() - dot_side) * 0.5
7624 } else {
7625 rect.y() + 15.0_f32.min((rect.height() - dot_side).max(0.0))
7626 },
7627 dot_side,
7628 dot_side,
7629 );
7630 ctx.fill(
7631 rounded_rect_path(dot_rect, dot_side * 0.5),
7632 theme.semantic_tone_color(dot_tone),
7633 );
7634 text_x += leading_width;
7635 } else if style.leading_width > 0.0 {
7636 text_x += style.leading_width;
7637 }
7638
7639 let text_width = (rect.max_x() - text_x - padding_x - style.trailing_width.max(0.0)).max(0.0);
7640 if text_width <= 0.0 {
7641 return;
7642 }
7643
7644 let title_color = style.title_color.unwrap_or_else(|| {
7645 if !style.enabled {
7646 palette.text.with_alpha(0.42)
7647 } else if style.highlighted {
7648 palette.text
7649 } else {
7650 palette.text_muted
7651 }
7652 });
7653 let subtitle_color = style.subtitle_color.unwrap_or_else(|| {
7654 if !style.enabled {
7655 palette.text.with_alpha(0.32)
7656 } else {
7657 palette.placeholder
7658 }
7659 });
7660 let mut title_style = text_token_style(theme, theme.text.sm, title_color);
7661 title_style.weight = FontWeight::SEMIBOLD;
7662 let title_style = numeric_text_style_if_numeric(title, title_style);
7663 let subtitle_style = text_token_style(theme, theme.text.xs, subtitle_color);
7664
7665 if compact {
7666 let title_rect = Rect::new(text_x, rect.y(), text_width, rect.height());
7667 ctx.push_clip_rect(title_rect);
7668 paint_aligned_text(
7669 ctx,
7670 title_rect,
7671 title,
7672 &title_style,
7673 title_style.line_height,
7674 0.0,
7675 );
7676 ctx.pop_clip();
7677 return;
7678 }
7679
7680 let title_rect = Rect::new(text_x, rect.y() + 8.0, text_width, title_style.line_height);
7681 ctx.push_clip_rect(title_rect);
7682 paint_single_line_aligned_text(
7683 ctx,
7684 title_rect,
7685 title,
7686 &title_style,
7687 title_style.line_height,
7688 0.0,
7689 );
7690 ctx.pop_clip();
7691
7692 if let Some(subtitle) = subtitle {
7693 let subtitle_rect = Rect::new(
7694 text_x,
7695 title_rect.max_y() + theme.metrics.action_card_text_gap.min(3.0),
7696 text_width,
7697 subtitle_style.line_height,
7698 );
7699 ctx.push_clip_rect(subtitle_rect);
7700 paint_single_line_aligned_text(
7701 ctx,
7702 subtitle_rect,
7703 subtitle,
7704 &subtitle_style,
7705 subtitle_style.line_height,
7706 0.0,
7707 );
7708 ctx.pop_clip();
7709 }
7710}
7711
7712#[derive(Clone, Copy, Debug, PartialEq)]
7713pub struct CodePanelPaint {
7714 pub fill: Option<Color>,
7715 pub border: Option<Color>,
7716 pub header_fill: Option<Color>,
7717 pub label_color: Option<Color>,
7718 pub radius: Option<f32>,
7719 pub header_height: f32,
7720 pub content_padding: Insets,
7721 pub label_inset_x: f32,
7722}
7723
7724impl CodePanelPaint {
7725 pub const fn new() -> Self {
7726 Self {
7727 fill: None,
7728 border: None,
7729 header_fill: None,
7730 label_color: None,
7731 radius: None,
7732 header_height: 24.0,
7733 content_padding: Insets {
7734 left: 8.0,
7735 top: 6.0,
7736 right: 8.0,
7737 bottom: 4.0,
7738 },
7739 label_inset_x: 10.0,
7740 }
7741 }
7742
7743 pub const fn fill(mut self, fill: Color) -> Self {
7744 self.fill = Some(fill);
7745 self
7746 }
7747
7748 pub const fn border(mut self, border: Color) -> Self {
7749 self.border = Some(border);
7750 self
7751 }
7752
7753 pub const fn header_fill(mut self, header_fill: Color) -> Self {
7754 self.header_fill = Some(header_fill);
7755 self
7756 }
7757
7758 pub const fn label_color(mut self, label_color: Color) -> Self {
7759 self.label_color = Some(label_color);
7760 self
7761 }
7762
7763 pub const fn radius(mut self, radius: f32) -> Self {
7764 self.radius = Some(radius);
7765 self
7766 }
7767
7768 pub const fn header_height(mut self, header_height: f32) -> Self {
7769 self.header_height = header_height;
7770 self
7771 }
7772
7773 pub const fn content_padding(mut self, content_padding: Insets) -> Self {
7774 self.content_padding = content_padding;
7775 self
7776 }
7777
7778 pub const fn label_inset_x(mut self, label_inset_x: f32) -> Self {
7779 self.label_inset_x = label_inset_x;
7780 self
7781 }
7782}
7783
7784impl Default for CodePanelPaint {
7785 fn default() -> Self {
7786 Self::new()
7787 }
7788}
7789
7790#[derive(Clone, Copy, Debug, PartialEq)]
7791pub struct CodeTextSpan<'a> {
7792 pub text: &'a str,
7793 pub color: Option<Color>,
7794}
7795
7796impl<'a> CodeTextSpan<'a> {
7797 pub const fn new(text: &'a str) -> Self {
7798 Self { text, color: None }
7799 }
7800
7801 pub const fn color(mut self, color: Color) -> Self {
7802 self.color = Some(color);
7803 self
7804 }
7805}
7806
7807#[derive(Clone, Copy, Debug, PartialEq)]
7808pub struct CodeTextLine<'a> {
7809 pub spans: &'a [CodeTextSpan<'a>],
7810 pub background: Option<Color>,
7811 pub fallback_color: Option<Color>,
7812}
7813
7814impl<'a> CodeTextLine<'a> {
7815 pub const fn new(spans: &'a [CodeTextSpan<'a>]) -> Self {
7816 Self {
7817 spans,
7818 background: None,
7819 fallback_color: None,
7820 }
7821 }
7822
7823 pub const fn background(mut self, background: Color) -> Self {
7824 self.background = Some(background);
7825 self
7826 }
7827
7828 pub const fn fallback_color(mut self, color: Color) -> Self {
7829 self.fallback_color = Some(color);
7830 self
7831 }
7832}
7833
7834#[derive(Clone, Copy, Debug, PartialEq)]
7835pub struct CodeTextPaint {
7836 pub color: Option<Color>,
7837 pub font_size: f32,
7840 pub line_height: f32,
7843 pub x_padding: f32,
7844 pub weight: FontWeight,
7845}
7846
7847impl CodeTextPaint {
7848 pub const fn new() -> Self {
7849 Self {
7850 color: None,
7851 font_size: 0.0,
7852 line_height: 0.0,
7853 x_padding: 2.0,
7854 weight: FontWeight::NORMAL,
7855 }
7856 }
7857
7858 pub const fn color(mut self, color: Color) -> Self {
7859 self.color = Some(color);
7860 self
7861 }
7862
7863 pub const fn font_size(mut self, font_size: f32) -> Self {
7864 self.font_size = font_size;
7865 self
7866 }
7867
7868 pub const fn line_height(mut self, line_height: f32) -> Self {
7869 self.line_height = line_height;
7870 self
7871 }
7872
7873 pub const fn x_padding(mut self, x_padding: f32) -> Self {
7874 self.x_padding = x_padding;
7875 self
7876 }
7877
7878 pub const fn weight(mut self, weight: FontWeight) -> Self {
7879 self.weight = weight;
7880 self
7881 }
7882}
7883
7884impl Default for CodeTextPaint {
7885 fn default() -> Self {
7886 Self::new()
7887 }
7888}
7889
7890pub fn paint_code_lines(
7891 ctx: &mut PaintCtx,
7892 theme: &DefaultTheme,
7893 rect: Rect,
7894 lines: &[CodeTextLine<'_>],
7895 style: CodeTextPaint,
7896) {
7897 if rect.width() <= 0.0 || rect.height() <= 0.0 || lines.is_empty() {
7898 return;
7899 }
7900
7901 let token = theme.text.xs;
7902 let font_size = if style.font_size > 0.0 {
7903 style.font_size
7904 } else {
7905 token.size
7906 };
7907 let line_height = if style.line_height > 0.0 {
7908 style.line_height
7909 } else {
7910 token.line_height
7911 };
7912 let mut base_style = TextStyle {
7913 font_size: font_size.max(1.0),
7914 line_height: line_height.max(1.0),
7915 color: style.color.unwrap_or(theme.palette.text),
7916 ..theme.mono_text_style(theme.palette.text)
7917 };
7918 base_style.weight = style.weight;
7919
7920 let line_height = base_style.line_height;
7921 let mut y = rect.y();
7922 ctx.push_clip_rect(rect);
7923 for line in lines {
7924 if y + line_height > rect.max_y() {
7925 break;
7926 }
7927 if let Some(background) = line.background {
7928 ctx.fill_rect(
7929 Rect::new(rect.x(), y, rect.width(), line_height),
7930 background,
7931 );
7932 }
7933
7934 let mut x = rect.x() + style.x_padding.max(0.0);
7935 for span in line.spans {
7936 if span.text.is_empty() || x > rect.max_x() {
7937 continue;
7938 }
7939 let mut span_style = base_style.clone();
7940 span_style.color = span
7941 .color
7942 .or(line.fallback_color)
7943 .unwrap_or(base_style.color);
7944 let width = ctx
7945 .measure_text(span.text.to_string(), span_style.clone())
7946 .ok()
7947 .map(|measurement| measurement.width)
7948 .unwrap_or(0.0);
7949 ctx.draw_text(
7950 Rect::new(x, y, (rect.max_x() - x).max(0.0), line_height),
7951 span.text,
7952 span_style,
7953 );
7954 x += width;
7955 }
7956 y += line_height;
7957 }
7958 ctx.pop_clip();
7959}
7960
7961pub fn paint_code_panel(
7962 ctx: &mut PaintCtx,
7963 theme: &DefaultTheme,
7964 rect: Rect,
7965 label: &str,
7966 style: CodePanelPaint,
7967) -> Rect {
7968 if rect.width() <= 0.0 || rect.height() <= 0.0 {
7969 return Rect::ZERO;
7970 }
7971
7972 let fill = style.fill.unwrap_or(theme.surfaces.field);
7973 let border = style.border.unwrap_or(theme.surfaces.border);
7974 let header_fill = style.header_fill.unwrap_or(theme.surfaces.titlebar);
7975 let label_color = style.label_color.unwrap_or(theme.surfaces.text_faint);
7976 let radius = style
7977 .radius
7978 .unwrap_or(theme.radius.xl)
7979 .min(rect.width().min(rect.height()) * 0.5)
7980 .max(0.0);
7981 let border_width = physical_pixels(ctx, theme.metrics.border_width.max(1.0));
7982
7983 let panel_shape = rounded_rect_path(rect, radius);
7984 ctx.fill(panel_shape.clone(), fill);
7985
7986 let header_height = style.header_height.clamp(0.0, rect.height());
7987 if header_height > 0.0 {
7988 let header_rect = Rect::new(rect.x(), rect.y(), rect.width(), header_height);
7989 let header_radius = radius.min(header_height * 0.5);
7990 ctx.fill(rounded_rect_path(header_rect, header_radius), header_fill);
7991 if header_height > header_radius {
7992 ctx.fill_rect(
7993 Rect::new(
7994 header_rect.x(),
7995 (header_rect.max_y() - header_radius).max(header_rect.y()),
7996 header_rect.width(),
7997 header_radius,
7998 ),
7999 header_fill,
8000 );
8001 }
8002
8003 let mut label_style = text_token_style(theme, theme.text.xs, label_color);
8004 label_style.weight = FontWeight::SEMIBOLD;
8005 let label_x = rect.x() + style.label_inset_x.max(0.0);
8006 let label_rect = Rect::new(
8007 label_x,
8008 rect.y() + ((header_height - label_style.line_height) * 0.5).max(0.0),
8009 (rect.max_x() - label_x - style.label_inset_x.max(0.0)).max(0.0),
8010 label_style.line_height,
8011 );
8012 if label_rect.width() > 0.0 {
8013 ctx.push_clip_rect(label_rect);
8014 paint_single_line_aligned_text(
8015 ctx,
8016 label_rect,
8017 label,
8018 &label_style,
8019 label_style.line_height,
8020 0.0,
8021 );
8022 ctx.pop_clip();
8023 }
8024 }
8025
8026 ctx.stroke(panel_shape, border, StrokeStyle::new(border_width));
8027
8028 Rect::new(
8029 rect.x() + style.content_padding.left,
8030 rect.y() + header_height + style.content_padding.top,
8031 (rect.width() - style.content_padding.left - style.content_padding.right).max(0.0),
8032 (rect.height() - header_height - style.content_padding.top - style.content_padding.bottom)
8033 .max(0.0),
8034 )
8035}
8036
8037#[derive(Clone, Copy, Debug, PartialEq)]
8038pub struct SectionPanelPaint {
8039 pub fill: Option<Color>,
8040 pub border: Option<Color>,
8041 pub title_color: Option<Color>,
8042 pub radius: Option<f32>,
8043 pub header_height: f32,
8044 pub content_padding: Insets,
8045 pub title_inset_x: f32,
8046 pub trailing_width: f32,
8047 pub title_token: Option<ThemeTextToken>,
8048 pub title_weight: FontWeight,
8049}
8050
8051#[derive(Clone, Copy, Debug, PartialEq)]
8052pub struct SectionPanelGeometry {
8053 pub panel_rect: Rect,
8054 pub header_rect: Rect,
8055 pub title_rect: Rect,
8056 pub content_rect: Rect,
8057}
8058
8059impl SectionPanelPaint {
8060 pub const fn new() -> Self {
8061 Self {
8062 fill: None,
8063 border: None,
8064 title_color: None,
8065 radius: None,
8066 header_height: 34.0,
8067 content_padding: Insets {
8068 left: 12.0,
8069 top: 0.0,
8070 right: 12.0,
8071 bottom: 8.0,
8072 },
8073 title_inset_x: 12.0,
8074 trailing_width: 0.0,
8075 title_token: None,
8076 title_weight: FontWeight::SEMIBOLD,
8077 }
8078 }
8079
8080 pub const fn fill(mut self, fill: Color) -> Self {
8081 self.fill = Some(fill);
8082 self
8083 }
8084
8085 pub const fn border(mut self, border: Color) -> Self {
8086 self.border = Some(border);
8087 self
8088 }
8089
8090 pub const fn title_color(mut self, title_color: Color) -> Self {
8091 self.title_color = Some(title_color);
8092 self
8093 }
8094
8095 pub const fn radius(mut self, radius: f32) -> Self {
8096 self.radius = Some(radius);
8097 self
8098 }
8099
8100 pub const fn header_height(mut self, header_height: f32) -> Self {
8101 self.header_height = header_height;
8102 self
8103 }
8104
8105 pub const fn content_padding(mut self, content_padding: Insets) -> Self {
8106 self.content_padding = content_padding;
8107 self
8108 }
8109
8110 pub const fn title_inset_x(mut self, title_inset_x: f32) -> Self {
8111 self.title_inset_x = title_inset_x;
8112 self
8113 }
8114
8115 pub const fn trailing_width(mut self, trailing_width: f32) -> Self {
8116 self.trailing_width = trailing_width;
8117 self
8118 }
8119
8120 pub const fn title_token(mut self, title_token: ThemeTextToken) -> Self {
8121 self.title_token = Some(title_token);
8122 self
8123 }
8124
8125 pub const fn title_weight(mut self, title_weight: FontWeight) -> Self {
8126 self.title_weight = title_weight;
8127 self
8128 }
8129}
8130
8131impl Default for SectionPanelPaint {
8132 fn default() -> Self {
8133 Self::new()
8134 }
8135}
8136
8137pub fn paint_section_panel(
8138 ctx: &mut PaintCtx,
8139 theme: &DefaultTheme,
8140 rect: Rect,
8141 title: &str,
8142 style: SectionPanelPaint,
8143) -> SectionPanelGeometry {
8144 if rect.width() <= 0.0 || rect.height() <= 0.0 {
8145 return SectionPanelGeometry {
8146 panel_rect: Rect::ZERO,
8147 header_rect: Rect::ZERO,
8148 title_rect: Rect::ZERO,
8149 content_rect: Rect::ZERO,
8150 };
8151 }
8152
8153 let fill = style.fill.unwrap_or(theme.surfaces.panel);
8154 let border = style.border.unwrap_or(theme.surfaces.border);
8155 let title_color = style.title_color.unwrap_or(theme.surfaces.text);
8156 let radius = style
8157 .radius
8158 .unwrap_or(theme.radius.lg)
8159 .min(rect.width().min(rect.height()) * 0.5)
8160 .max(0.0);
8161 let header_height = style.header_height.clamp(0.0, rect.height());
8162 let shape = rounded_rect_path(rect, radius);
8163 ctx.fill(shape.clone(), fill);
8164 ctx.stroke(
8165 shape,
8166 border,
8167 StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
8168 );
8169
8170 let header_rect = Rect::new(rect.x(), rect.y(), rect.width(), header_height);
8171 let mut title_style = text_token_style(
8172 theme,
8173 style.title_token.unwrap_or(theme.text.sm),
8174 title_color,
8175 );
8176 title_style.weight = style.title_weight;
8177 let title_x = rect.x() + style.title_inset_x.max(0.0);
8178 let title_rect = Rect::new(
8179 title_x,
8180 rect.y() + ((header_height - title_style.line_height) * 0.5).max(0.0),
8181 (rect.max_x() - title_x - style.title_inset_x.max(0.0) - style.trailing_width.max(0.0))
8182 .max(0.0),
8183 title_style.line_height,
8184 );
8185 if title_rect.width() > 0.0 && !title.is_empty() {
8186 ctx.push_clip_rect(title_rect);
8187 paint_single_line_aligned_text(
8188 ctx,
8189 title_rect,
8190 title,
8191 &title_style,
8192 title_style.line_height,
8193 0.0,
8194 );
8195 ctx.pop_clip();
8196 }
8197
8198 let content_rect = Rect::new(
8199 rect.x() + style.content_padding.left,
8200 rect.y() + header_height + style.content_padding.top,
8201 (rect.width() - style.content_padding.left - style.content_padding.right).max(0.0),
8202 (rect.height() - header_height - style.content_padding.top - style.content_padding.bottom)
8203 .max(0.0),
8204 );
8205
8206 SectionPanelGeometry {
8207 panel_rect: rect,
8208 header_rect,
8209 title_rect,
8210 content_rect,
8211 }
8212}
8213
8214impl Widget for StatusBadge {
8215 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8216 let theme = self.resolved_theme();
8217 let (height, icon_size, gap, padding) = self.metrics(&theme);
8218 let label = self.label();
8219 let tone = self.resolved_tone();
8220 let text = measure_text(ctx, &label, &self.text_style(&theme, &label, tone));
8221 let icon_w = self.icon.map(|_| icon_size + gap).unwrap_or(0.0);
8222 let natural_w = text.width.ceil() + icon_w + padding * 2.0;
8223 constraints.clamp(Size::new(
8224 self.min_width.unwrap_or(0.0).max(natural_w),
8225 height,
8226 ))
8227 }
8228
8229 fn paint(&self, ctx: &mut PaintCtx) {
8230 let theme = self.resolved_theme();
8231 let label = self.label();
8232 let tone = self.resolved_tone();
8233 paint_status_badge(ctx, ctx.bounds(), &theme, &label, self.icon, tone);
8234 }
8235
8236 fn semantics(&self, ctx: &mut SemanticsCtx) {
8237 let label = self.label();
8238 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8239 node.name = Some(label.clone());
8240 node.value = Some(SemanticsValue::Text(label));
8241 ctx.push(node);
8242 }
8243}
8244
8245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8246pub struct CoverageDotsConfig {
8247 pub current: usize,
8248 pub target: usize,
8249 pub tone: SemanticTone,
8250 pub max_dots: usize,
8251 pub show_label: bool,
8252}
8253
8254impl CoverageDotsConfig {
8255 pub fn new(current: usize, target: usize) -> Self {
8256 Self {
8257 current,
8258 target,
8259 tone: SemanticTone::Neutral,
8260 max_dots: 4,
8261 show_label: true,
8262 }
8263 }
8264
8265 fn normalized_target(self) -> usize {
8266 self.target.max(self.current)
8267 }
8268
8269 fn normalized_max_dots(self) -> usize {
8270 self.max_dots.max(1)
8271 }
8272
8273 fn label(self) -> String {
8274 format!("{}/{}", self.current, self.normalized_target())
8275 }
8276}
8277
8278pub fn paint_coverage_dots(
8279 ctx: &mut PaintCtx,
8280 theme: &DefaultTheme,
8281 rect: Rect,
8282 current: usize,
8283 target: usize,
8284 tone: SemanticTone,
8285) {
8286 let mut config = CoverageDotsConfig::new(current, target);
8287 config.tone = tone;
8288 paint_coverage_dots_with_config(ctx, theme, rect, config);
8289}
8290
8291pub fn paint_coverage_dots_with_config(
8292 ctx: &mut PaintCtx,
8293 theme: &DefaultTheme,
8294 rect: Rect,
8295 config: CoverageDotsConfig,
8296) {
8297 let target = config.normalized_target();
8298 if target == 0 || rect.width() <= 0.0 || rect.height() <= 0.0 {
8299 return;
8300 }
8301
8302 let (dot, gap, label_gap) = coverage_dot_metrics(theme);
8303 let shown = target.min(config.normalized_max_dots());
8304 let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
8305 let label = config.label();
8306 let label_width = if config.show_label {
8307 (label.len() as f32 * theme.text.xs.size * 0.56).min(34.0)
8308 } else {
8309 0.0
8310 };
8311 let total_width = dots_width
8312 + if config.show_label {
8313 label_gap + label_width
8314 } else {
8315 0.0
8316 };
8317 let mut x = rect.x() + ((rect.width() - total_width) * 0.5).max(0.0);
8318 let y = rect.y() + (rect.height() - dot) * 0.5;
8319 let (tone_color, _) = theme.semantic_tone_colors(config.tone);
8320 for index in 0..shown {
8321 let dot_rect = Rect::new(x, y, dot, dot);
8322 if index < config.current.min(shown) {
8323 ctx.fill(rounded_rect_path(dot_rect, dot * 0.5), tone_color);
8324 } else {
8325 ctx.stroke(
8326 rounded_rect_path(dot_rect, dot * 0.5),
8327 theme.palette.border,
8328 StrokeStyle::new(theme.metrics.border_width.max(1.0)),
8329 );
8330 }
8331 x += dot + gap;
8332 }
8333
8334 if config.show_label {
8335 let label_rect = Rect::new(
8336 x + (label_gap - gap).max(0.0),
8337 rect.y(),
8338 (rect.max_x() - x).max(0.0),
8339 rect.height(),
8340 );
8341 let text_style = numeric_text_style(text_token_style(
8342 theme,
8343 theme.text.xs,
8344 theme.palette.text_muted,
8345 ));
8346 ctx.push_clip_rect(label_rect);
8347 paint_aligned_text(
8348 ctx,
8349 label_rect,
8350 &label,
8351 &text_style,
8352 text_style.line_height,
8353 0.0,
8354 );
8355 ctx.pop_clip();
8356 }
8357}
8358
8359fn coverage_dot_metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
8360 let dot = (theme.text.xs.size * 0.42).clamp(4.0, 6.0);
8361 let gap = (dot * 0.65).clamp(2.0, 4.0);
8362 let label_gap = (theme.metrics.icon_label_gap * 0.7).max(4.0);
8363 (dot, gap, label_gap)
8364}
8365
8366pub struct CoverageDots {
8367 theme: Box<DefaultTheme>,
8368 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8369 name: String,
8370 config: CoverageDotsConfig,
8371 min_width: Option<f32>,
8372}
8373
8374impl CoverageDots {
8375 pub fn new(name: impl Into<String>, current: usize, target: usize) -> Self {
8376 Self {
8377 theme: Box::new(DefaultTheme::default()),
8378 theme_reader: None,
8379 name: name.into(),
8380 config: CoverageDotsConfig::new(current, target),
8381 min_width: None,
8382 }
8383 }
8384
8385 pub fn theme(mut self, theme: DefaultTheme) -> Self {
8386 self.theme = Box::new(theme);
8387 self.theme_reader = None;
8388 self
8389 }
8390
8391 pub fn theme_when<F>(mut self, theme: F) -> Self
8392 where
8393 F: Fn() -> DefaultTheme + 'static,
8394 {
8395 self.theme_reader = Some(Box::new(theme));
8396 self
8397 }
8398
8399 pub fn tone(mut self, tone: SemanticTone) -> Self {
8400 self.config.tone = tone;
8401 self
8402 }
8403
8404 pub fn max_dots(mut self, max_dots: usize) -> Self {
8405 self.config.max_dots = max_dots;
8406 self
8407 }
8408
8409 pub fn show_label(mut self, show_label: bool) -> Self {
8410 self.config.show_label = show_label;
8411 self
8412 }
8413
8414 pub fn min_width(mut self, min_width: f32) -> Self {
8415 self.min_width = Some(min_width.max(0.0));
8416 self
8417 }
8418
8419 fn resolved_theme(&self) -> DefaultTheme {
8420 self.theme_reader
8421 .as_ref()
8422 .map(|theme| theme())
8423 .unwrap_or(*self.theme)
8424 }
8425}
8426
8427impl Widget for CoverageDots {
8428 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8429 let theme = self.resolved_theme();
8430 let target = self.config.normalized_target();
8431 if target == 0 {
8432 return constraints.clamp(Size::ZERO);
8433 }
8434 let (dot, gap, label_gap) = coverage_dot_metrics(&theme);
8435 let shown = target.min(self.config.normalized_max_dots());
8436 let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
8437 let label_width = if self.config.show_label {
8438 measure_text(
8439 ctx,
8440 &self.config.label(),
8441 &numeric_text_style(text_token_style(
8442 &theme,
8443 theme.text.xs,
8444 theme.palette.text_muted,
8445 )),
8446 )
8447 .width
8448 + label_gap
8449 } else {
8450 0.0
8451 };
8452 constraints.clamp(Size::new(
8453 self.min_width.unwrap_or(0.0).max(dots_width + label_width),
8454 theme
8455 .text
8456 .xs
8457 .line_height
8458 .max(dot + 2.0)
8459 .max(theme.metrics.min_height * 0.55),
8460 ))
8461 }
8462
8463 fn paint(&self, ctx: &mut PaintCtx) {
8464 paint_coverage_dots_with_config(ctx, &self.resolved_theme(), ctx.bounds(), self.config);
8465 }
8466
8467 fn semantics(&self, ctx: &mut SemanticsCtx) {
8468 let target = self.config.normalized_target();
8469 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8470 node.name = Some(self.name.clone());
8471 node.value = Some(SemanticsValue::Text(self.config.label()));
8472 node.description = Some(format!(
8473 "{} of {} covered",
8474 self.config.current.min(target),
8475 target
8476 ));
8477 ctx.push(node);
8478 }
8479}
8480
8481pub struct PlacementBadge {
8482 theme: Box<DefaultTheme>,
8483 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8484 label: String,
8485 label_reader: Option<Box<dyn Fn() -> String>>,
8486 icon: Option<IconGlyph>,
8487 tone: SemanticTone,
8488 tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
8489 coverage: Option<(usize, usize)>,
8490 coverage_reader: Option<Box<dyn Fn() -> Option<(usize, usize)>>>,
8491 min_width: Option<f32>,
8492}
8493
8494impl PlacementBadge {
8495 pub fn new(label: impl Into<String>) -> Self {
8496 Self {
8497 theme: Box::new(DefaultTheme::default()),
8498 theme_reader: None,
8499 label: label.into(),
8500 label_reader: None,
8501 icon: None,
8502 tone: SemanticTone::Neutral,
8503 tone_reader: None,
8504 coverage: None,
8505 coverage_reader: None,
8506 min_width: None,
8507 }
8508 }
8509
8510 pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
8511 where
8512 F: Fn() -> String + 'static,
8513 {
8514 let mut badge = Self::new(fallback);
8515 badge.label_reader = Some(Box::new(reader));
8516 badge
8517 }
8518
8519 pub fn theme(mut self, theme: DefaultTheme) -> Self {
8520 self.theme = Box::new(theme);
8521 self.theme_reader = None;
8522 self
8523 }
8524
8525 pub fn theme_when<F>(mut self, theme: F) -> Self
8526 where
8527 F: Fn() -> DefaultTheme + 'static,
8528 {
8529 self.theme_reader = Some(Box::new(theme));
8530 self
8531 }
8532
8533 pub fn icon(mut self, icon: IconGlyph) -> Self {
8534 self.icon = Some(icon);
8535 self
8536 }
8537
8538 pub fn tone(mut self, tone: SemanticTone) -> Self {
8539 self.tone = tone;
8540 self.tone_reader = None;
8541 self
8542 }
8543
8544 pub fn tone_when<F>(mut self, tone: F) -> Self
8545 where
8546 F: Fn() -> SemanticTone + 'static,
8547 {
8548 self.tone_reader = Some(Box::new(tone));
8549 self
8550 }
8551
8552 pub fn coverage(mut self, current: usize, target: usize) -> Self {
8553 self.coverage = Some((current, target));
8554 self.coverage_reader = None;
8555 self
8556 }
8557
8558 pub fn coverage_when<F>(mut self, coverage: F) -> Self
8559 where
8560 F: Fn() -> Option<(usize, usize)> + 'static,
8561 {
8562 self.coverage_reader = Some(Box::new(coverage));
8563 self
8564 }
8565
8566 pub fn min_width(mut self, min_width: f32) -> Self {
8567 self.min_width = Some(min_width.max(0.0));
8568 self
8569 }
8570
8571 fn resolved_theme(&self) -> DefaultTheme {
8572 self.theme_reader
8573 .as_ref()
8574 .map(|theme| theme())
8575 .unwrap_or(*self.theme)
8576 }
8577
8578 fn label(&self) -> String {
8579 self.label_reader
8580 .as_ref()
8581 .map(|reader| reader())
8582 .unwrap_or_else(|| self.label.clone())
8583 }
8584
8585 fn resolved_tone(&self) -> SemanticTone {
8586 self.tone_reader
8587 .as_ref()
8588 .map(|reader| reader())
8589 .unwrap_or(self.tone)
8590 }
8591
8592 fn resolved_coverage(&self) -> Option<(usize, usize)> {
8593 self.coverage_reader
8594 .as_ref()
8595 .map(|reader| reader())
8596 .unwrap_or(self.coverage)
8597 .filter(|(_, target)| *target > 0)
8598 }
8599
8600 fn metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
8601 let height = (theme.metrics.min_height - 2.0).max(22.0);
8602 let coverage_width = 50.0;
8603 let gap = theme.metrics.icon_label_gap.max(6.0);
8604 (height, coverage_width, gap)
8605 }
8606}
8607
8608#[derive(Clone, Copy, Debug, PartialEq)]
8609pub struct PlacementBadgePaint {
8610 pub padding: Insets,
8611}
8612
8613impl PlacementBadgePaint {
8614 pub const fn new() -> Self {
8615 Self {
8616 padding: Insets::ZERO,
8617 }
8618 }
8619
8620 pub const fn padding(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self {
8621 self.padding = Insets {
8622 left,
8623 top,
8624 right,
8625 bottom,
8626 };
8627 self
8628 }
8629
8630 fn content_rect(self, rect: Rect) -> Rect {
8631 Rect::new(
8632 rect.x() + self.padding.left,
8633 rect.y() + self.padding.top,
8634 (rect.width() - self.padding.left - self.padding.right).max(0.0),
8635 (rect.height() - self.padding.top - self.padding.bottom).max(0.0),
8636 )
8637 }
8638}
8639
8640impl Default for PlacementBadgePaint {
8641 fn default() -> Self {
8642 Self::new()
8643 }
8644}
8645
8646pub fn paint_placement_badge(
8647 ctx: &mut PaintCtx,
8648 theme: &DefaultTheme,
8649 rect: Rect,
8650 label: &str,
8651 icon: Option<IconGlyph>,
8652 tone: SemanticTone,
8653 coverage: Option<(usize, usize)>,
8654) {
8655 paint_placement_badge_with(
8656 ctx,
8657 theme,
8658 rect,
8659 label,
8660 icon,
8661 tone,
8662 coverage,
8663 PlacementBadgePaint::new(),
8664 );
8665}
8666
8667pub fn paint_placement_badge_with(
8668 ctx: &mut PaintCtx,
8669 theme: &DefaultTheme,
8670 rect: Rect,
8671 label: &str,
8672 icon: Option<IconGlyph>,
8673 tone: SemanticTone,
8674 coverage: Option<(usize, usize)>,
8675 paint: PlacementBadgePaint,
8676) {
8677 let rect = paint.content_rect(rect);
8678 if rect.width() <= 0.0 || rect.height() <= 0.0 {
8679 return;
8680 }
8681
8682 let (_, coverage_width, gap) = PlacementBadge::metrics(theme);
8683 let show_coverage = coverage.is_some() && rect.width() >= 118.0;
8684 let coverage_slot = if show_coverage { coverage_width } else { 0.0 };
8685 let slot_gap = if show_coverage { gap } else { 0.0 };
8686 let badge_rect = Rect::new(
8687 rect.x(),
8688 rect.y(),
8689 (rect.width() - coverage_slot - slot_gap).clamp(48.0, 86.0),
8690 rect.height(),
8691 );
8692 paint_status_badge(ctx, badge_rect, theme, label, icon, tone);
8693
8694 if show_coverage && let Some((current, target)) = coverage {
8695 let dots_rect = Rect::new(
8696 badge_rect.max_x() + slot_gap,
8697 rect.y(),
8698 (rect.max_x() - badge_rect.max_x() - slot_gap).max(0.0),
8699 rect.height(),
8700 );
8701 paint_coverage_dots(ctx, theme, dots_rect, current, target, tone);
8702 }
8703}
8704
8705impl Widget for PlacementBadge {
8706 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8707 let theme = self.resolved_theme();
8708 let (height, coverage_width, gap) = Self::metrics(&theme);
8709 let label = self.label();
8710 let tone = self.resolved_tone();
8711 let icon_w = self
8712 .icon
8713 .map(|_| (height - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0))
8714 .unwrap_or(0.0);
8715 let text = measure_text(
8716 ctx,
8717 &label,
8718 &StatusBadge::new(&label).text_style(&theme, &label, tone),
8719 );
8720 let badge_width =
8721 (text.width.ceil() + icon_w + theme.metrics.button_padding.left.max(8.0) * 2.0)
8722 .clamp(48.0, 86.0);
8723 let coverage_width = if self.resolved_coverage().is_some() {
8724 coverage_width + gap
8725 } else {
8726 0.0
8727 };
8728 constraints.clamp(Size::new(
8729 self.min_width
8730 .unwrap_or(0.0)
8731 .max(badge_width + coverage_width),
8732 height,
8733 ))
8734 }
8735
8736 fn paint(&self, ctx: &mut PaintCtx) {
8737 let theme = self.resolved_theme();
8738 paint_placement_badge(
8739 ctx,
8740 &theme,
8741 ctx.bounds(),
8742 &self.label(),
8743 self.icon,
8744 self.resolved_tone(),
8745 self.resolved_coverage(),
8746 );
8747 }
8748
8749 fn semantics(&self, ctx: &mut SemanticsCtx) {
8750 let label = self.label();
8751 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8752 node.name = Some(label.clone());
8753 node.value = Some(SemanticsValue::Text(label.clone()));
8754 if let Some((current, target)) = self.resolved_coverage() {
8755 let target = target.max(current);
8756 node.description = Some(format!("{current} of {target} replicas available"));
8757 }
8758 ctx.push(node);
8759 }
8760}
8761
8762pub struct TabBar {
8763 theme: Box<DefaultTheme>,
8764 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8765 name: String,
8766 tabs: Vec<String>,
8767 selected: usize,
8768 selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
8769 selected_source: Option<Arc<dyn Observable<Option<usize>>>>,
8770 selection_from: usize,
8771 selection_animation: AnimatedScalar,
8772 hovered: Option<usize>,
8773 hover_visual: Option<usize>,
8774 pressed: Option<usize>,
8775 press_visual: Option<usize>,
8776 hover_animation: AnimatedScalar,
8777 press_animation: AnimatedScalar,
8778 focus_animation: AnimatedScalar,
8779 gap: Option<f32>,
8780 label_measurements: Vec<TextMeasurement>,
8781 widths: Vec<f32>,
8782 on_change: Option<Box<dyn FnMut(usize, String)>>,
8783}
8784
8785impl TabBar {
8786 pub fn new(name: impl Into<String>) -> Self {
8787 Self {
8788 theme: Box::new(DefaultTheme::default()),
8789 theme_reader: None,
8790 name: name.into(),
8791 tabs: Vec::new(),
8792 selected: 0,
8793 selected_reader: None,
8794 selected_source: None,
8795 selection_from: 0,
8796 selection_animation: AnimatedScalar::new(1.0),
8797 hovered: None,
8798 hover_visual: None,
8799 pressed: None,
8800 press_visual: None,
8801 hover_animation: AnimatedScalar::new(0.0),
8802 press_animation: AnimatedScalar::new(0.0),
8803 focus_animation: AnimatedScalar::new(0.0),
8804 gap: None,
8805 label_measurements: Vec::new(),
8806 widths: Vec::new(),
8807 on_change: None,
8808 }
8809 }
8810
8811 pub fn theme(mut self, theme: DefaultTheme) -> Self {
8812 self.theme = Box::new(theme);
8813 self.theme_reader = None;
8814 self
8815 }
8816
8817 pub fn theme_when<F>(mut self, theme: F) -> Self
8818 where
8819 F: Fn() -> DefaultTheme + 'static,
8820 {
8821 self.theme_reader = Some(Box::new(theme));
8822 self
8823 }
8824
8825 pub fn tab(mut self, label: impl Into<String>) -> Self {
8826 self.tabs.push(label.into());
8827 self
8828 }
8829
8830 pub fn tabs<I, S>(mut self, labels: I) -> Self
8831 where
8832 I: IntoIterator<Item = S>,
8833 S: Into<String>,
8834 {
8835 self.tabs.extend(labels.into_iter().map(Into::into));
8836 self
8837 }
8838
8839 pub fn selected(mut self, index: usize) -> Self {
8840 self.selected = index;
8841 self.selected_reader = None;
8842 self.selected_source = None;
8843 self.selection_from = index;
8844 self.selection_animation = AnimatedScalar::new(1.0);
8845 self
8846 }
8847
8848 pub fn selected_when<F>(mut self, selected: F) -> Self
8849 where
8850 F: Fn() -> Option<usize> + 'static,
8851 {
8852 if let Some(index) = selected() {
8853 self.selected = index;
8854 self.selection_from = index;
8855 }
8856 self.selected_reader = Some(Box::new(selected));
8857 self.selected_source = None;
8858 self
8859 }
8860
8861 pub fn selected_from<O>(mut self, selected: O) -> Self
8864 where
8865 O: Observable<Option<usize>> + 'static,
8866 {
8867 if let Some(index) = selected.get() {
8868 self.selected = index;
8869 self.selection_from = index;
8870 }
8871 self.selected_reader = None;
8872 self.selected_source = Some(Arc::new(selected));
8873 self
8874 }
8875
8876 pub fn gap(mut self, gap: f32) -> Self {
8877 self.gap = Some(gap.max(0.0));
8878 self
8879 }
8880
8881 pub fn on_change<F>(mut self, on_change: F) -> Self
8882 where
8883 F: FnMut(usize, String) + 'static,
8884 {
8885 self.on_change = Some(Box::new(on_change));
8886 self
8887 }
8888
8889 pub fn selected_index(&self) -> usize {
8890 self.normalized_selected()
8891 }
8892
8893 pub fn current_tab(&self) -> Option<&str> {
8894 self.tabs
8895 .get(self.normalized_selected())
8896 .map(String::as_str)
8897 }
8898
8899 fn normalized_selected(&self) -> usize {
8900 let selected = self
8901 .selected_source
8902 .as_ref()
8903 .and_then(|source| source.get())
8904 .or_else(|| self.selected_reader.as_ref().and_then(|reader| reader()))
8905 .unwrap_or(self.selected);
8906 if self.tabs.is_empty() {
8907 0
8908 } else {
8909 selected.min(self.tabs.len() - 1)
8910 }
8911 }
8912
8913 fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
8914 if self.tabs.is_empty() {
8915 return;
8916 }
8917
8918 let index = index.min(self.tabs.len() - 1);
8919 let selected = self.normalized_selected();
8920 if selected != index {
8921 self.selected = index;
8922 if let Some(on_change) = &mut self.on_change {
8923 on_change(index, self.tabs[index].clone());
8924 }
8925 let target = self.normalized_selected();
8926 self.selected = target;
8927 self.start_selection_animation(selected, target, ctx);
8928 }
8929 }
8930
8931 fn start_selection_animation(&mut self, from: usize, to: usize, ctx: &mut EventCtx) {
8932 if self.tabs.is_empty() || from == to {
8933 self.selection_from = to;
8934 self.selection_animation = AnimatedScalar::new(1.0);
8935 return;
8936 }
8937
8938 let theme = self.resolved_theme();
8939 self.selection_from = from.min(self.tabs.len() - 1);
8940 self.selection_animation = AnimatedScalar::new(0.0);
8941 self.selection_animation.set_target_event(
8942 1.0,
8943 theme.motion.tab_switch_duration(),
8944 theme.motion.tab_switch_easing(),
8945 ctx,
8946 );
8947 ctx.request_paint();
8948 ctx.request_semantics();
8949 }
8950
8951 fn sync_external_selected(&mut self, ctx: &mut EventCtx) {
8952 if (self.selected_reader.is_none() && self.selected_source.is_none())
8953 || self.tabs.is_empty()
8954 {
8955 return;
8956 }
8957
8958 if let Some(source) = &self.selected_source {
8959 let _ = ctx.observe(source.as_ref(), InvalidationKind::Paint);
8960 let _ = ctx.observe(source.as_ref(), InvalidationKind::Semantics);
8961 }
8962
8963 let previous = self.selected.min(self.tabs.len() - 1);
8964 let selected = self.normalized_selected();
8965 if previous != selected {
8966 self.selected = selected;
8967 self.start_selection_animation(previous, selected, ctx);
8968 }
8969 }
8970
8971 fn tab_height(&self) -> f32 {
8972 self.resolved_theme().metrics.tab_height
8973 }
8974
8975 fn resolved_gap(&self) -> f32 {
8976 self.gap
8977 .unwrap_or(self.resolved_theme().metrics.tab_gap)
8978 .max(0.0)
8979 }
8980
8981 fn measured_widths(&self) -> &[f32] {
8982 &self.widths
8983 }
8984
8985 fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
8986 if index >= self.tabs.len() || self.measured_widths().len() != self.tabs.len() {
8987 return None;
8988 }
8989
8990 let gap = self.resolved_gap();
8991 let base_total =
8992 self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
8993 let extra_per_tab = if bounds.width() > base_total && !self.tabs.is_empty() {
8994 (bounds.width() - base_total) / self.tabs.len() as f32
8995 } else {
8996 0.0
8997 };
8998
8999 let tab_height = self.tab_height().min(bounds.height()).max(0.0);
9000 let tab_y = bounds.y() + ((bounds.height() - tab_height) * 0.5).max(0.0);
9001 let mut x = bounds.x();
9002 for (current, width) in self.widths.iter().enumerate() {
9003 let width = *width + extra_per_tab;
9004 let rect = Rect::new(x, tab_y, width, tab_height);
9005 if current == index {
9006 return Some(rect);
9007 }
9008 x += width + gap;
9009 }
9010
9011 None
9012 }
9013
9014 fn tab_at(&self, bounds: Rect, position: Point) -> Option<usize> {
9015 self.tabs.iter().enumerate().find_map(|(index, _)| {
9016 self.tab_rect(bounds, index)
9017 .filter(|rect| rect.contains(position))
9018 .map(|_| index)
9019 })
9020 }
9021
9022 fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
9023 if self.tabs.is_empty() {
9024 return;
9025 }
9026
9027 let selected = self.normalized_selected() as isize;
9028 let last = self.tabs.len() as isize - 1;
9029 let next = (selected + delta).clamp(0, last) as usize;
9030 self.activate(next, ctx);
9031 self.set_hovered(Some(next), ctx);
9032 }
9033
9034 fn advance_animations(&mut self, time: f64) -> bool {
9035 let selection_animating = self.selection_animation.advance(time);
9036 let hover_animating = self.hover_animation.advance(time);
9037 if !hover_animating
9038 && self.hovered.is_none()
9039 && self.hover_animation.value <= AnimatedScalar::EPSILON
9040 {
9041 self.hover_visual = None;
9042 }
9043 let press_animating = self.press_animation.advance(time);
9044 if !press_animating
9045 && self.pressed.is_none()
9046 && self.press_animation.value <= AnimatedScalar::EPSILON
9047 {
9048 self.press_visual = None;
9049 }
9050 let focus_animating = self.focus_animation.advance(time);
9051 selection_animating | hover_animating | press_animating | focus_animating
9052 }
9053
9054 fn resolved_theme(&self) -> DefaultTheme {
9055 self.theme_reader
9056 .as_ref()
9057 .map(|theme| theme())
9058 .unwrap_or(*self.theme)
9059 }
9060
9061 fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
9062 if self.hovered == hovered {
9063 return;
9064 }
9065 let theme = self.resolved_theme();
9066 self.hovered = hovered;
9067 if let Some(index) = hovered {
9068 self.hover_visual = Some(index);
9069 self.hover_animation = AnimatedScalar::new(0.0);
9070 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
9071 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
9072 self.hover_visual = None;
9073 }
9074 ctx.request_paint();
9075 ctx.request_semantics();
9076 }
9077
9078 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
9079 if self.pressed == pressed {
9080 return;
9081 }
9082 let theme = self.resolved_theme();
9083 self.pressed = pressed;
9084 if let Some(index) = pressed {
9085 self.press_visual = Some(index);
9086 self.press_animation = AnimatedScalar::new(0.0);
9087 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
9088 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
9089 self.press_visual = None;
9090 }
9091 ctx.request_paint();
9092 ctx.request_semantics();
9093 }
9094
9095 fn hover_amount_for(&self, index: usize) -> f32 {
9096 if self.hover_visual == Some(index) {
9097 self.hover_animation.value
9098 } else {
9099 0.0
9100 }
9101 }
9102
9103 fn press_amount_for(&self, index: usize) -> f32 {
9104 if self.press_visual == Some(index) {
9105 self.press_animation.value
9106 } else {
9107 0.0
9108 }
9109 }
9110}
9111
9112impl Widget for TabBar {
9113 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
9114 self.sync_external_selected(ctx);
9115 match event {
9116 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
9117 self.set_hovered(self.tab_at(ctx.bounds(), pointer.position), ctx);
9118 }
9119 Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
9120 self.set_hovered(None, ctx);
9121 }
9122 Event::Pointer(pointer)
9123 if pointer.kind == PointerEventKind::Down
9124 && pointer.button == Some(PointerButton::Primary) =>
9125 {
9126 let hovered = self.tab_at(ctx.bounds(), pointer.position);
9127 self.set_hovered(hovered, ctx);
9128 self.set_pressed(hovered, ctx);
9129 ctx.request_focus();
9130 ctx.request_pointer_capture(pointer.pointer_id);
9131 ctx.set_handled();
9132 }
9133 Event::Pointer(pointer)
9134 if pointer.kind == PointerEventKind::Up
9135 && pointer.button == Some(PointerButton::Primary) =>
9136 {
9137 let hovered = self.tab_at(ctx.bounds(), pointer.position);
9138 if let Some(index) = self
9139 .pressed
9140 .zip(hovered)
9141 .filter(|(left, right)| left == right)
9142 .map(|(index, _)| index)
9143 {
9144 self.activate(index, ctx);
9145 }
9146 self.set_hovered(hovered, ctx);
9147 self.set_pressed(None, ctx);
9148 ctx.release_pointer_capture(pointer.pointer_id);
9149 ctx.set_handled();
9150 }
9151 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
9152 if self.pressed.is_some() {
9153 self.set_pressed(None, ctx);
9154 self.set_hovered(None, ctx);
9155 ctx.release_pointer_capture(pointer.pointer_id);
9156 ctx.set_handled();
9157 }
9158 }
9159 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
9160 match key.key.as_str() {
9161 "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
9162 "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
9163 "Home" => self.activate(0, ctx),
9164 "End" if !self.tabs.is_empty() => self.activate(self.tabs.len() - 1, ctx),
9165 _ => return,
9166 }
9167 ctx.request_paint();
9168 ctx.request_semantics();
9169 ctx.set_handled();
9170 }
9171 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
9172 if self.advance_animations(*time) {
9173 ctx.request_animation_frame();
9174 }
9175 ctx.request_paint();
9176 }
9177 _ => {}
9178 }
9179 }
9180
9181 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
9182 if command.is(REACTIVE_CHANGED) && self.selected_source.is_some() {
9183 self.sync_external_selected(ctx);
9184 ctx.set_handled();
9185 }
9186 }
9187
9188 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
9189 if let Some(source) = &self.selected_source {
9190 let selected = ctx.observe_with(source.as_ref(), InvalidationKind::Paint);
9191 let _ = ctx.observe_with(source.as_ref(), InvalidationKind::Semantics);
9192 if let Some(selected) = selected {
9193 self.selected = selected;
9194 }
9195 }
9196 let theme = self.resolved_theme();
9197 let style = theme.text_style(theme.palette.text);
9198 let padding = theme.metrics.tab_padding;
9199 self.label_measurements = self
9200 .tabs
9201 .iter()
9202 .map(|tab| measure_text(ctx, tab, &style))
9203 .collect();
9204 self.widths = self
9205 .label_measurements
9206 .iter()
9207 .map(|measurement| {
9208 (measurement.width + padding.left + padding.right).max(theme.metrics.tab_min_width)
9209 })
9210 .collect();
9211
9212 let gap = self.resolved_gap();
9213 let width =
9214 self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
9215 constraints.clamp(Size::new(width.max(160.0), self.tab_height()))
9216 }
9217
9218 fn paint(&self, ctx: &mut PaintCtx) {
9219 let theme = self.resolved_theme();
9220 let palette = theme.palette;
9221 let metrics = theme.metrics;
9222 let interaction = theme.interaction;
9223 let tab_padding = metrics.tab_padding;
9224 let label_style = theme.text_style(palette.text_muted);
9225 let selected_label_style = theme.text_style(palette.text);
9226
9227 ctx.fill_rect(ctx.bounds(), palette.control);
9230 let divider_height = physical_pixels(ctx, metrics.border_width);
9231 ctx.fill_rect(
9232 Rect::new(
9233 ctx.bounds().x(),
9234 ctx.bounds().max_y() - divider_height,
9235 ctx.bounds().width(),
9236 divider_height,
9237 ),
9238 palette.border.with_alpha(0.72),
9239 );
9240
9241 let focus_progress = self.focus_animation.value;
9242 for (index, tab) in self.tabs.iter().enumerate() {
9243 let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9244 continue;
9245 };
9246 let selected = self.normalized_selected() == index;
9247 let hovered = self.hovered == Some(index);
9248 let pressed = self.pressed == Some(index);
9249 let hover_amount = self.hover_amount_for(index);
9250 let press_amount = self.press_amount_for(index);
9251
9252 if (hovered
9255 || pressed
9256 || hover_amount > AnimatedScalar::EPSILON
9257 || press_amount > AnimatedScalar::EPSILON)
9258 && let Some((background, border)) =
9259 tab_state_visuals(&theme, false, hovered, pressed, hover_amount, press_amount)
9260 {
9261 draw_control_shape(
9262 ctx,
9263 rect,
9264 metrics.corner_radius,
9265 physical_pixels(ctx, metrics.border_width),
9266 background,
9267 border,
9268 );
9269 }
9270
9271 if selected && focus_progress > AnimatedScalar::EPSILON {
9272 draw_focus_ring_frame(
9273 ctx,
9274 rect,
9275 metrics.corner_radius,
9276 metrics,
9277 palette
9278 .focus_ring
9279 .with_alpha(palette.focus_ring.alpha * focus_progress),
9280 );
9281 }
9282
9283 let text_style = if selected {
9284 selected_label_style.clone()
9285 } else {
9286 label_style.clone()
9287 };
9288 let text_slot = inset_rect(rect, tab_padding);
9289 let pressed_offset = press_amount * interaction.pressed_offset;
9290 ctx.push_clip_rect(text_slot);
9291 paint_aligned_text(
9292 ctx,
9293 text_slot.translate(Vector::new(0.0, pressed_offset)),
9294 tab,
9295 &text_style,
9296 text_style.line_height,
9297 0.5,
9298 );
9299 ctx.pop_clip();
9300 }
9301
9302 if let Some(accent) = tab_indicator_rect(
9303 |index| self.tab_rect(ctx.bounds(), index),
9304 self.selection_from,
9305 self.normalized_selected(),
9306 self.selection_animation.value,
9307 tab_padding,
9308 interaction.active_indicator_thickness,
9309 ) {
9310 ctx.fill(
9311 rounded_rect_path(accent, accent.height() * 0.5),
9312 palette.accent,
9313 );
9314 }
9315 }
9316
9317 fn semantics(&self, ctx: &mut SemanticsCtx) {
9318 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TabBar, ctx.bounds());
9319 node.name = Some(self.name.clone());
9320 node.value = self
9321 .current_tab()
9322 .map(|value| SemanticsValue::Text(value.to_string()));
9323 node.state.focused = ctx.is_focused();
9324 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
9325 ctx.push(node);
9326 }
9327
9328 fn accepts_focus(&self) -> bool {
9329 true
9330 }
9331
9332 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
9333 let theme = self.resolved_theme();
9334 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
9335 ctx.request_paint();
9336 ctx.request_semantics();
9337 }
9338}
9339
9340#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9341enum BrowserTabHit {
9342 Tab(usize),
9343 Close(usize),
9344}
9345
9346impl BrowserTabHit {
9347 fn index(self) -> usize {
9348 match self {
9349 Self::Tab(index) | Self::Close(index) => index,
9350 }
9351 }
9352}
9353
9354type BrowserTabBarChange = Box<dyn FnMut(usize, String)>;
9355type BrowserTabBarContextChange = Box<dyn FnMut(usize, String, &mut EventCtx)>;
9356
9357pub struct BrowserTabBar {
9358 theme: Box<DefaultTheme>,
9359 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
9360 name: String,
9361 tabs: Vec<String>,
9362 tabs_reader: Option<Box<dyn Fn() -> Vec<String>>>,
9363 selected: Option<usize>,
9364 selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
9365 selection_from: Option<usize>,
9366 selection_to: Option<usize>,
9367 selection_animation: AnimatedScalar,
9368 hovered: Option<BrowserTabHit>,
9369 hover_visual: Option<BrowserTabHit>,
9370 pressed: Option<BrowserTabHit>,
9371 press_visual: Option<BrowserTabHit>,
9372 hover_animation: AnimatedScalar,
9373 press_animation: AnimatedScalar,
9374 focus_animation: AnimatedScalar,
9375 label_measurements: Vec<TextMeasurement>,
9376 widths: Vec<f32>,
9377 on_change: Option<BrowserTabBarChange>,
9378 on_change_with_ctx: Option<BrowserTabBarContextChange>,
9379 on_close: Option<BrowserTabBarChange>,
9380 on_close_with_ctx: Option<BrowserTabBarContextChange>,
9381}
9382
9383impl BrowserTabBar {
9384 pub fn new(name: impl Into<String>) -> Self {
9385 Self {
9386 theme: Box::new(DefaultTheme::default()),
9387 theme_reader: None,
9388 name: name.into(),
9389 tabs: Vec::new(),
9390 tabs_reader: None,
9391 selected: None,
9392 selected_reader: None,
9393 selection_from: None,
9394 selection_to: None,
9395 selection_animation: AnimatedScalar::new(1.0),
9396 hovered: None,
9397 hover_visual: None,
9398 pressed: None,
9399 press_visual: None,
9400 hover_animation: AnimatedScalar::new(0.0),
9401 press_animation: AnimatedScalar::new(0.0),
9402 focus_animation: AnimatedScalar::new(0.0),
9403 label_measurements: Vec::new(),
9404 widths: Vec::new(),
9405 on_change: None,
9406 on_change_with_ctx: None,
9407 on_close: None,
9408 on_close_with_ctx: None,
9409 }
9410 }
9411
9412 pub fn theme(mut self, theme: DefaultTheme) -> Self {
9413 self.theme = Box::new(theme);
9414 self.theme_reader = None;
9415 self
9416 }
9417
9418 pub fn theme_when<F>(mut self, theme: F) -> Self
9419 where
9420 F: Fn() -> DefaultTheme + 'static,
9421 {
9422 self.theme_reader = Some(Box::new(theme));
9423 self
9424 }
9425
9426 pub fn tabs<I, S>(mut self, labels: I) -> Self
9427 where
9428 I: IntoIterator<Item = S>,
9429 S: Into<String>,
9430 {
9431 self.tabs.extend(labels.into_iter().map(Into::into));
9432 self
9433 }
9434
9435 pub fn tabs_when<F>(mut self, tabs: F) -> Self
9436 where
9437 F: Fn() -> Vec<String> + 'static,
9438 {
9439 self.tabs_reader = Some(Box::new(tabs));
9440 self
9441 }
9442
9443 pub fn selected(mut self, index: Option<usize>) -> Self {
9444 self.selected = index;
9445 self.selection_from = index;
9446 self.selection_to = index;
9447 self.selection_animation = AnimatedScalar::new(1.0);
9448 self
9449 }
9450
9451 pub fn selected_when<F>(mut self, selected: F) -> Self
9452 where
9453 F: Fn() -> Option<usize> + 'static,
9454 {
9455 self.selected_reader = Some(Box::new(selected));
9456 self
9457 }
9458
9459 pub fn on_change<F>(mut self, on_change: F) -> Self
9460 where
9461 F: FnMut(usize, String) + 'static,
9462 {
9463 self.on_change = Some(Box::new(on_change));
9464 self
9465 }
9466
9467 pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
9468 where
9469 F: FnMut(usize, String, &mut EventCtx) + 'static,
9470 {
9471 self.on_change_with_ctx = Some(Box::new(on_change));
9472 self
9473 }
9474
9475 pub fn on_close<F>(mut self, on_close: F) -> Self
9476 where
9477 F: FnMut(usize, String) + 'static,
9478 {
9479 self.on_close = Some(Box::new(on_close));
9480 self
9481 }
9482
9483 pub fn on_close_with_ctx<F>(mut self, on_close: F) -> Self
9484 where
9485 F: FnMut(usize, String, &mut EventCtx) + 'static,
9486 {
9487 self.on_close_with_ctx = Some(Box::new(on_close));
9488 self
9489 }
9490
9491 pub fn selected_index(&self) -> Option<usize> {
9492 self.normalized_selected()
9493 }
9494
9495 fn refresh_tabs(&mut self) {
9496 if let Some(reader) = &self.tabs_reader {
9497 self.tabs = reader();
9498 }
9499 self.selected = self.resolved_selected_raw();
9500 let selected = self.normalized_selected();
9501 if self.selection_animation.value >= 1.0 - AnimatedScalar::EPSILON
9502 && self.selection_to != selected
9503 {
9504 self.selection_from = selected;
9505 self.selection_to = selected;
9506 self.selection_animation = AnimatedScalar::new(1.0);
9507 }
9508 }
9509
9510 fn resolved_selected_raw(&self) -> Option<usize> {
9511 self.selected_reader
9512 .as_ref()
9513 .map(|reader| reader())
9514 .unwrap_or(self.selected)
9515 }
9516
9517 fn normalized_selected(&self) -> Option<usize> {
9518 let selected = self.resolved_selected_raw()?;
9519 (selected < self.tabs.len()).then_some(selected)
9520 }
9521
9522 fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
9523 self.refresh_tabs();
9524 if index >= self.tabs.len() {
9525 return;
9526 }
9527 let from = self.normalized_selected();
9528 if from == Some(index) {
9529 return;
9530 }
9531 let label = self.tabs[index].clone();
9532 self.selected = Some(index);
9533 if let Some(on_change) = &mut self.on_change {
9534 on_change(index, label.clone());
9535 }
9536 if let Some(on_change) = &mut self.on_change_with_ctx {
9537 on_change(index, label, ctx);
9538 }
9539 self.refresh_tabs();
9540 self.start_selection_animation(from, self.normalized_selected(), ctx);
9541 }
9542
9543 fn close(&mut self, index: usize, ctx: &mut EventCtx) {
9544 self.refresh_tabs();
9545 if index >= self.tabs.len() {
9546 return;
9547 }
9548 let from = self.normalized_selected();
9549 let label = self.tabs[index].clone();
9550 if let Some(on_close) = &mut self.on_close {
9551 on_close(index, label.clone());
9552 }
9553 if let Some(on_close) = &mut self.on_close_with_ctx {
9554 on_close(index, label, ctx);
9555 }
9556 self.refresh_tabs();
9557 self.start_selection_animation(from, self.normalized_selected(), ctx);
9558 }
9559
9560 fn start_selection_animation(
9561 &mut self,
9562 from: Option<usize>,
9563 to: Option<usize>,
9564 ctx: &mut EventCtx,
9565 ) {
9566 self.selection_from = from.or(to);
9567 self.selection_to = to;
9568 if from.zip(to).is_some_and(|(from, to)| from != to) {
9569 let theme = self.resolved_theme();
9570 self.selection_animation = AnimatedScalar::new(0.0);
9571 self.selection_animation.set_target_event(
9572 1.0,
9573 theme.motion.tab_switch_duration(),
9574 theme.motion.tab_switch_easing(),
9575 ctx,
9576 );
9577 } else {
9578 self.selection_animation = AnimatedScalar::new(1.0);
9579 }
9580 ctx.request_paint();
9581 ctx.request_semantics();
9582 }
9583
9584 fn resolved_theme(&self) -> DefaultTheme {
9585 self.theme_reader
9586 .as_ref()
9587 .map(|theme| theme())
9588 .unwrap_or(*self.theme)
9589 }
9590
9591 fn close_size(theme: &DefaultTheme) -> f32 {
9592 (theme.metrics.tab_height * 0.56).clamp(16.0, 20.0)
9593 }
9594
9595 fn close_gap(theme: &DefaultTheme) -> f32 {
9596 theme.metrics.icon_label_gap.max(7.0)
9597 }
9598
9599 fn tab_height(&self) -> f32 {
9600 self.resolved_theme().metrics.tab_height
9601 }
9602
9603 fn measured_widths(&self) -> &[f32] {
9604 &self.widths
9605 }
9606
9607 fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
9608 if index >= self.tabs.len() || self.measured_widths().len() != self.tabs.len() {
9609 return None;
9610 }
9611
9612 let theme = self.resolved_theme();
9613 let gap = theme.metrics.tab_gap;
9614 let tab_height = self.tab_height().min(bounds.height()).max(0.0);
9615 let tab_y = bounds.y() + ((bounds.height() - tab_height) * 0.5).max(0.0);
9616 let mut x = bounds.x();
9617 for (current, measured_width) in self.widths.iter().enumerate() {
9618 let visible_width = (*measured_width).min((bounds.max_x() - x).max(0.0));
9619 let rect = Rect::new(x, tab_y, visible_width, tab_height);
9620 if current == index {
9621 return (visible_width > 0.0).then_some(rect);
9622 }
9623 x += *measured_width + gap;
9624 if x >= bounds.max_x() {
9625 break;
9626 }
9627 }
9628
9629 None
9630 }
9631
9632 fn close_rect_for(&self, tab_rect: Rect) -> Rect {
9633 let theme = self.resolved_theme();
9634 let close = Self::close_size(&theme)
9635 .min(tab_rect.width())
9636 .min(tab_rect.height());
9637 Rect::new(
9638 tab_rect.max_x() - close - Self::close_gap(&theme),
9639 tab_rect.y() + ((tab_rect.height() - close) * 0.5),
9640 close,
9641 close,
9642 )
9643 }
9644
9645 fn label_rect_for(&self, tab_rect: Rect) -> Rect {
9646 let theme = self.resolved_theme();
9647 let padding = theme.metrics.tab_padding;
9648 let close = self.close_rect_for(tab_rect);
9649 Rect::new(
9650 tab_rect.x() + padding.left,
9651 tab_rect.y() + padding.top,
9652 (close.x() - tab_rect.x() - padding.left - Self::close_gap(&theme)).max(0.0),
9653 (tab_rect.height() - padding.top - padding.bottom).max(0.0),
9654 )
9655 }
9656
9657 fn hit_at(&self, bounds: Rect, position: Point) -> Option<BrowserTabHit> {
9658 for index in 0..self.tabs.len() {
9659 let Some(rect) = self.tab_rect(bounds, index) else {
9660 continue;
9661 };
9662 if self.close_rect_for(rect).contains(position) {
9663 return Some(BrowserTabHit::Close(index));
9664 }
9665 if rect.contains(position) {
9666 return Some(BrowserTabHit::Tab(index));
9667 }
9668 }
9669 None
9670 }
9671
9672 fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
9673 self.refresh_tabs();
9674 if self.tabs.is_empty() {
9675 return;
9676 }
9677 let selected = self.normalized_selected().unwrap_or(0) as isize;
9678 let last = self.tabs.len() as isize - 1;
9679 let next = (selected + delta).clamp(0, last) as usize;
9680 self.activate(next, ctx);
9681 self.set_hovered(Some(BrowserTabHit::Tab(next)), ctx);
9682 }
9683
9684 fn advance_animations(&mut self, time: f64) -> bool {
9685 let selection_animating = self.selection_animation.advance(time);
9686 let hover_animating = self.hover_animation.advance(time);
9687 if !hover_animating
9688 && self.hovered.is_none()
9689 && self.hover_animation.value <= AnimatedScalar::EPSILON
9690 {
9691 self.hover_visual = None;
9692 }
9693 let press_animating = self.press_animation.advance(time);
9694 if !press_animating
9695 && self.pressed.is_none()
9696 && self.press_animation.value <= AnimatedScalar::EPSILON
9697 {
9698 self.press_visual = None;
9699 }
9700 let focus_animating = self.focus_animation.advance(time);
9701 selection_animating | hover_animating | press_animating | focus_animating
9702 }
9703
9704 fn set_hovered(&mut self, hovered: Option<BrowserTabHit>, ctx: &mut EventCtx) {
9705 if self.hovered == hovered {
9706 return;
9707 }
9708 let theme = self.resolved_theme();
9709 self.hovered = hovered;
9710 if let Some(hit) = hovered {
9711 self.hover_visual = Some(hit);
9712 self.hover_animation = AnimatedScalar::new(0.0);
9713 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
9714 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
9715 self.hover_visual = None;
9716 }
9717 ctx.request_paint();
9718 ctx.request_semantics();
9719 }
9720
9721 fn set_pressed(&mut self, pressed: Option<BrowserTabHit>, ctx: &mut EventCtx) {
9722 if self.pressed == pressed {
9723 return;
9724 }
9725 let theme = self.resolved_theme();
9726 self.pressed = pressed;
9727 if let Some(hit) = pressed {
9728 self.press_visual = Some(hit);
9729 self.press_animation = AnimatedScalar::new(0.0);
9730 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
9731 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
9732 self.press_visual = None;
9733 }
9734 ctx.request_paint();
9735 ctx.request_semantics();
9736 }
9737
9738 fn hover_amount_for(&self, index: usize) -> f32 {
9739 if self.hover_visual.is_some_and(|hit| hit.index() == index) {
9740 self.hover_animation.value
9741 } else {
9742 0.0
9743 }
9744 }
9745
9746 fn press_amount_for(&self, index: usize) -> f32 {
9747 if self.press_visual.is_some_and(|hit| hit.index() == index) {
9748 self.press_animation.value
9749 } else {
9750 0.0
9751 }
9752 }
9753}
9754
9755impl Widget for BrowserTabBar {
9756 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
9757 self.refresh_tabs();
9758 match event {
9759 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
9760 self.set_hovered(self.hit_at(ctx.bounds(), pointer.position), ctx);
9761 }
9762 Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
9763 self.set_hovered(None, ctx);
9764 }
9765 Event::Pointer(pointer)
9766 if pointer.kind == PointerEventKind::Down
9767 && pointer.button == Some(PointerButton::Primary) =>
9768 {
9769 let hovered = self.hit_at(ctx.bounds(), pointer.position);
9770 self.set_hovered(hovered, ctx);
9771 self.set_pressed(hovered, ctx);
9772 ctx.request_focus();
9773 ctx.request_pointer_capture(pointer.pointer_id);
9774 ctx.set_handled();
9775 }
9776 Event::Pointer(pointer)
9777 if pointer.kind == PointerEventKind::Up
9778 && pointer.button == Some(PointerButton::Primary) =>
9779 {
9780 let hovered = self.hit_at(ctx.bounds(), pointer.position);
9781 if let Some(hit) = self
9782 .pressed
9783 .zip(hovered)
9784 .filter(|(left, right)| left == right)
9785 .map(|(hit, _)| hit)
9786 {
9787 match hit {
9788 BrowserTabHit::Tab(index) => self.activate(index, ctx),
9789 BrowserTabHit::Close(index) => self.close(index, ctx),
9790 }
9791 }
9792 self.set_hovered(hovered, ctx);
9793 self.set_pressed(None, ctx);
9794 ctx.release_pointer_capture(pointer.pointer_id);
9795 ctx.set_handled();
9796 }
9797 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
9798 if self.pressed.is_some() {
9799 self.set_pressed(None, ctx);
9800 self.set_hovered(None, ctx);
9801 ctx.release_pointer_capture(pointer.pointer_id);
9802 ctx.set_handled();
9803 }
9804 }
9805 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
9806 match key.key.as_str() {
9807 "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
9808 "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
9809 "Home" => self.activate(0, ctx),
9810 "End" if !self.tabs.is_empty() => self.activate(self.tabs.len() - 1, ctx),
9811 _ => return,
9812 }
9813 ctx.request_paint();
9814 ctx.request_semantics();
9815 ctx.set_handled();
9816 }
9817 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
9818 if self.advance_animations(*time) {
9819 ctx.request_animation_frame();
9820 }
9821 ctx.request_paint();
9822 }
9823 _ => {}
9824 }
9825 }
9826
9827 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
9828 self.refresh_tabs();
9829 let theme = self.resolved_theme();
9830 let style = theme.text_style(theme.palette.text);
9831 let padding = theme.metrics.tab_padding;
9832 let close_extent = Self::close_size(&theme) + (Self::close_gap(&theme) * 2.0);
9833 self.label_measurements = self
9834 .tabs
9835 .iter()
9836 .map(|tab| measure_text(ctx, tab, &style))
9837 .collect();
9838 self.widths = self
9839 .label_measurements
9840 .iter()
9841 .map(|measurement| {
9842 (measurement.width + padding.left + padding.right + close_extent)
9843 .max(theme.metrics.tab_min_width)
9844 })
9845 .collect();
9846
9847 let gap = theme.metrics.tab_gap;
9848 let width =
9849 self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
9850 constraints.clamp(Size::new(width, self.tab_height()))
9851 }
9852
9853 fn paint(&self, ctx: &mut PaintCtx) {
9854 let theme = self.resolved_theme();
9855 let palette = theme.palette;
9856 let interaction = theme.interaction;
9857 let selected_index = self.normalized_selected();
9858 let focus_progress = self.focus_animation.value;
9859
9860 let clip_outset = physical_pixels(
9861 ctx,
9862 theme.metrics.focus_ring_outset + (theme.metrics.focus_ring_width * 0.5),
9863 );
9864 ctx.push_clip_rect(ctx.bounds().inflate(clip_outset, clip_outset));
9865 for (index, tab) in self.tabs.iter().enumerate() {
9866 let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9867 continue;
9868 };
9869 let selected = selected_index == Some(index);
9870 let hovered = self.hovered.is_some_and(|hit| hit.index() == index);
9871 let pressed = self.pressed.is_some_and(|hit| hit.index() == index);
9872 let hover_amount = self.hover_amount_for(index);
9873 let press_amount = self.press_amount_for(index);
9874
9875 if let Some((background, border)) = tab_state_visuals(
9876 &theme,
9877 selected,
9878 hovered,
9879 pressed,
9880 hover_amount,
9881 press_amount,
9882 ) {
9883 draw_control_shape(
9884 ctx,
9885 rect,
9886 theme.metrics.corner_radius,
9887 physical_pixels(ctx, theme.metrics.border_width),
9888 background,
9889 border,
9890 );
9891 }
9892
9893 if selected && focus_progress > AnimatedScalar::EPSILON {
9894 draw_focus_ring_frame(
9895 ctx,
9896 rect,
9897 theme.metrics.corner_radius,
9898 theme.metrics,
9899 palette
9900 .focus_ring
9901 .with_alpha(palette.focus_ring.alpha * focus_progress),
9902 );
9903 }
9904
9905 let text_style = theme.text_style(if selected {
9906 palette.text
9907 } else {
9908 palette.text_muted
9909 });
9910 let text_slot = self.label_rect_for(rect);
9911 let pressed_offset = press_amount * interaction.pressed_offset;
9912 ctx.push_clip_rect(text_slot);
9913 paint_aligned_text(
9914 ctx,
9915 text_slot.translate(Vector::new(0.0, pressed_offset)),
9916 tab,
9917 &text_style,
9918 text_style.line_height,
9919 0.0,
9920 );
9921 ctx.pop_clip();
9922
9923 let close = self.close_rect_for(rect);
9924 let close_hovered = self.hovered == Some(BrowserTabHit::Close(index));
9925 let close_pressed = self.pressed == Some(BrowserTabHit::Close(index));
9926 if close_hovered || close_pressed {
9927 ctx.fill(
9928 rounded_rect_path(close, theme.metrics.corner_radius.min(5.0)),
9929 if close_pressed {
9930 palette.control_active
9931 } else {
9932 palette.control_hover
9933 },
9934 );
9935 }
9936 draw_icon_glyph(
9937 ctx,
9938 IconGlyph::Close,
9939 close.inflate(-3.0, -3.0),
9940 if close_hovered || selected {
9941 palette.text
9942 } else {
9943 palette.placeholder
9944 }
9945 .with_alpha(if close_pressed { 0.95 } else { 0.78 }),
9946 );
9947 }
9948
9949 if let Some(selected) = selected_index {
9950 let progress = if self.selection_to == Some(selected) {
9951 self.selection_animation.value
9952 } else {
9953 1.0
9954 };
9955 if let Some(accent) = tab_indicator_rect(
9956 |index| self.tab_rect(ctx.bounds(), index),
9957 self.selection_from.unwrap_or(selected),
9958 selected,
9959 progress,
9960 theme.metrics.tab_padding,
9961 interaction.active_indicator_thickness,
9962 ) {
9963 ctx.fill(
9964 rounded_rect_path(accent, accent.height() * 0.5),
9965 palette.accent,
9966 );
9967 }
9968 }
9969 ctx.pop_clip();
9970 }
9971
9972 fn semantics(&self, ctx: &mut SemanticsCtx) {
9973 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TabBar, ctx.bounds());
9974 node.name = Some(self.name.clone());
9975 node.value = self
9976 .normalized_selected()
9977 .and_then(|index| self.tabs.get(index))
9978 .map(|value| SemanticsValue::Text(value.to_string()));
9979 node.state.focused = ctx.is_focused();
9980 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
9981 ctx.push(node);
9982
9983 for (index, tab) in self.tabs.iter().enumerate() {
9984 let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9985 continue;
9986 };
9987 let tab_id = browser_tab_semantics_id(ctx.widget_id(), index);
9988 let mut tab_node = SemanticsNode::new(tab_id, SemanticsRole::Button, rect);
9989 tab_node.parent = Some(ctx.widget_id());
9990 tab_node.name = Some(tab.clone());
9991 tab_node.state.selected = self.normalized_selected() == Some(index);
9992 tab_node.state.hovered = self.hovered.is_some_and(|hit| hit.index() == index);
9993 tab_node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
9994 ctx.push(tab_node);
9995
9996 let mut close_node = SemanticsNode::new(
9997 browser_tab_close_semantics_id(ctx.widget_id(), index),
9998 SemanticsRole::Button,
9999 self.close_rect_for(rect),
10000 );
10001 close_node.parent = Some(tab_id);
10002 close_node.name = Some(format!("Close {tab} tab"));
10003 close_node.state.hovered = self.hovered == Some(BrowserTabHit::Close(index));
10004 close_node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
10005 ctx.push(close_node);
10006 }
10007 }
10008
10009 fn accepts_focus(&self) -> bool {
10010 true
10011 }
10012
10013 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
10014 let theme = self.resolved_theme();
10015 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
10016 ctx.request_paint();
10017 ctx.request_semantics();
10018 }
10019}
10020
10021fn browser_tab_semantics_id(parent: WidgetId, index: usize) -> WidgetId {
10022 const TAG: u64 = 3_u64 << 51;
10023 const LOW_MASK: u64 = (1_u64 << 51) - 1;
10024 WidgetId::new(
10025 TAG | (parent
10026 .get()
10027 .wrapping_mul(397)
10028 .wrapping_add(index as u64 + 1)
10029 & LOW_MASK),
10030 )
10031}
10032
10033fn browser_tab_close_semantics_id(parent: WidgetId, index: usize) -> WidgetId {
10034 const TAG: u64 = 3_u64 << 51;
10035 const LOW_MASK: u64 = (1_u64 << 51) - 1;
10036 WidgetId::new(
10037 TAG | (parent
10038 .get()
10039 .wrapping_mul(397)
10040 .wrapping_add(10_000 + index as u64)
10041 & LOW_MASK),
10042 )
10043}
10044
10045pub struct SegmentedControl {
10046 theme: Box<DefaultTheme>,
10047 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
10048 name: String,
10049 segments: Vec<SegmentedControlItem>,
10050 selected: usize,
10051 selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
10052 selection_from: usize,
10053 selection_animation: AnimatedScalar,
10054 hovered: Option<usize>,
10055 hover_visual: Option<usize>,
10056 pressed: Option<usize>,
10057 press_visual: Option<usize>,
10058 hover_animation: AnimatedScalar,
10059 press_animation: AnimatedScalar,
10060 focus_animation: AnimatedScalar,
10061 label_measurements: Vec<TextMeasurement>,
10062 on_change: Option<SegmentedControlChange>,
10063 on_change_with_ctx: Option<SegmentedControlContextChange>,
10064}
10065
10066pub struct SegmentedControlItem {
10067 label: String,
10068 semantic_name: Option<String>,
10069 description: Option<String>,
10070 disabled: bool,
10071}
10072
10073impl SegmentedControlItem {
10074 pub fn new(label: impl Into<String>) -> Self {
10075 Self {
10076 label: label.into(),
10077 semantic_name: None,
10078 description: None,
10079 disabled: false,
10080 }
10081 }
10082
10083 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
10084 self.semantic_name = Some(name.into());
10085 self
10086 }
10087
10088 pub fn description(mut self, description: impl Into<String>) -> Self {
10089 self.description = Some(description.into());
10090 self
10091 }
10092
10093 pub fn disabled(mut self) -> Self {
10094 self.disabled = true;
10095 self
10096 }
10097
10098 pub fn label(&self) -> &str {
10099 &self.label
10100 }
10101}
10102
10103impl SegmentedControl {
10104 pub fn new(name: impl Into<String>) -> Self {
10105 Self {
10106 theme: Box::new(DefaultTheme::default()),
10107 theme_reader: None,
10108 name: name.into(),
10109 segments: Vec::new(),
10110 selected: 0,
10111 selected_reader: None,
10112 selection_from: 0,
10113 selection_animation: AnimatedScalar::new(1.0),
10114 hovered: None,
10115 hover_visual: None,
10116 pressed: None,
10117 press_visual: None,
10118 hover_animation: AnimatedScalar::new(0.0),
10119 press_animation: AnimatedScalar::new(0.0),
10120 focus_animation: AnimatedScalar::new(0.0),
10121 label_measurements: Vec::new(),
10122 on_change: None,
10123 on_change_with_ctx: None,
10124 }
10125 }
10126
10127 pub fn theme(mut self, theme: DefaultTheme) -> Self {
10128 self.theme = Box::new(theme);
10129 self.theme_reader = None;
10130 self
10131 }
10132
10133 pub fn theme_when<F>(mut self, theme: F) -> Self
10134 where
10135 F: Fn() -> DefaultTheme + 'static,
10136 {
10137 self.theme_reader = Some(Box::new(theme));
10138 self
10139 }
10140
10141 pub fn item(mut self, item: SegmentedControlItem) -> Self {
10142 self.segments.push(item);
10143 self
10144 }
10145
10146 pub fn items<I>(mut self, items: I) -> Self
10147 where
10148 I: IntoIterator<Item = SegmentedControlItem>,
10149 {
10150 self.segments.extend(items);
10151 self
10152 }
10153
10154 pub fn segments<I, S>(mut self, labels: I) -> Self
10155 where
10156 I: IntoIterator<Item = S>,
10157 S: Into<String>,
10158 {
10159 self.segments
10160 .extend(labels.into_iter().map(SegmentedControlItem::new));
10161 self
10162 }
10163
10164 pub fn selected(mut self, index: usize) -> Self {
10165 self.selected = index;
10166 self.selected_reader = None;
10167 self.selection_from = index;
10168 self.selection_animation = AnimatedScalar::new(1.0);
10169 self
10170 }
10171
10172 pub fn selected_when<F>(mut self, selected: F) -> Self
10173 where
10174 F: Fn() -> Option<usize> + 'static,
10175 {
10176 self.selected_reader = Some(Box::new(selected));
10177 self
10178 }
10179
10180 pub fn on_change<F>(mut self, on_change: F) -> Self
10181 where
10182 F: FnMut(usize, String) + 'static,
10183 {
10184 self.on_change = Some(Box::new(on_change));
10185 self
10186 }
10187
10188 pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
10189 where
10190 F: FnMut(usize, String, &mut EventCtx) + 'static,
10191 {
10192 self.on_change_with_ctx = Some(Box::new(on_change));
10193 self
10194 }
10195
10196 pub fn selected_index(&self) -> usize {
10197 self.normalized_selected()
10198 }
10199
10200 fn normalized_selected(&self) -> usize {
10201 let selected = self
10202 .selected_reader
10203 .as_ref()
10204 .and_then(|reader| reader())
10205 .unwrap_or(self.selected);
10206 if self.segments.is_empty() {
10207 0
10208 } else {
10209 selected.min(self.segments.len() - 1)
10210 }
10211 }
10212
10213 fn segment_height(&self) -> f32 {
10214 self.resolved_theme().metrics.tab_height
10215 }
10216
10217 fn segment_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
10218 if index >= self.segments.len() {
10219 return None;
10220 }
10221 let count = self.segments.len().max(1);
10222 let width = bounds.width() / count as f32;
10223 let x = bounds.x() + width * index as f32;
10224 let width = if index + 1 == count {
10225 bounds.max_x() - x
10226 } else {
10227 width
10228 };
10229 Some(Rect::new(
10230 x,
10231 bounds.y(),
10232 width.max(0.0),
10233 bounds.height().max(0.0),
10234 ))
10235 }
10236
10237 fn segment_at(&self, bounds: Rect, position: Point) -> Option<usize> {
10238 if !bounds.contains(position) || self.segments.is_empty() {
10239 return None;
10240 }
10241 let slot_width = (bounds.width() / self.segments.len() as f32).max(1.0);
10242 let index = ((position.x - bounds.x()) / slot_width).floor() as usize;
10243 Some(index.min(self.segments.len() - 1))
10244 }
10245
10246 fn resolved_theme(&self) -> DefaultTheme {
10247 self.theme_reader
10248 .as_ref()
10249 .map(|theme| theme())
10250 .unwrap_or(*self.theme)
10251 }
10252
10253 fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
10254 let Some(segment) = self.segments.get(index) else {
10255 return;
10256 };
10257 if segment.disabled {
10258 return;
10259 }
10260
10261 let index = index.min(self.segments.len() - 1);
10262 let selected = self.normalized_selected();
10263 if selected != index {
10264 let theme = self.resolved_theme();
10265 self.selection_from = selected;
10266 self.selected = index;
10267 self.selection_animation = AnimatedScalar::new(0.0);
10268 self.selection_animation.set_target_event(
10269 1.0,
10270 theme.motion.tab_switch_duration(),
10271 theme.motion.tab_switch_easing(),
10272 ctx,
10273 );
10274 let label = self.segments[index].label.clone();
10275 if let Some(on_change) = &mut self.on_change {
10276 on_change(index, label.clone());
10277 }
10278 if let Some(on_change) = &mut self.on_change_with_ctx {
10279 on_change(index, label, ctx);
10280 }
10281 }
10282 }
10283
10284 fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
10285 if self.segments.is_empty() {
10286 return;
10287 }
10288 let selected = self.normalized_selected() as isize;
10289 let last = self.segments.len() as isize - 1;
10290 let next = (selected + delta).clamp(0, last) as usize;
10291 self.activate(next, ctx);
10292 self.set_hovered(Some(next), ctx);
10293 }
10294
10295 fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
10296 if self.hovered == hovered {
10297 return;
10298 }
10299 let theme = self.resolved_theme();
10300 self.hovered = hovered;
10301 if let Some(index) = hovered {
10302 self.hover_visual = Some(index);
10303 self.hover_animation = AnimatedScalar::new(0.0);
10304 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
10305 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
10306 self.hover_visual = None;
10307 }
10308 ctx.request_paint();
10309 ctx.request_semantics();
10310 }
10311
10312 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
10313 if self.pressed == pressed {
10314 return;
10315 }
10316 let theme = self.resolved_theme();
10317 self.pressed = pressed;
10318 if let Some(index) = pressed {
10319 self.press_visual = Some(index);
10320 self.press_animation = AnimatedScalar::new(0.0);
10321 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
10322 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
10323 self.press_visual = None;
10324 }
10325 ctx.request_paint();
10326 ctx.request_semantics();
10327 }
10328
10329 fn hover_amount_for(&self, index: usize) -> f32 {
10330 if self.hover_visual == Some(index) {
10331 self.hover_animation.value
10332 } else {
10333 0.0
10334 }
10335 }
10336
10337 fn press_amount_for(&self, index: usize) -> f32 {
10338 if self.press_visual == Some(index) {
10339 self.press_animation.value
10340 } else {
10341 0.0
10342 }
10343 }
10344
10345 fn advance_animations(&mut self, time: f64) -> bool {
10346 let selection_animating = self.selection_animation.advance(time);
10347 let hover_animating = self.hover_animation.advance(time);
10348 if !hover_animating
10349 && self.hovered.is_none()
10350 && self.hover_animation.value <= AnimatedScalar::EPSILON
10351 {
10352 self.hover_visual = None;
10353 }
10354 let press_animating = self.press_animation.advance(time);
10355 if !press_animating
10356 && self.pressed.is_none()
10357 && self.press_animation.value <= AnimatedScalar::EPSILON
10358 {
10359 self.press_visual = None;
10360 }
10361 let focus_animating = self.focus_animation.advance(time);
10362 selection_animating | hover_animating | press_animating | focus_animating
10363 }
10364}
10365
10366impl Widget for SegmentedControl {
10367 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
10368 match event {
10369 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
10370 self.set_hovered(self.segment_at(ctx.bounds(), pointer.position), ctx);
10371 }
10372 Event::Pointer(pointer)
10373 if pointer.kind == PointerEventKind::Leave
10374 || pointer.kind == PointerEventKind::Cancel =>
10375 {
10376 if pointer.kind == PointerEventKind::Cancel && self.pressed.is_some() {
10377 ctx.release_pointer_capture(pointer.pointer_id);
10378 ctx.set_handled();
10379 }
10380 self.set_pressed(None, ctx);
10381 self.set_hovered(None, ctx);
10382 }
10383 Event::Pointer(pointer)
10384 if pointer.kind == PointerEventKind::Down
10385 && pointer.button == Some(PointerButton::Primary) =>
10386 {
10387 let hovered = self.segment_at(ctx.bounds(), pointer.position);
10388 self.set_hovered(hovered, ctx);
10389 self.set_pressed(hovered, ctx);
10390 ctx.request_focus();
10391 ctx.request_pointer_capture(pointer.pointer_id);
10392 ctx.set_handled();
10393 }
10394 Event::Pointer(pointer)
10395 if pointer.kind == PointerEventKind::Up
10396 && pointer.button == Some(PointerButton::Primary) =>
10397 {
10398 let hovered = self.segment_at(ctx.bounds(), pointer.position);
10399 if let Some(index) = self
10400 .pressed
10401 .zip(hovered)
10402 .filter(|(left, right)| left == right)
10403 .map(|(index, _)| index)
10404 {
10405 self.activate(index, ctx);
10406 }
10407 self.set_hovered(hovered, ctx);
10408 self.set_pressed(None, ctx);
10409 ctx.release_pointer_capture(pointer.pointer_id);
10410 ctx.set_handled();
10411 }
10412 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
10413 match key.key.as_str() {
10414 "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
10415 "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
10416 "Home" => self.activate(0, ctx),
10417 "End" if !self.segments.is_empty() => {
10418 self.activate(self.segments.len() - 1, ctx)
10419 }
10420 _ => return,
10421 }
10422 ctx.request_paint();
10423 ctx.request_semantics();
10424 ctx.set_handled();
10425 }
10426 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
10427 if self.advance_animations(*time) {
10428 ctx.request_animation_frame();
10429 }
10430 ctx.request_paint();
10431 }
10432 _ => {}
10433 }
10434 }
10435
10436 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
10437 let theme = self.resolved_theme();
10438 let style = semibold_control_text_style(&theme, theme.palette.text);
10439 let padding = theme.metrics.tab_padding;
10440 self.label_measurements = self
10441 .segments
10442 .iter()
10443 .map(|segment| measure_text(ctx, &segment.label, &style))
10444 .collect();
10445 let widest = self
10446 .label_measurements
10447 .iter()
10448 .map(|measurement| measurement.width + padding.left + padding.right)
10449 .fold(theme.metrics.tab_min_width, f32::max);
10450 let width = widest * self.segments.len().max(1) as f32;
10451 constraints.clamp(Size::new(width.max(160.0), self.segment_height()))
10452 }
10453
10454 fn paint(&self, ctx: &mut PaintCtx) {
10455 let theme = self.resolved_theme();
10456 let palette = theme.palette;
10457 let metrics = theme.metrics;
10458 let interaction = theme.interaction;
10459 let padding = metrics.tab_padding;
10460 let label_style = semibold_control_text_style(&theme, palette.text_muted);
10461 let selected_label_style = TextStyle {
10462 color: palette.accent,
10463 ..label_style.clone()
10464 };
10465 let radius = metrics.corner_radius;
10466
10467 ctx.fill(rounded_rect_path(ctx.bounds(), radius), palette.control);
10468
10469 let selected_thumb = if !self.segments.is_empty() {
10470 let from = self.selection_from.min(self.segments.len() - 1);
10471 let selected = self.normalized_selected();
10472 let thumb = sliding_inset_rect(
10473 |index| self.segment_rect(ctx.bounds(), index),
10474 from,
10475 selected,
10476 self.selection_animation.value,
10477 Insets::all(2.0),
10478 );
10479 if let Some(thumb) = thumb {
10480 draw_control_shape(
10481 ctx,
10482 thumb,
10483 (thumb.height() * 0.5).min(radius),
10484 physical_pixels(ctx, metrics.border_width),
10485 palette.selection,
10486 palette.accent.with_alpha(0.36),
10487 );
10488 }
10489 thumb
10490 } else {
10491 None
10492 };
10493
10494 let focus_progress = self.focus_animation.value;
10495 for (index, segment) in self.segments.iter().enumerate() {
10496 let Some(rect) = self.segment_rect(ctx.bounds(), index) else {
10497 continue;
10498 };
10499 let selected = self.normalized_selected() == index;
10500 let hovered = self.hovered == Some(index);
10501 let pressed = self.pressed == Some(index);
10502 let hover_amount = self.hover_amount_for(index);
10503 let press_amount = self.press_amount_for(index);
10504
10505 if !selected
10506 && let Some((background, border)) =
10507 tab_state_visuals(&theme, false, hovered, pressed, hover_amount, press_amount)
10508 {
10509 draw_control_shape(
10510 ctx,
10511 rect.inflate(-1.0, -1.0),
10512 radius,
10513 physical_pixels(ctx, metrics.border_width),
10514 background,
10515 border,
10516 );
10517 }
10518
10519 if selected && focus_progress > AnimatedScalar::EPSILON {
10520 let focus_bounds = selected_thumb.unwrap_or_else(|| rect.inflate(-2.0, -2.0));
10521 draw_focus_ring_frame(
10522 ctx,
10523 focus_bounds,
10524 (focus_bounds.height() * 0.5).min(radius),
10525 metrics,
10526 palette
10527 .focus_ring
10528 .with_alpha(palette.focus_ring.alpha * focus_progress),
10529 );
10530 }
10531
10532 let text_style = if selected {
10533 selected_label_style.clone()
10534 } else {
10535 label_style.clone()
10536 };
10537 let text_slot = inset_rect(rect, padding);
10538 let pressed_offset = press_amount * interaction.pressed_offset;
10539 ctx.push_clip_rect(text_slot);
10540 paint_aligned_text(
10541 ctx,
10542 text_slot.translate(Vector::new(0.0, pressed_offset)),
10543 &segment.label,
10544 &text_style,
10545 text_style.line_height,
10546 0.5,
10547 );
10548 ctx.pop_clip();
10549 }
10550 }
10551
10552 fn semantics(&self, ctx: &mut SemanticsCtx) {
10553 let selected = self.normalized_selected();
10554 let value = self
10555 .segments
10556 .get(selected)
10557 .map(|segment| segment.label.clone());
10558 let mut group =
10559 SemanticsNode::new(ctx.widget_id(), SemanticsRole::RadioGroup, ctx.bounds());
10560 group.name = Some(self.name.clone());
10561 group.value = value.map(SemanticsValue::Text);
10562 group.state.focused = ctx.is_focused();
10563 group.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
10564 ctx.push(group);
10565
10566 for (index, segment) in self.segments.iter().enumerate() {
10567 let Some(bounds) = self.segment_rect(ctx.bounds(), index) else {
10568 continue;
10569 };
10570 let mut node = SemanticsNode::new(
10571 segmented_control_item_id(ctx.widget_id(), index),
10572 SemanticsRole::RadioButton,
10573 bounds,
10574 );
10575 node.parent = Some(ctx.widget_id());
10576 node.name = Some(
10577 segment
10578 .semantic_name
10579 .clone()
10580 .unwrap_or_else(|| segment.label.clone()),
10581 );
10582 node.description = segment.description.clone();
10583 node.value = Some(SemanticsValue::Text(segment.label.clone()));
10584 node.actions = if segment.disabled {
10585 Vec::new()
10586 } else {
10587 vec![SemanticsAction::Activate]
10588 };
10589 node.state.disabled = segment.disabled;
10590 node.state.hovered = self.hovered == Some(index);
10591 node.state.selected = selected == index;
10592 node.state.checked = Some(if selected == index {
10593 sui_core::ToggleState::Checked
10594 } else {
10595 sui_core::ToggleState::Unchecked
10596 });
10597 ctx.push(node);
10598 }
10599 }
10600
10601 fn accepts_focus(&self) -> bool {
10602 true
10603 }
10604
10605 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
10606 let theme = self.resolved_theme();
10607 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
10608 ctx.request_paint();
10609 ctx.request_semantics();
10610 }
10611}
10612
10613pub struct Tabs {
10614 theme: Box<DefaultTheme>,
10615 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
10616 name: String,
10617 labels: Vec<String>,
10618 panels: WidgetChildren,
10619 selected: usize,
10620 selection_from: usize,
10621 selection_animation: AnimatedScalar,
10622 hovered: Option<usize>,
10623 hover_visual: Option<usize>,
10624 pressed: Option<usize>,
10625 press_visual: Option<usize>,
10626 hover_animation: AnimatedScalar,
10627 press_animation: AnimatedScalar,
10628 focus_animation: AnimatedScalar,
10629 label_measurements: Vec<TextMeasurement>,
10630 widths: Vec<f32>,
10631 gap: Option<f32>,
10632 panel_frame: Rect,
10633 on_change: Option<Box<dyn FnMut(usize, String)>>,
10634}
10635
10636impl Tabs {
10637 pub fn new(name: impl Into<String>) -> Self {
10638 Self {
10639 theme: Box::new(DefaultTheme::default()),
10640 theme_reader: None,
10641 name: name.into(),
10642 labels: Vec::new(),
10643 panels: WidgetChildren::new(),
10644 selected: 0,
10645 selection_from: 0,
10646 selection_animation: AnimatedScalar::new(1.0),
10647 hovered: None,
10648 hover_visual: None,
10649 pressed: None,
10650 press_visual: None,
10651 hover_animation: AnimatedScalar::new(0.0),
10652 press_animation: AnimatedScalar::new(0.0),
10653 focus_animation: AnimatedScalar::new(0.0),
10654 label_measurements: Vec::new(),
10655 widths: Vec::new(),
10656 gap: None,
10657 panel_frame: Rect::ZERO,
10658 on_change: None,
10659 }
10660 }
10661
10662 pub fn theme(mut self, theme: DefaultTheme) -> Self {
10663 self.theme = Box::new(theme);
10664 self.theme_reader = None;
10665 self
10666 }
10667
10668 pub fn theme_when<F>(mut self, theme: F) -> Self
10669 where
10670 F: Fn() -> DefaultTheme + 'static,
10671 {
10672 self.theme_reader = Some(Box::new(theme));
10673 self
10674 }
10675
10676 pub fn selected(mut self, index: usize) -> Self {
10677 self.selected = index;
10678 self.selection_from = index;
10679 self.selection_animation = AnimatedScalar::new(1.0);
10680 self
10681 }
10682
10683 pub fn on_change<F>(mut self, on_change: F) -> Self
10684 where
10685 F: FnMut(usize, String) + 'static,
10686 {
10687 self.on_change = Some(Box::new(on_change));
10688 self
10689 }
10690
10691 pub fn tab<W>(mut self, label: impl Into<String>, panel: W) -> Self
10692 where
10693 W: Widget + 'static,
10694 {
10695 self.labels.push(label.into());
10696 self.panels.push(panel);
10697 self
10698 }
10699
10700 pub fn selected_index(&self) -> usize {
10701 self.normalized_selected()
10702 }
10703
10704 pub fn current_tab(&self) -> Option<&str> {
10705 self.labels
10706 .get(self.normalized_selected())
10707 .map(String::as_str)
10708 }
10709
10710 fn normalized_selected(&self) -> usize {
10711 if self.labels.is_empty() {
10712 0
10713 } else {
10714 self.selected.min(self.labels.len() - 1)
10715 }
10716 }
10717
10718 fn header_height(&self) -> f32 {
10719 self.resolved_theme().metrics.tab_height
10720 }
10721
10722 fn resolved_gap(&self) -> f32 {
10723 self.gap
10724 .unwrap_or(self.resolved_theme().metrics.tab_gap)
10725 .max(0.0)
10726 }
10727
10728 fn header_rect(&self, bounds: Rect) -> Rect {
10729 Rect::new(bounds.x(), bounds.y(), bounds.width(), self.header_height())
10730 }
10731
10732 fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
10733 if index >= self.labels.len() || self.widths.len() != self.labels.len() {
10734 return None;
10735 }
10736
10737 let header = self.header_rect(bounds);
10738 let gap = self.resolved_gap();
10739 let base_total =
10740 self.widths.iter().sum::<f32>() + (gap * self.labels.len().saturating_sub(1) as f32);
10741 let extra_per_tab = if header.width() > base_total && !self.labels.is_empty() {
10742 (header.width() - base_total) / self.labels.len() as f32
10743 } else {
10744 0.0
10745 };
10746
10747 let mut x = header.x();
10748 for (current, width) in self.widths.iter().enumerate() {
10749 let rect = Rect::new(x, header.y(), *width + extra_per_tab, header.height());
10750 if current == index {
10751 return Some(rect);
10752 }
10753 x += rect.width() + gap;
10754 }
10755
10756 None
10757 }
10758
10759 fn tab_at(&self, bounds: Rect, position: Point) -> Option<usize> {
10760 self.labels.iter().enumerate().find_map(|(index, _)| {
10761 self.tab_rect(bounds, index)
10762 .filter(|rect| rect.contains(position))
10763 .map(|_| index)
10764 })
10765 }
10766
10767 fn select(&mut self, index: usize, ctx: &mut EventCtx) {
10768 if self.labels.is_empty() {
10769 return;
10770 }
10771
10772 let index = index.min(self.labels.len() - 1);
10773 if self.selected != index {
10774 let theme = self.resolved_theme();
10775 self.selection_from = self.normalized_selected();
10776 self.selected = index;
10777 self.selection_animation = AnimatedScalar::new(0.0);
10778 self.selection_animation.set_target_event(
10779 1.0,
10780 theme.motion.tab_switch_duration(),
10781 theme.motion.tab_switch_easing(),
10782 ctx,
10783 );
10784 if let Some(on_change) = &mut self.on_change {
10785 on_change(index, self.labels[index].clone());
10786 }
10787 }
10788 }
10789
10790 fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
10791 if self.labels.is_empty() {
10792 return;
10793 }
10794
10795 let next = (self.normalized_selected() as isize + delta)
10796 .clamp(0, self.labels.len() as isize - 1) as usize;
10797 self.set_hovered(Some(next), ctx);
10798 self.select(next, ctx);
10799 }
10800
10801 fn advance_animations(&mut self, time: f64) -> bool {
10802 let selection_animating = self.selection_animation.advance(time);
10803 let hover_animating = self.hover_animation.advance(time);
10804 if !hover_animating
10805 && self.hovered.is_none()
10806 && self.hover_animation.value <= AnimatedScalar::EPSILON
10807 {
10808 self.hover_visual = None;
10809 }
10810 let press_animating = self.press_animation.advance(time);
10811 if !press_animating
10812 && self.pressed.is_none()
10813 && self.press_animation.value <= AnimatedScalar::EPSILON
10814 {
10815 self.press_visual = None;
10816 }
10817 let focus_animating = self.focus_animation.advance(time);
10818 selection_animating | hover_animating | press_animating | focus_animating
10819 }
10820
10821 fn selected_panel(&self) -> Option<&sui_runtime::WidgetPod> {
10822 self.panels.as_slice().get(self.normalized_selected())
10823 }
10824
10825 fn selected_panel_mut(&mut self) -> Option<&mut sui_runtime::WidgetPod> {
10826 let index = self.normalized_selected();
10827 self.panels.as_mut_slice().get_mut(index)
10828 }
10829
10830 fn resolved_theme(&self) -> DefaultTheme {
10831 self.theme_reader
10832 .as_ref()
10833 .map(|theme| theme())
10834 .unwrap_or(*self.theme)
10835 }
10836
10837 fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
10838 if self.hovered == hovered {
10839 return;
10840 }
10841 let theme = self.resolved_theme();
10842 self.hovered = hovered;
10843 if let Some(index) = hovered {
10844 self.hover_visual = Some(index);
10845 self.hover_animation = AnimatedScalar::new(0.0);
10846 set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
10847 } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
10848 self.hover_visual = None;
10849 }
10850 ctx.request_paint();
10851 ctx.request_semantics();
10852 }
10853
10854 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
10855 if self.pressed == pressed {
10856 return;
10857 }
10858 let theme = self.resolved_theme();
10859 self.pressed = pressed;
10860 if let Some(index) = pressed {
10861 self.press_visual = Some(index);
10862 self.press_animation = AnimatedScalar::new(0.0);
10863 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
10864 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
10865 self.press_visual = None;
10866 }
10867 ctx.request_paint();
10868 ctx.request_semantics();
10869 }
10870
10871 fn hover_amount_for(&self, index: usize) -> f32 {
10872 if self.hover_visual == Some(index) {
10873 self.hover_animation.value
10874 } else {
10875 0.0
10876 }
10877 }
10878
10879 fn press_amount_for(&self, index: usize) -> f32 {
10880 if self.press_visual == Some(index) {
10881 self.press_animation.value
10882 } else {
10883 0.0
10884 }
10885 }
10886}
10887
10888impl Widget for Tabs {
10889 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
10890 match event {
10891 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
10892 self.set_hovered(self.tab_at(ctx.bounds(), pointer.position), ctx);
10893 }
10894 Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
10895 self.set_hovered(None, ctx);
10896 }
10897 Event::Pointer(pointer)
10898 if pointer.kind == PointerEventKind::Down
10899 && pointer.button == Some(PointerButton::Primary)
10900 && self.header_rect(ctx.bounds()).contains(pointer.position) =>
10901 {
10902 let hovered = self.tab_at(ctx.bounds(), pointer.position);
10903 self.set_hovered(hovered, ctx);
10904 self.set_pressed(hovered, ctx);
10905 ctx.request_focus();
10906 ctx.request_pointer_capture(pointer.pointer_id);
10907 ctx.set_handled();
10908 }
10909 Event::Pointer(pointer)
10910 if pointer.kind == PointerEventKind::Up
10911 && pointer.button == Some(PointerButton::Primary) =>
10912 {
10913 if self.pressed.is_some() {
10914 let hovered = self.tab_at(ctx.bounds(), pointer.position);
10915 if let Some(index) = self
10916 .pressed
10917 .zip(hovered)
10918 .filter(|(left, right)| left == right)
10919 .map(|(index, _)| index)
10920 {
10921 self.select(index, ctx);
10922 ctx.request_measure();
10923 }
10924 self.set_hovered(hovered, ctx);
10925 self.set_pressed(None, ctx);
10926 ctx.release_pointer_capture(pointer.pointer_id);
10927 ctx.set_handled();
10928 }
10929 }
10930 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
10931 if self.pressed.is_some() {
10932 self.set_pressed(None, ctx);
10933 self.set_hovered(None, ctx);
10934 ctx.release_pointer_capture(pointer.pointer_id);
10935 ctx.set_handled();
10936 }
10937 }
10938 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
10939 match key.key.as_str() {
10940 "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
10941 "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
10942 "Home" => self.select(0, ctx),
10943 "End" if !self.labels.is_empty() => self.select(self.labels.len() - 1, ctx),
10944 _ => return,
10945 }
10946 ctx.request_measure();
10947 ctx.request_paint();
10948 ctx.request_semantics();
10949 ctx.set_handled();
10950 }
10951 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
10952 if self.advance_animations(*time) {
10953 ctx.request_animation_frame();
10954 }
10955 ctx.request_paint();
10956 }
10957 _ => {}
10958 }
10959 }
10960
10961 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
10962 let theme = self.resolved_theme();
10963 let text_style = theme.text_style(theme.palette.text);
10964 let tab_padding = theme.metrics.tab_padding;
10965 self.label_measurements = self
10966 .labels
10967 .iter()
10968 .map(|label| measure_text(ctx, label, &text_style))
10969 .collect();
10970 self.widths = self
10971 .label_measurements
10972 .iter()
10973 .map(|measurement| {
10974 (measurement.width + tab_padding.left + tab_padding.right)
10975 .max(theme.metrics.tab_min_width)
10976 })
10977 .collect();
10978
10979 let gap = self.resolved_gap();
10980 let header_width =
10981 self.widths.iter().sum::<f32>() + (gap * self.labels.len().saturating_sub(1) as f32);
10982 let available_width = if constraints.max.width.is_finite() {
10983 constraints.max.width.max(header_width)
10984 } else {
10985 header_width.max(320.0)
10986 };
10987 let header_height = self.header_height();
10988 let padding = theme.metrics.tab_panel_padding;
10989 let panel_gap = theme.metrics.tab_panel_gap;
10990
10991 let panel_constraints = Constraints::new(
10992 Size::ZERO,
10993 Size::new(
10994 (available_width - padding.left - padding.right).max(0.0),
10995 if constraints.max.height.is_finite() {
10996 (constraints.max.height
10997 - header_height
10998 - panel_gap
10999 - padding.top
11000 - padding.bottom)
11001 .max(0.0)
11002 } else {
11003 f32::INFINITY
11004 },
11005 ),
11006 );
11007
11008 let panel_size = if let Some(panel) = self.selected_panel_mut() {
11009 panel.measure(ctx, panel_constraints)
11010 } else {
11011 Size::new(0.0, theme.metrics.min_height)
11012 };
11013
11014 let content_width = (panel_size.width + padding.left + padding.right).max(available_width);
11015 let content_height = panel_size.height + padding.top + padding.bottom;
11016 self.panel_frame = Rect::new(
11017 0.0,
11018 header_height + panel_gap,
11019 content_width,
11020 content_height,
11021 );
11022
11023 constraints.clamp(Size::new(
11024 content_width,
11025 header_height + panel_gap + content_height,
11026 ))
11027 }
11028
11029 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
11030 let theme = self.resolved_theme();
11031 let header_height = self.header_height();
11032 let padding = theme.metrics.tab_panel_padding;
11033 let panel_gap = theme.metrics.tab_panel_gap;
11034 if let Some(panel) = self.selected_panel_mut() {
11035 let panel_size = panel.measured_size();
11036 panel.arrange(
11037 ctx,
11038 Rect::new(
11039 bounds.x() + padding.left,
11040 bounds.y() + header_height + panel_gap + padding.top,
11041 panel_size.width,
11042 panel_size.height,
11043 ),
11044 );
11045 }
11046 }
11047
11048 fn paint(&self, ctx: &mut PaintCtx) {
11049 let theme = self.resolved_theme();
11050 let palette = theme.palette;
11051 let metrics = theme.metrics;
11052 let interaction = theme.interaction;
11053 let tab_padding = metrics.tab_padding;
11054 let header = self.header_rect(ctx.bounds());
11055 let label_style = theme.text_style(palette.text_muted);
11056 let selected_label_style = theme.text_style(palette.text);
11057
11058 ctx.fill(
11059 rounded_rect_path(header, metrics.corner_radius),
11060 palette.control,
11061 );
11062
11063 let focus_progress = self.focus_animation.value;
11064 for (index, label) in self.labels.iter().enumerate() {
11065 let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
11066 continue;
11067 };
11068 let selected = self.normalized_selected() == index;
11069 let hovered = self.hovered == Some(index);
11070 let pressed = self.pressed == Some(index);
11071 let hover_amount = self.hover_amount_for(index);
11072 let press_amount = self.press_amount_for(index);
11073
11074 if let Some((background, border)) = tab_state_visuals(
11075 &theme,
11076 selected,
11077 hovered,
11078 pressed,
11079 hover_amount,
11080 press_amount,
11081 ) {
11082 draw_control_shape(
11083 ctx,
11084 rect,
11085 metrics.corner_radius,
11086 physical_pixels(ctx, metrics.border_width),
11087 background,
11088 border,
11089 );
11090 }
11091
11092 if selected && focus_progress > AnimatedScalar::EPSILON {
11093 draw_focus_ring_frame(
11094 ctx,
11095 rect,
11096 metrics.corner_radius,
11097 metrics,
11098 palette
11099 .focus_ring
11100 .with_alpha(palette.focus_ring.alpha * focus_progress),
11101 );
11102 }
11103
11104 let text_style = if selected {
11105 selected_label_style.clone()
11106 } else {
11107 label_style.clone()
11108 };
11109 let text_slot = inset_rect(rect, tab_padding);
11110 let pressed_offset = press_amount * interaction.pressed_offset;
11111 ctx.push_clip_rect(text_slot);
11112 paint_aligned_text(
11113 ctx,
11114 text_slot.translate(Vector::new(0.0, pressed_offset)),
11115 label,
11116 &text_style,
11117 text_style.line_height,
11118 0.5,
11119 );
11120 ctx.pop_clip();
11121 }
11122
11123 if let Some(accent) = tab_indicator_rect(
11124 |index| self.tab_rect(ctx.bounds(), index),
11125 self.selection_from,
11126 self.normalized_selected(),
11127 self.selection_animation.value,
11128 tab_padding,
11129 interaction.active_indicator_thickness,
11130 ) {
11131 ctx.fill(
11132 rounded_rect_path(accent, accent.height() * 0.5),
11133 palette.accent,
11134 );
11135 }
11136
11137 let content = self.panel_frame.translate(ctx.bounds().origin.to_vector());
11138 draw_control_frame(
11139 ctx,
11140 content,
11141 metrics.corner_radius + 2.0,
11142 metrics,
11143 palette.surface_raised,
11144 palette.border,
11145 None,
11146 );
11147 if let Some(panel) = self.selected_panel() {
11148 let panel_translation = tab_panel_transition_translation(
11149 self.selection_from,
11150 self.normalized_selected(),
11151 self.selection_animation.value,
11152 metrics,
11153 );
11154 if panel_translation == Vector::ZERO {
11155 panel.paint(ctx);
11156 } else {
11157 ctx.push_clip_rect(content);
11158 ctx.translate(panel_translation);
11159 panel.paint(ctx);
11160 ctx.pop_transform();
11161 ctx.pop_clip();
11162 }
11163 }
11164 }
11165
11166 fn semantics(&self, ctx: &mut SemanticsCtx) {
11167 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Tabs, ctx.bounds());
11168 node.name = Some(self.name.clone());
11169 node.value = self
11170 .current_tab()
11171 .map(|value| SemanticsValue::Text(value.to_string()));
11172 node.state.focused = ctx.is_focused();
11173 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
11174 ctx.push(node);
11175 if let Some(panel) = self.selected_panel() {
11176 panel.semantics(ctx);
11177 }
11178 }
11179
11180 fn accepts_focus(&self) -> bool {
11181 true
11182 }
11183
11184 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
11185 let theme = self.resolved_theme();
11186 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
11187 ctx.request_paint();
11188 ctx.request_semantics();
11189 }
11190
11191 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
11192 if let Some(panel) = self.selected_panel() {
11193 visitor.visit(panel);
11194 }
11195 }
11196
11197 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
11198 if let Some(panel) = self.selected_panel_mut() {
11199 visitor.visit(panel);
11200 }
11201 }
11202}
11203
11204pub struct Menu {
11205 theme: Box<DefaultTheme>,
11206 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
11207 name: String,
11208 items: Vec<MenuItem>,
11209 highlighted: Option<usize>,
11210 highlight_visual: Option<usize>,
11211 pressed: Option<usize>,
11212 press_visual: Option<usize>,
11213 highlight_animation: AnimatedScalar,
11214 press_animation: AnimatedScalar,
11215 focus_animation: AnimatedScalar,
11216 measured_width: f32,
11217 focus_on_pointer_down: bool,
11218 on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
11219 on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
11220}
11221
11222impl Menu {
11223 pub fn new(name: impl Into<String>) -> Self {
11224 Self {
11225 theme: Box::new(DefaultTheme::default()),
11226 theme_reader: None,
11227 name: name.into(),
11228 items: Vec::new(),
11229 highlighted: None,
11230 highlight_visual: None,
11231 pressed: None,
11232 press_visual: None,
11233 highlight_animation: AnimatedScalar::new(0.0),
11234 press_animation: AnimatedScalar::new(0.0),
11235 focus_animation: AnimatedScalar::new(0.0),
11236 measured_width: 220.0,
11237 focus_on_pointer_down: true,
11238 on_activate: None,
11239 on_activate_with_ctx: None,
11240 }
11241 }
11242
11243 pub fn theme(mut self, theme: DefaultTheme) -> Self {
11244 self.theme = Box::new(theme);
11245 self.theme_reader = None;
11246 self
11247 }
11248
11249 pub fn theme_when<F>(mut self, theme: F) -> Self
11250 where
11251 F: Fn() -> DefaultTheme + 'static,
11252 {
11253 self.theme_reader = Some(Box::new(theme));
11254 self
11255 }
11256
11257 pub fn item(mut self, item: MenuItem) -> Self {
11258 self.items.push(item);
11259 self
11260 }
11261
11262 pub fn items<I>(mut self, items: I) -> Self
11263 where
11264 I: IntoIterator<Item = MenuItem>,
11265 {
11266 self.items.extend(items);
11267 self
11268 }
11269
11270 pub fn highlighted(mut self, index: usize) -> Self {
11271 self.highlighted = Some(index);
11272 self.highlight_visual = Some(index);
11273 self.highlight_animation = AnimatedScalar::new(1.0);
11274 self
11275 }
11276
11277 pub fn on_activate<F>(mut self, on_activate: F) -> Self
11278 where
11279 F: FnMut(usize, MenuItem) + 'static,
11280 {
11281 self.on_activate = Some(Box::new(on_activate));
11282 self
11283 }
11284
11285 pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
11286 where
11287 F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
11288 {
11289 self.on_activate_with_ctx = Some(Box::new(on_activate));
11290 self
11291 }
11292
11293 pub fn focus_on_pointer_down(mut self, focus_on_pointer_down: bool) -> Self {
11294 self.focus_on_pointer_down = focus_on_pointer_down;
11295 self
11296 }
11297
11298 fn row_height(&self) -> f32 {
11299 let theme = self.resolved_theme();
11300 menu_row_height(&theme)
11301 }
11302
11303 fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
11304 let Some(item) = self.items.get(index).cloned() else {
11305 return;
11306 };
11307 if !item.enabled {
11308 return;
11309 }
11310 match (&mut self.on_activate, &mut self.on_activate_with_ctx) {
11311 (Some(on_activate), _) => on_activate(index, item),
11312 (None, Some(on_activate)) => on_activate(ctx, index, item),
11313 (None, None) => {}
11314 }
11315 }
11316
11317 fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
11318 if index >= self.items.len() {
11319 return None;
11320 }
11321 let theme = self.resolved_theme();
11322 let padding = theme.metrics.menu_padding;
11323 let x = bounds.x() + padding.left;
11324 let y = bounds.y() + padding.top + (index as f32 * self.row_height());
11325 Some(Rect::new(
11326 x,
11327 y,
11328 (bounds.width() - padding.left - padding.right).max(0.0),
11329 self.row_height(),
11330 ))
11331 }
11332
11333 fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
11334 self.items.iter().enumerate().find_map(|(index, _)| {
11335 self.item_rect(bounds, index)
11336 .filter(|rect| rect.contains(position))
11337 .map(|_| index)
11338 })
11339 }
11340
11341 fn move_highlight(&mut self, delta: isize, ctx: &mut EventCtx) {
11342 if self.items.is_empty() {
11343 return;
11344 }
11345
11346 let len = self.items.len() as isize;
11347 let start = self.highlighted.unwrap_or(0) as isize;
11348 let mut index = (start + delta).clamp(0, len - 1);
11349 while !self.items[index as usize].enabled {
11350 let next = (index + delta).clamp(0, len - 1);
11351 if next == index {
11352 break;
11353 }
11354 index = next;
11355 }
11356 self.set_highlighted(Some(index as usize), ctx);
11357 }
11358
11359 fn resolved_theme(&self) -> DefaultTheme {
11360 self.theme_reader
11361 .as_ref()
11362 .map(|theme| theme())
11363 .unwrap_or(*self.theme)
11364 }
11365
11366 fn set_highlighted(&mut self, highlighted: Option<usize>, ctx: &mut EventCtx) {
11367 if self.highlighted == highlighted {
11368 return;
11369 }
11370 let theme = self.resolved_theme();
11371 self.highlighted = highlighted;
11372 if let Some(index) = highlighted {
11373 self.highlight_visual = Some(index);
11374 self.highlight_animation = AnimatedScalar::new(0.0);
11375 set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
11376 } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
11377 self.highlight_visual = None;
11378 }
11379 ctx.request_paint();
11380 ctx.request_semantics();
11381 }
11382
11383 fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
11384 if self.pressed == pressed {
11385 return;
11386 }
11387 let theme = self.resolved_theme();
11388 self.pressed = pressed;
11389 if let Some(index) = pressed {
11390 self.press_visual = Some(index);
11391 self.press_animation = AnimatedScalar::new(0.0);
11392 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
11393 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
11394 self.press_visual = None;
11395 }
11396 ctx.request_paint();
11397 ctx.request_semantics();
11398 }
11399
11400 fn highlight_amount_for(&self, index: usize) -> f32 {
11401 if self.highlight_visual == Some(index) {
11402 self.highlight_animation.value
11403 } else {
11404 0.0
11405 }
11406 }
11407
11408 fn press_amount_for(&self, index: usize) -> f32 {
11409 if self.press_visual == Some(index) {
11410 self.press_animation.value
11411 } else {
11412 0.0
11413 }
11414 }
11415
11416 fn advance_animations(&mut self, time: f64) -> bool {
11417 let highlight_animating = self.highlight_animation.advance(time);
11418 if !highlight_animating
11419 && self.highlighted.is_none()
11420 && self.highlight_animation.value <= AnimatedScalar::EPSILON
11421 {
11422 self.highlight_visual = None;
11423 }
11424
11425 let press_animating = self.press_animation.advance(time);
11426 if !press_animating
11427 && self.pressed.is_none()
11428 && self.press_animation.value <= AnimatedScalar::EPSILON
11429 {
11430 self.press_visual = None;
11431 }
11432
11433 highlight_animating | press_animating | self.focus_animation.advance(time)
11434 }
11435}
11436
11437impl Widget for Menu {
11438 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
11439 match event {
11440 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
11441 self.set_highlighted(self.item_at(ctx.bounds(), pointer.position), ctx);
11442 }
11443 Event::Pointer(pointer)
11444 if pointer.kind == PointerEventKind::Down
11445 && pointer.button == Some(PointerButton::Primary) =>
11446 {
11447 let highlighted = self.item_at(ctx.bounds(), pointer.position);
11448 self.set_highlighted(highlighted, ctx);
11449 self.set_pressed(
11450 highlighted
11451 .filter(|index| self.items.get(*index).is_some_and(|item| item.enabled)),
11452 ctx,
11453 );
11454 if self.focus_on_pointer_down {
11455 ctx.request_focus();
11456 }
11457 ctx.request_pointer_capture(pointer.pointer_id);
11458 ctx.set_handled();
11459 }
11460 Event::Pointer(pointer)
11461 if pointer.kind == PointerEventKind::Up
11462 && pointer.button == Some(PointerButton::Primary) =>
11463 {
11464 let highlighted = self.item_at(ctx.bounds(), pointer.position);
11465 if let Some(index) = self
11466 .pressed
11467 .zip(highlighted)
11468 .filter(|(left, right)| left == right)
11469 .map(|(index, _)| index)
11470 {
11471 self.activate(ctx, index);
11472 }
11473 self.set_highlighted(highlighted, ctx);
11474 self.set_pressed(None, ctx);
11475 ctx.release_pointer_capture(pointer.pointer_id);
11476 ctx.set_handled();
11477 }
11478 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
11479 if self.pressed.is_some() {
11480 self.set_pressed(None, ctx);
11481 ctx.release_pointer_capture(pointer.pointer_id);
11482 ctx.set_handled();
11483 }
11484 }
11485 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
11486 match key.key.as_str() {
11487 "ArrowDown" => self.move_highlight(1, ctx),
11488 "ArrowUp" => self.move_highlight(-1, ctx),
11489 "Home" => {
11490 self.set_highlighted(self.items.iter().position(|item| item.enabled), ctx);
11491 }
11492 "End" => {
11493 self.set_highlighted(self.items.iter().rposition(|item| item.enabled), ctx);
11494 }
11495 "Enter" | " " => {
11496 if let Some(index) = self.highlighted {
11497 self.activate(ctx, index);
11498 }
11499 }
11500 _ => return,
11501 }
11502 ctx.request_paint();
11503 ctx.request_semantics();
11504 ctx.set_handled();
11505 }
11506 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
11507 if self.advance_animations(*time) {
11508 ctx.request_animation_frame();
11509 }
11510 ctx.request_paint();
11511 }
11512 _ => {}
11513 }
11514 }
11515
11516 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
11517 let theme = self.resolved_theme();
11518 let label_style = theme.body_text_style();
11519 let shortcut_style = theme.placeholder_text_style();
11520 let mut width: f32 = 0.0;
11521 for item in &self.items {
11522 let label = measure_text(ctx, item.label(), &label_style).width;
11523 let shortcut = item
11524 .shortcut
11525 .as_ref()
11526 .map(|text| measure_text(ctx, text, &shortcut_style).width)
11527 .unwrap_or(0.0);
11528 width = width.max(
11529 label
11530 + shortcut
11531 + theme.metrics.menu_item_padding.left
11532 + theme.metrics.menu_item_padding.right
11533 + theme.metrics.menu_shortcut_width,
11534 );
11535 }
11536 self.measured_width = width.max(220.0);
11537 let height = themed_menu_height_for_rows(&theme, self.row_height(), self.items.len());
11538 constraints.clamp(Size::new(
11539 self.measured_width,
11540 height.max(themed_menu_height_for_rows(&theme, self.row_height(), 1)),
11541 ))
11542 }
11543
11544 fn paint(&self, ctx: &mut PaintCtx) {
11545 let theme = self.resolved_theme();
11546 let palette = theme.palette;
11547 let metrics = theme.metrics;
11548 let interaction = theme.interaction;
11549 let item_padding = metrics.menu_item_padding;
11550
11551 let surface_radius = metrics.corner_radius + 2.0;
11554 paint_theme_shadow(
11555 ctx,
11556 ctx.bounds(),
11557 [surface_radius; 4],
11558 &theme.shadows.box_shadow.lg,
11559 );
11560
11561 draw_control_frame(
11562 ctx,
11563 ctx.bounds(),
11564 surface_radius,
11565 metrics,
11566 palette.surface_raised,
11567 palette.border,
11568 (self.focus_animation.value > AnimatedScalar::EPSILON).then_some(
11569 palette
11570 .focus_ring
11571 .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
11572 ),
11573 );
11574
11575 for (index, item) in self.items.iter().enumerate() {
11576 let Some(row) = self.item_rect(ctx.bounds(), index) else {
11577 continue;
11578 };
11579
11580 if item.separator_before {
11581 let line = Rect::new(
11582 row.x(),
11583 row.y() - (metrics.menu_padding.top * 0.5),
11584 row.width(),
11585 1.0,
11586 );
11587 ctx.fill(rounded_rect_path(line, 0.5), palette.border);
11588 }
11589
11590 let highlighted = self.highlighted == Some(index);
11591 let highlight_amount = self.highlight_amount_for(index);
11592 let press_amount = self.press_amount_for(index);
11593 let label_style = theme.text_style(item.text_color(&theme));
11594 let label_slot = Rect::new(
11595 row.x() + item_padding.left,
11596 row.y(),
11597 (row.width()
11598 - item_padding.left
11599 - item_padding.right
11600 - item
11601 .shortcut
11602 .as_ref()
11603 .map(|_| metrics.menu_shortcut_width)
11604 .unwrap_or(0.0))
11605 .max(0.0),
11606 row.height(),
11607 );
11608 if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
11609 let highlight_background = mix_color(
11610 palette.control,
11611 palette.accent,
11612 interaction.selected_blend * highlight_amount,
11613 );
11614 let background = if press_amount > 0.0 {
11615 mix_color(
11616 highlight_background,
11617 palette.control_active,
11618 interaction.pressed_blend * press_amount,
11619 )
11620 } else {
11621 highlight_background
11622 };
11623 ctx.fill(
11624 rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
11625 background,
11626 );
11627 }
11628
11629 ctx.push_clip_rect(label_slot);
11630 paint_aligned_text(
11631 ctx,
11632 label_slot,
11633 &item.label,
11634 &label_style,
11635 label_style.line_height,
11636 0.0,
11637 );
11638 ctx.pop_clip();
11639
11640 if let Some(shortcut) = &item.shortcut {
11641 let shortcut_style = theme.placeholder_text_style();
11642 let shortcut_slot = Rect::new(
11643 row.max_x() - item_padding.right - metrics.menu_shortcut_width,
11644 row.y(),
11645 metrics.menu_shortcut_width,
11646 row.height(),
11647 );
11648 ctx.push_clip_rect(shortcut_slot);
11649 paint_aligned_text(
11650 ctx,
11651 shortcut_slot,
11652 shortcut,
11653 &shortcut_style,
11654 shortcut_style.line_height,
11655 1.0,
11656 );
11657 ctx.pop_clip();
11658 }
11659 }
11660 }
11661
11662 fn semantics(&self, ctx: &mut SemanticsCtx) {
11663 let state = SemanticsState {
11664 focused: ctx.is_focused(),
11665 ..SemanticsState::default()
11666 };
11667 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Menu, ctx.bounds());
11668 node.name = Some(self.name.clone());
11669 node.state = state;
11670 node.value = self
11671 .highlighted
11672 .and_then(|index| self.items.get(index))
11673 .map(|item| SemanticsValue::Text(item.label.clone()));
11674 node.actions = vec![
11675 SemanticsAction::Focus,
11676 SemanticsAction::SetValue,
11677 SemanticsAction::Activate,
11678 ];
11679 ctx.push(node);
11680 for (index, item) in self.items.iter().enumerate() {
11681 let Some(row) = self.item_rect(ctx.bounds(), index) else {
11682 continue;
11683 };
11684 ctx.push(menu_item_semantics_node(
11685 ctx.widget_id(),
11686 index,
11687 item,
11688 row,
11689 self.highlighted == Some(index),
11690 ));
11691 }
11692 }
11693
11694 fn accepts_focus(&self) -> bool {
11695 true
11696 }
11697
11698 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
11699 let theme = self.resolved_theme();
11700 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
11701 ctx.request_paint();
11702 ctx.request_semantics();
11703 }
11704}
11705
11706type AnimatedScalar = MotionScalar;
11707
11708fn request_child_invalidation(ctx: &mut EventCtx, widget_id: WidgetId, kind: InvalidationKind) {
11709 ctx.request(InvalidationRequest::new(
11710 InvalidationTarget::Widget(widget_id),
11711 kind,
11712 ));
11713}
11714
11715fn tooltip_fallback_measurement(theme: &DefaultTheme) -> TextMeasurement {
11716 TextMeasurement {
11717 width: 120.0,
11718 height: theme.typography.body_line_height,
11719 bounds: Rect::new(0.0, 0.0, 120.0, theme.typography.body_line_height),
11720 ascent: theme.typography.body_font_size,
11721 descent: 0.0,
11722 cap_height: Some(theme.typography.body_font_size),
11723 }
11724}
11725
11726fn tooltip_bubble_rect(
11727 trigger_bounds: Rect,
11728 measurement: Option<TextMeasurement>,
11729 theme: &DefaultTheme,
11730 placement: TooltipPlacement,
11731 alignment: TooltipAlignment,
11732 viewport: Rect,
11733) -> (Rect, TooltipPlacement) {
11734 let measurement = measurement.unwrap_or_else(|| tooltip_fallback_measurement(theme));
11735 let padding = theme.metrics.tooltip_padding;
11736 let width =
11737 (measurement.width + padding.left + padding.right).max(theme.metrics.tooltip_min_width);
11738 let height =
11739 measurement.height.max(theme.typography.body_line_height) + padding.top + padding.bottom;
11740 let side = match placement {
11741 TooltipPlacement::Above => OverlaySide::Top,
11742 TooltipPlacement::Below => OverlaySide::Bottom,
11743 };
11744 let alignment = match alignment {
11745 TooltipAlignment::Start => OverlayAlignment::Start,
11746 TooltipAlignment::Center => OverlayAlignment::Center,
11747 TooltipAlignment::End => OverlayAlignment::End,
11748 };
11749 let result = place_overlay(
11750 &OverlayPlacementRequest::new(
11751 trigger_bounds,
11752 Size::new(width, height),
11753 viewport,
11754 OverlayPlacement::new(side, alignment),
11755 )
11756 .gap(theme.metrics.tooltip_gap)
11757 .margin(theme.metrics.tooltip_gap.max(4.0)),
11758 );
11759 let resolved = if result.placement.side == OverlaySide::Top {
11760 TooltipPlacement::Above
11761 } else {
11762 TooltipPlacement::Below
11763 };
11764 (result.bounds, resolved)
11765}
11766
11767#[derive(Debug, Clone)]
11768struct TooltipPresentationState {
11769 theme: DefaultTheme,
11770 text: String,
11771 placement: TooltipPlacement,
11772 resolved_placement: TooltipPlacement,
11773 alignment: TooltipAlignment,
11774 measurement: Option<TextMeasurement>,
11775 hovered: bool,
11776 trigger_bounds: Rect,
11777 bubble_bounds: Rect,
11778 reveal: AnimatedScalar,
11779}
11780
11781impl TooltipPresentationState {
11782 fn new(text: String) -> Self {
11783 Self {
11784 theme: DefaultTheme::default(),
11785 text,
11786 placement: TooltipPlacement::Above,
11787 resolved_placement: TooltipPlacement::Above,
11788 alignment: TooltipAlignment::Center,
11789 measurement: None,
11790 hovered: false,
11791 trigger_bounds: Rect::ZERO,
11792 bubble_bounds: Rect::ZERO,
11793 reveal: AnimatedScalar::new(0.0),
11794 }
11795 }
11796
11797 fn is_presented(&self) -> bool {
11798 self.reveal.is_presented()
11799 }
11800
11801 fn layer_properties(&self) -> LayerProperties {
11802 let direction = match self.resolved_placement {
11803 TooltipPlacement::Above => -1.0,
11804 TooltipPlacement::Below => 1.0,
11805 };
11806 LayerProperties {
11807 opacity: self.reveal.value,
11808 translation: Vector::new(
11809 0.0,
11810 self.theme.metrics.tooltip_reveal_offset * (1.0 - self.reveal.value) * direction,
11811 ),
11812 }
11813 }
11814}
11815
11816struct TooltipOverlay {
11817 state: Rc<RefCell<TooltipPresentationState>>,
11818}
11819
11820impl TooltipOverlay {
11821 fn new(state: Rc<RefCell<TooltipPresentationState>>) -> Self {
11822 Self { state }
11823 }
11824}
11825
11826impl Widget for TooltipOverlay {
11827 fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
11828 let state = self.state.borrow();
11829 if !state.is_presented() {
11830 return Size::ZERO;
11831 }
11832 state.bubble_bounds.size
11833 }
11834
11835 fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
11836 self.state.borrow_mut().bubble_bounds = bounds;
11837 }
11838
11839 fn paint(&self, ctx: &mut PaintCtx) {
11840 let state = self.state.borrow();
11841 if !state.is_presented() {
11842 return;
11843 }
11844
11845 let bubble = ctx.bounds();
11846 let metrics = state.theme.metrics;
11847 paint_theme_shadow(
11849 ctx,
11850 bubble,
11851 [metrics.corner_radius; 4],
11852 &state.theme.shadows.box_shadow.sm,
11853 );
11854 draw_control_frame(
11855 ctx,
11856 bubble,
11857 metrics.corner_radius,
11858 metrics,
11859 state.theme.surfaces.tooltip,
11860 state.theme.surfaces.tooltip_border,
11861 None,
11862 );
11863 let tail = tooltip_tail(state.trigger_bounds, bubble, state.resolved_placement);
11864 ctx.fill(tail, state.theme.surfaces.tooltip);
11865 let text_style = text_token_style(
11866 &state.theme,
11867 state.theme.text.sm,
11868 state.theme.surfaces.tooltip_text,
11869 );
11870 let text_slot = inset_rect(bubble, metrics.tooltip_padding);
11871 ctx.push_clip_rect(text_slot);
11872 paint_aligned_text(
11873 ctx,
11874 text_slot,
11875 &state.text,
11876 &text_style,
11877 text_style.line_height,
11878 0.0,
11879 );
11880 ctx.pop_clip();
11881 }
11882
11883 fn layer_options(&self) -> LayerOptions {
11884 let presented = self.state.borrow().is_presented();
11885 LayerOptions {
11886 paint_boundary: PaintBoundaryMode::Explicit,
11887 composition_mode: if presented {
11888 LayerCompositionMode::Overlay
11889 } else {
11890 LayerCompositionMode::Normal
11891 },
11892 }
11893 }
11894
11895 fn layer_properties(&self) -> LayerProperties {
11896 self.state.borrow().layer_properties()
11897 }
11898
11899 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
11900 self.state
11901 .borrow()
11902 .is_presented()
11903 .then_some(StackSurfaceOptions {
11904 transient: true,
11905 hit_test: false,
11906 ..StackSurfaceOptions::default()
11907 })
11908 }
11909}
11910
11911pub struct Tooltip {
11912 child: SingleChild,
11913 overlay: SingleChild,
11914 state: Rc<RefCell<TooltipPresentationState>>,
11915}
11916
11917impl Tooltip {
11918 pub fn new<W>(text: impl Into<String>, child: W) -> Self
11919 where
11920 W: Widget + 'static,
11921 {
11922 let state = Rc::new(RefCell::new(TooltipPresentationState::new(text.into())));
11923 Self {
11924 child: SingleChild::new(child),
11925 overlay: SingleChild::new(TooltipOverlay::new(Rc::clone(&state))),
11926 state,
11927 }
11928 }
11929
11930 pub fn theme(self, theme: DefaultTheme) -> Self {
11931 self.state.borrow_mut().theme = theme;
11932 self
11933 }
11934
11935 pub fn placement(self, placement: TooltipPlacement) -> Self {
11936 self.state.borrow_mut().placement = placement;
11937 self
11938 }
11939
11940 pub fn alignment(self, alignment: TooltipAlignment) -> Self {
11941 self.state.borrow_mut().alignment = alignment;
11942 self
11943 }
11944
11945 fn set_hovered(&mut self, ctx: &mut EventCtx, hovered: bool) {
11946 let overlay_id = self.overlay.child().id();
11947 let mut state = self.state.borrow_mut();
11948 if state.hovered == hovered {
11949 return;
11950 }
11951 let was_presented = state.is_presented();
11952 let motion = state.theme.motion;
11953 state.hovered = hovered;
11954 let should_animate = state.reveal.set_target(
11955 hovered as u8 as f32,
11956 ctx.current_time(),
11957 motion.entrance_duration(),
11958 motion.entrance_easing(),
11959 );
11960 let is_presented = state.is_presented();
11961 drop(state);
11962
11963 if was_presented != is_presented {
11964 ctx.request_measure();
11965 request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
11966 }
11967 if should_animate {
11968 ctx.request_animation_frame();
11969 }
11970 ctx.request_semantics();
11971 }
11972}
11973
11974impl Widget for Tooltip {
11975 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
11976 match event {
11977 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
11978 self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11979 }
11980 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
11981 self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11982 }
11983 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
11984 self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11985 }
11986 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
11987 let overlay_id = self.overlay.child().id();
11988 let mut state = self.state.borrow_mut();
11989 let was_presented = state.is_presented();
11990 let previous = state.reveal.value;
11991 let animating = state.reveal.advance(*time);
11992 let changed = state.reveal.changed_since(previous);
11993 let is_presented = state.is_presented();
11994 drop(state);
11995
11996 if changed {
11997 request_child_invalidation(ctx, overlay_id, InvalidationKind::Transform);
11998 request_child_invalidation(ctx, overlay_id, InvalidationKind::Effect);
11999 }
12000 if was_presented != is_presented {
12001 ctx.request_measure();
12002 request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
12003 }
12004 if animating {
12005 ctx.request_animation_frame();
12006 }
12007 ctx.set_handled();
12008 }
12009 _ => {}
12010 }
12011 }
12012
12013 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
12014 let mut state = self.state.borrow_mut();
12015 let text_style = text_token_style(
12016 &state.theme,
12017 state.theme.text.sm,
12018 state.theme.surfaces.tooltip_text,
12019 );
12020 state.measurement = Some(measure_text(ctx, &state.text, &text_style));
12021 drop(state);
12022 self.child.measure(ctx, constraints)
12023 }
12024
12025 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
12026 let trigger_bounds =
12027 Rect::from_origin_size(bounds.origin, self.child.child().measured_size());
12028 self.child.arrange(ctx, trigger_bounds);
12029
12030 let mut state = self.state.borrow_mut();
12031 state.trigger_bounds = trigger_bounds;
12032 let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
12033 let (bubble_bounds, resolved_placement) = tooltip_bubble_rect(
12034 trigger_bounds,
12035 state.measurement,
12036 &state.theme,
12037 state.placement,
12038 state.alignment,
12039 viewport,
12040 );
12041 state.bubble_bounds = bubble_bounds;
12042 state.resolved_placement = resolved_placement;
12043 let overlay_bounds = if state.is_presented() {
12044 state.bubble_bounds
12045 } else {
12046 Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
12047 };
12048 drop(state);
12049 self.overlay.arrange(ctx, overlay_bounds);
12050 }
12051
12052 fn paint(&self, ctx: &mut PaintCtx) {
12053 self.child.paint(ctx);
12054 self.overlay.paint(ctx);
12055 }
12056
12057 fn overlay_options(&self) -> Option<OverlayOptions> {
12058 self.state.borrow().is_presented().then_some(
12059 OverlayOptions::new(OverlayKind::Tooltip)
12060 .dismiss(OverlayDismissPolicy::NONE)
12061 .focus(OverlayFocusBehavior::NONE),
12062 )
12063 }
12064
12065 fn semantics(&self, ctx: &mut SemanticsCtx) {
12066 self.child.semantics(ctx);
12067 let state = self.state.borrow();
12068 if state.hovered {
12069 let mut node =
12070 SemanticsNode::new(ctx.widget_id(), SemanticsRole::Tooltip, state.bubble_bounds);
12071 node.name = Some(state.text.clone());
12072 ctx.push(node);
12073 }
12074 }
12075
12076 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12077 self.child.visit_children(visitor);
12078 if self.state.borrow().is_presented() {
12079 self.overlay.visit_children(visitor);
12080 }
12081 }
12082
12083 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12084 self.child.visit_children_mut(visitor);
12085 if self.state.borrow().is_presented() {
12086 self.overlay.visit_children_mut(visitor);
12087 }
12088 }
12089}
12090
12091#[derive(Debug, Clone, Copy, PartialEq)]
12092struct PopoverVisuals {
12093 background: Color,
12094 border: Color,
12095 focus_ring: Option<Color>,
12096 surface_style: Option<ResolvedHdrStyle>,
12097 arrival_effect: Option<ResolvedEffectStyle>,
12098}
12099
12100#[derive(Debug, Clone)]
12101struct PopoverSurfaceState {
12102 theme: DefaultTheme,
12103 frame_rect: Rect,
12104 arrival_active: bool,
12105 reveal: AnimatedScalar,
12106 focus_animation: AnimatedScalar,
12107}
12108
12109impl PopoverSurfaceState {
12110 fn new() -> Self {
12111 Self {
12112 theme: DefaultTheme::default(),
12113 frame_rect: Rect::ZERO,
12114 arrival_active: false,
12115 reveal: AnimatedScalar::new(0.0),
12116 focus_animation: AnimatedScalar::new(0.0),
12117 }
12118 }
12119
12120 fn is_presented(&self) -> bool {
12121 self.reveal.is_presented()
12122 }
12123
12124 fn arrival_duration(&self) -> f64 {
12125 (0.18 / self.theme.hdr.effects.pulse.speed.max(0.25) as f64).clamp(0.10, 0.28)
12126 }
12127
12128 fn layer_properties(&self) -> LayerProperties {
12129 LayerProperties {
12130 opacity: self.reveal.value,
12131 translation: Vector::new(
12132 0.0,
12133 -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
12134 ),
12135 }
12136 }
12137
12138 fn resolved_visuals(&self) -> PopoverVisuals {
12139 let palette = self.theme.palette;
12140
12141 if !self.is_presented() || matches!(self.theme.hdr.mode, HdrThemeMode::Disabled) {
12142 return PopoverVisuals {
12143 background: palette.surface_raised,
12144 border: palette.border,
12145 focus_ring: Some(palette.focus_ring),
12146 surface_style: None,
12147 arrival_effect: None,
12148 };
12149 }
12150
12151 let surface_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
12152 &self.theme.hdr,
12153 WidgetColorRole::SurfaceElevated,
12154 WidgetLuminanceRole::Standard,
12155 WidgetMaterialRole::Raised,
12156 self.arrival_active.then_some(WidgetEffectRole::Pulse),
12157 ));
12158 let border_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
12159 &self.theme.hdr,
12160 WidgetColorRole::SurfaceOutline,
12161 WidgetLuminanceRole::Standard,
12162 WidgetMaterialRole::Flat,
12163 None,
12164 ));
12165
12166 PopoverVisuals {
12167 background: surface_style.color,
12168 border: border_style.color,
12169 focus_ring: Some(border_style.color.with_alpha(palette.focus_ring.alpha)),
12170 surface_style: Some(surface_style),
12171 arrival_effect: surface_style.effect,
12172 }
12173 }
12174}
12175
12176struct PopoverSurface {
12177 content: SingleChild,
12178 state: Rc<RefCell<PopoverSurfaceState>>,
12179}
12180
12181impl PopoverSurface {
12182 fn new<C>(state: Rc<RefCell<PopoverSurfaceState>>, content: C) -> Self
12183 where
12184 C: Widget + 'static,
12185 {
12186 Self {
12187 content: SingleChild::new(content),
12188 state,
12189 }
12190 }
12191}
12192
12193impl Widget for PopoverSurface {
12194 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
12195 let state = self.state.borrow();
12196 if !state.is_presented() {
12197 return Size::ZERO;
12198 }
12199 let padding = state.theme.metrics.popover_padding;
12200 drop(state);
12201
12202 let content_constraints = Constraints::new(
12203 Size::ZERO,
12204 Size::new(
12205 if constraints.max.width.is_finite() {
12206 (constraints.max.width - padding.left - padding.right).max(0.0)
12207 } else {
12208 f32::INFINITY
12209 },
12210 if constraints.max.height.is_finite() {
12211 (constraints.max.height - padding.top - padding.bottom).max(0.0)
12212 } else {
12213 f32::INFINITY
12214 },
12215 ),
12216 );
12217 let content_size = self.content.measure(ctx, content_constraints);
12218 Size::new(
12219 content_size.width + padding.left + padding.right,
12220 content_size.height + padding.top + padding.bottom,
12221 )
12222 }
12223
12224 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
12225 let state = self.state.borrow();
12226 if !state.is_presented() {
12227 drop(state);
12228 self.content
12229 .arrange(ctx, Rect::from_origin_size(bounds.origin, Size::ZERO));
12230 return;
12231 }
12232 let padding = state.theme.metrics.popover_padding;
12233 drop(state);
12234 let content_size = self.content.child().measured_size();
12235 self.content.arrange(
12236 ctx,
12237 Rect::new(
12238 bounds.x() + padding.left,
12239 bounds.y() + padding.top,
12240 content_size.width,
12241 content_size.height,
12242 ),
12243 );
12244 }
12245
12246 fn paint(&self, ctx: &mut PaintCtx) {
12247 let state = self.state.borrow();
12248 if !state.is_presented() {
12249 return;
12250 }
12251
12252 let rect = ctx.bounds();
12253 let metrics = state.theme.metrics;
12254 let visuals = state.resolved_visuals();
12255 let surface_radius = metrics.corner_radius + 2.0;
12257 paint_theme_shadow(
12258 ctx,
12259 rect,
12260 [surface_radius; 4],
12261 &state.theme.shadows.box_shadow.md,
12262 );
12263 draw_control_frame(
12264 ctx,
12265 rect,
12266 surface_radius,
12267 metrics,
12268 visuals.background,
12269 visuals.border,
12270 None,
12271 );
12272 if let Some(arrival_effect) = visuals.arrival_effect {
12273 draw_popover_arrival_overlay(
12274 ctx,
12275 rect,
12276 metrics,
12277 visuals.background,
12278 visuals.border,
12279 arrival_effect,
12280 );
12281 }
12282 drop(state);
12283 self.content.paint(ctx);
12284 }
12285
12286 fn layer_options(&self) -> LayerOptions {
12287 let presented = self.state.borrow().is_presented();
12288 LayerOptions {
12289 paint_boundary: PaintBoundaryMode::Explicit,
12290 composition_mode: if presented {
12291 LayerCompositionMode::Overlay
12292 } else {
12293 LayerCompositionMode::Normal
12294 },
12295 }
12296 }
12297
12298 fn layer_properties(&self) -> LayerProperties {
12299 self.state.borrow().layer_properties()
12300 }
12301
12302 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
12303 self.state
12304 .borrow()
12305 .is_presented()
12306 .then_some(StackSurfaceOptions {
12307 transient: true,
12308 ..StackSurfaceOptions::default()
12309 })
12310 }
12311
12312 fn semantics(&self, ctx: &mut SemanticsCtx) {
12313 self.content.semantics(ctx);
12314 }
12315
12316 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12317 self.content.visit_children(visitor);
12318 }
12319
12320 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12321 self.content.visit_children_mut(visitor);
12322 }
12323}
12324
12325struct PopoverFocusSurface {
12326 state: Rc<RefCell<PopoverSurfaceState>>,
12327}
12328
12329impl PopoverFocusSurface {
12330 fn new(state: Rc<RefCell<PopoverSurfaceState>>) -> Self {
12331 Self { state }
12332 }
12333}
12334
12335impl Widget for PopoverFocusSurface {
12336 fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
12337 let state = self.state.borrow();
12338 if state.is_presented() {
12339 state.frame_rect.size
12340 } else {
12341 Size::ZERO
12342 }
12343 }
12344
12345 fn paint(&self, ctx: &mut PaintCtx) {
12346 let state = self.state.borrow();
12347 if !state.is_presented() || !state.focus_animation.is_presented() {
12348 return;
12349 }
12350
12351 let Some(focus_ring) = state.resolved_visuals().focus_ring else {
12352 return;
12353 };
12354 let progress = state.focus_animation.value;
12355 if progress <= AnimatedScalar::EPSILON {
12356 return;
12357 }
12358
12359 let metrics = state.theme.metrics;
12360 draw_focus_ring_frame(
12361 ctx,
12362 ctx.bounds(),
12363 metrics.corner_radius + 2.0,
12364 metrics,
12365 focus_ring.with_alpha(focus_ring.alpha * progress),
12366 );
12367 }
12368
12369 fn layer_options(&self) -> LayerOptions {
12370 LayerOptions {
12371 paint_boundary: PaintBoundaryMode::Explicit,
12372 composition_mode: LayerCompositionMode::Normal,
12373 }
12374 }
12375
12376 fn layer_properties(&self) -> LayerProperties {
12377 self.state.borrow().layer_properties()
12378 }
12379
12380 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
12381 let state = self.state.borrow();
12382 (state.is_presented() && state.focus_animation.is_presented()).then_some(
12383 StackSurfaceOptions {
12384 transient: true,
12385 hit_test: false,
12386 ..StackSurfaceOptions::default()
12387 },
12388 )
12389 }
12390}
12391
12392#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12393pub enum PopoverAlignment {
12394 #[default]
12395 Start,
12396 End,
12397}
12398
12399pub struct Popover {
12400 name: String,
12401 trigger: SingleChild,
12402 surface: SingleChild,
12403 focus_surface: SingleChild,
12404 open: bool,
12405 open_reader: Option<Box<dyn Fn() -> bool>>,
12406 on_open_change: Option<Box<dyn FnMut(bool)>>,
12407 alignment: PopoverAlignment,
12408 gap: f32,
12409 arrival_timer: Option<TimerToken>,
12410 state: Rc<RefCell<PopoverSurfaceState>>,
12411}
12412
12413impl Popover {
12414 pub fn new<T, C>(name: impl Into<String>, trigger: T, content: C) -> Self
12415 where
12416 T: Widget + 'static,
12417 C: Widget + 'static,
12418 {
12419 let state = Rc::new(RefCell::new(PopoverSurfaceState::new()));
12420 Self {
12421 name: name.into(),
12422 trigger: SingleChild::new(trigger),
12423 surface: SingleChild::new(PopoverSurface::new(Rc::clone(&state), content)),
12424 focus_surface: SingleChild::new(PopoverFocusSurface::new(Rc::clone(&state))),
12425 open: false,
12426 open_reader: None,
12427 on_open_change: None,
12428 alignment: PopoverAlignment::Start,
12429 gap: DefaultTheme::default().metrics.popover_gap,
12430 arrival_timer: None,
12431 state,
12432 }
12433 }
12434
12435 pub fn theme(mut self, theme: DefaultTheme) -> Self {
12436 self.gap = theme.metrics.popover_gap;
12437 self.state.borrow_mut().theme = theme;
12438 self
12439 }
12440
12441 pub fn open(mut self, open: bool) -> Self {
12442 self.open = open;
12443 self.open_reader = None;
12444 {
12445 let mut state = self.state.borrow_mut();
12446 state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
12447 }
12448 self
12449 }
12450
12451 pub fn open_when<F>(mut self, open: F) -> Self
12452 where
12453 F: Fn() -> bool + 'static,
12454 {
12455 self.open_reader = Some(Box::new(open));
12456 self
12457 }
12458
12459 pub fn on_open_change<F>(mut self, on_open_change: F) -> Self
12460 where
12461 F: FnMut(bool) + 'static,
12462 {
12463 self.on_open_change = Some(Box::new(on_open_change));
12464 self
12465 }
12466
12467 pub fn alignment(mut self, alignment: PopoverAlignment) -> Self {
12471 self.alignment = alignment;
12472 self
12473 }
12474
12475 fn sync_external_open(&mut self) {
12476 let Some(open) = self.open_reader.as_ref().map(|open| open()) else {
12477 return;
12478 };
12479 if self.open == open {
12480 return;
12481 }
12482 self.open = open;
12483 let mut state = self.state.borrow_mut();
12484 state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
12485 state.arrival_active = false;
12486 }
12487
12488 fn start_arrival(&mut self, ctx: &mut EventCtx) {
12489 if let Some(token) = self.arrival_timer.take() {
12490 ctx.cancel_timer(token);
12491 }
12492
12493 let mut state = self.state.borrow_mut();
12494 state.arrival_active = !matches!(state.theme.hdr.mode, HdrThemeMode::Disabled)
12495 && state.theme.hdr.effects.pulse.intensity > 0.0;
12496 if state.arrival_active {
12497 self.arrival_timer = Some(ctx.schedule_timer_after(state.arrival_duration()));
12498 }
12499 }
12500
12501 fn stop_arrival(&mut self, ctx: &mut EventCtx) {
12502 self.state.borrow_mut().arrival_active = false;
12503 if let Some(token) = self.arrival_timer.take() {
12504 ctx.cancel_timer(token);
12505 }
12506 }
12507
12508 fn trigger_rect(&self) -> Rect {
12509 self.trigger.child().bounds()
12510 }
12511
12512 fn content_rect(&self) -> Rect {
12513 self.state.borrow().frame_rect
12514 }
12515
12516 fn is_inside_open_regions(&self, position: Point) -> bool {
12517 self.trigger_rect().contains(position)
12518 || (self.open && self.content_rect().contains(position))
12519 }
12520
12521 fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
12522 if self.open == open {
12523 return;
12524 }
12525
12526 if open {
12527 self.start_arrival(ctx);
12528 } else {
12529 self.stop_arrival(ctx);
12530 }
12531
12532 self.open = open;
12533 if let Some(on_open_change) = &mut self.on_open_change {
12534 on_open_change(open);
12535 }
12536 let surface_id = self.surface.child().id();
12537 let focus_surface_id = self.focus_surface.child().id();
12538 let mut state = self.state.borrow_mut();
12539 let was_presented = state.is_presented();
12540 let motion = state.theme.motion;
12541 let should_animate = state.reveal.set_target(
12542 open as u8 as f32,
12543 ctx.current_time(),
12544 motion.entrance_duration(),
12545 motion.entrance_easing(),
12546 );
12547 let is_presented = state.is_presented();
12548 drop(state);
12549
12550 if open || was_presented != is_presented {
12551 ctx.request_measure();
12552 request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
12553 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12554 }
12555 if should_animate {
12556 ctx.request_animation_frame();
12557 }
12558 ctx.request_semantics();
12559 }
12560}
12561
12562impl Widget for Popover {
12563 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
12564 if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
12565 self.set_open(ctx, false);
12566 ctx.set_handled();
12567 }
12568 }
12569
12570 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
12571 match event {
12572 Event::Pointer(pointer)
12573 if pointer.kind == PointerEventKind::Down
12574 && pointer.button == Some(PointerButton::Primary)
12575 && self.trigger_rect().contains(pointer.position) =>
12576 {
12577 let next = !self.open;
12578 self.set_open(ctx, next);
12579 ctx.request_focus();
12580 ctx.set_handled();
12581 }
12582 Event::Pointer(pointer)
12583 if pointer.kind == PointerEventKind::Down
12584 && pointer.button == Some(PointerButton::Primary)
12585 && self.open
12586 && !self.is_inside_open_regions(pointer.position) =>
12587 {
12588 self.set_open(ctx, false);
12589 }
12590 Event::Keyboard(key)
12591 if ctx.is_focused()
12592 && key.state == KeyState::Pressed
12593 && key.key == "Escape"
12594 && self.open =>
12595 {
12596 self.set_open(ctx, false);
12597 ctx.set_handled();
12598 }
12599 Event::Keyboard(key)
12600 if ctx.is_focused()
12601 && key.state == KeyState::Pressed
12602 && matches!(key.key.as_str(), "Enter" | " ") =>
12603 {
12604 self.set_open(ctx, !self.open);
12605 ctx.set_handled();
12606 }
12607 Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
12608 let open = match semantics.action {
12609 sui_core::SemanticsActionRequest::Expand => Some(true),
12610 sui_core::SemanticsActionRequest::Collapse => Some(false),
12611 _ => None,
12612 };
12613 if let Some(open) = open {
12614 self.set_open(ctx, open);
12615 ctx.set_handled();
12616 }
12617 }
12618 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
12619 let surface_id = self.surface.child().id();
12620 let focus_surface_id = self.focus_surface.child().id();
12621 let mut state = self.state.borrow_mut();
12622 let was_presented = state.is_presented();
12623 let was_focus_presented = state.focus_animation.is_presented();
12624 let previous_reveal = state.reveal.value;
12625 let previous_focus = state.focus_animation.value;
12626 let reveal_animating = state.reveal.advance(*time);
12627 let focus_animating = state.focus_animation.advance(*time);
12628 let reveal_changed = state.reveal.changed_since(previous_reveal);
12629 let focus_changed = state.focus_animation.changed_since(previous_focus);
12630 let is_presented = state.is_presented();
12631 let is_focus_presented = state.focus_animation.is_presented();
12632 drop(state);
12633
12634 if reveal_changed {
12635 request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
12636 request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
12637 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
12638 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
12639 }
12640 if focus_changed {
12641 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
12642 }
12643 if was_presented != is_presented {
12644 ctx.request_measure();
12645 request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
12646 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12647 }
12648 if was_focus_presented != is_focus_presented {
12649 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12650 }
12651 if reveal_animating || focus_animating {
12652 ctx.request_animation_frame();
12653 }
12654 ctx.set_handled();
12655 }
12656 Event::Wake(WakeEvent::Timer { token, .. }) if self.arrival_timer == Some(*token) => {
12657 self.arrival_timer = None;
12658 let surface_id = self.surface.child().id();
12659 let mut state = self.state.borrow_mut();
12660 if state.arrival_active {
12661 state.arrival_active = false;
12662 drop(state);
12663 request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
12664 } else {
12665 drop(state);
12666 }
12667 ctx.set_handled();
12668 }
12669 _ => {}
12670 }
12671 }
12672
12673 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
12674 self.sync_external_open();
12675 let trigger_size = self.trigger.measure(ctx, constraints.loosen());
12676 let viewport = ctx.dpi().viewport;
12682 let viewport_margin = self.gap.max(4.0);
12683 let surface_max = Size::new(
12684 if viewport.width > 0.0 {
12685 (viewport.width - viewport_margin * 2.0).max(0.0)
12686 } else {
12687 f32::INFINITY
12688 },
12689 if viewport.height > 0.0 {
12690 (viewport.height - viewport_margin * 2.0).max(0.0)
12691 } else {
12692 f32::INFINITY
12693 },
12694 );
12695 let surface_size = self
12696 .surface
12697 .measure(ctx, Constraints::new(Size::ZERO, surface_max));
12698 let presented = self.state.borrow().is_presented();
12699 let focus_size = if presented { surface_size } else { Size::ZERO };
12700 self.focus_surface
12701 .measure(ctx, Constraints::tight(focus_size));
12702 constraints.clamp(trigger_size)
12703 }
12704
12705 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
12706 let trigger_size = self.trigger.child().measured_size();
12707 let aligned_x = |width: f32| match self.alignment {
12708 PopoverAlignment::Start => bounds.x(),
12709 PopoverAlignment::End => bounds.max_x() - width,
12710 };
12711 let trigger_bounds = Rect::new(
12712 aligned_x(trigger_size.width),
12713 bounds.y(),
12714 trigger_size.width,
12715 trigger_size.height,
12716 );
12717 self.trigger.arrange(ctx, trigger_bounds);
12718
12719 let presented = self.state.borrow().is_presented();
12720 let surface_bounds = if presented {
12721 let surface_size = self.surface.child().measured_size();
12722 let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
12723 let margin = self.gap.max(4.0);
12724 let width = surface_size.width.max(trigger_size.width);
12725 let alignment = match self.alignment {
12726 PopoverAlignment::Start => OverlayAlignment::Start,
12727 PopoverAlignment::End => OverlayAlignment::End,
12728 };
12729 place_overlay(
12730 &OverlayPlacementRequest::new(
12731 trigger_bounds,
12732 Size::new(width, surface_size.height),
12733 viewport,
12734 OverlayPlacement::new(OverlaySide::Bottom, alignment),
12735 )
12736 .fallbacks([OverlayPlacement::new(OverlaySide::Top, alignment)])
12737 .gap(self.gap)
12738 .margin(margin),
12739 )
12740 .bounds
12741 } else {
12742 Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
12743 };
12744 self.state.borrow_mut().frame_rect = surface_bounds;
12745 self.surface.arrange(ctx, surface_bounds);
12746 self.focus_surface.arrange(ctx, surface_bounds);
12747 }
12748
12749 fn paint(&self, ctx: &mut PaintCtx) {
12750 self.trigger.paint(ctx);
12751 if self.state.borrow().is_presented() {
12752 self.surface.paint(ctx);
12753 self.focus_surface.paint(ctx);
12754 }
12755 }
12756
12757 fn semantics(&self, ctx: &mut SemanticsCtx) {
12758 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Popover, ctx.bounds());
12759 node.name = Some(self.name.clone());
12760 node.state.focused = ctx.is_focused();
12761 node.state.expanded = Some(self.open);
12762 node.popup = Some(SemanticsPopupKind::Dialog);
12763 node.actions = vec![
12764 SemanticsAction::Focus,
12765 SemanticsAction::Expand,
12766 SemanticsAction::Collapse,
12767 ];
12768 ctx.push(node);
12769 self.trigger.semantics(ctx);
12770 if self.open {
12771 self.surface.semantics(ctx);
12772 }
12773 }
12774
12775 fn accepts_focus(&self) -> bool {
12776 true
12777 }
12778
12779 fn overlay_options(&self) -> Option<OverlayOptions> {
12780 (self.open || self.state.borrow().is_presented()).then_some(
12781 OverlayOptions::new(OverlayKind::Popover)
12782 .dismiss(if self.open {
12783 OverlayDismissPolicy::TRANSIENT
12784 } else {
12785 OverlayDismissPolicy::NONE
12786 })
12787 .focus(OverlayFocusBehavior::NONE),
12788 )
12789 }
12790
12791 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
12792 let focus_surface_id = self.focus_surface.child().id();
12793 let mut state = self.state.borrow_mut();
12794 let was_focus_presented = state.focus_animation.is_presented();
12795 let theme = state.theme;
12796 set_focus_animation_target(
12797 &mut state.focus_animation,
12798 focused as u8 as f32,
12799 &theme,
12800 ctx,
12801 );
12802 let is_focus_presented = state.focus_animation.is_presented();
12803 drop(state);
12804
12805 if was_focus_presented != is_focus_presented {
12806 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12807 }
12808 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
12809 if !focused && self.open {
12810 self.set_open(ctx, false);
12811 }
12812 ctx.request_semantics();
12813 }
12814
12815 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12816 self.trigger.visit_children(visitor);
12817 if self.open || self.state.borrow().is_presented() {
12818 self.surface.visit_children(visitor);
12819 self.focus_surface.visit_children(visitor);
12820 }
12821 }
12822
12823 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12824 self.trigger.visit_children_mut(visitor);
12825 if self.open || self.state.borrow().is_presented() {
12826 self.surface.visit_children_mut(visitor);
12827 self.focus_surface.visit_children_mut(visitor);
12828 }
12829 }
12830}
12831
12832#[derive(Debug, Clone)]
12833struct ContextMenuPanel {
12834 prefix: Vec<usize>,
12835 items: Vec<MenuItem>,
12836 frame_rect: Rect,
12837 opens_left: bool,
12838}
12839
12840impl ContextMenuPanel {
12841 fn item_rect(&self, theme: &DefaultTheme, row_height: f32, index: usize) -> Option<Rect> {
12842 if index >= self.items.len() {
12843 return None;
12844 }
12845 let padding = theme.metrics.menu_padding;
12846 Some(Rect::new(
12847 self.frame_rect.x() + padding.left,
12848 self.frame_rect.y() + padding.top + (index as f32 * row_height),
12849 (self.frame_rect.width() - padding.left - padding.right).max(0.0),
12850 row_height,
12851 ))
12852 }
12853}
12854
12855#[derive(Debug, Clone)]
12856struct ContextMenuPresentationState {
12857 theme: DefaultTheme,
12858 panels: Vec<ContextMenuPanel>,
12859 highlighted: Option<Vec<usize>>,
12860 highlight_visual: Option<Vec<usize>>,
12861 pressed: Option<Vec<usize>>,
12862 press_visual: Option<Vec<usize>>,
12863 surface_rect: Rect,
12864 row_height: f32,
12865 reveal: AnimatedScalar,
12866 focus_animation: AnimatedScalar,
12867 highlight_animation: AnimatedScalar,
12868 press_animation: AnimatedScalar,
12869}
12870
12871impl ContextMenuPresentationState {
12872 fn new() -> Self {
12873 let theme = DefaultTheme::default();
12874 Self {
12875 theme,
12876 panels: Vec::new(),
12877 highlighted: None,
12878 highlight_visual: None,
12879 pressed: None,
12880 press_visual: None,
12881 surface_rect: Rect::ZERO,
12882 row_height: menu_row_height(&theme),
12883 reveal: AnimatedScalar::new(0.0),
12884 focus_animation: AnimatedScalar::new(0.0),
12885 highlight_animation: AnimatedScalar::new(0.0),
12886 press_animation: AnimatedScalar::new(0.0),
12887 }
12888 }
12889
12890 fn is_presented(&self) -> bool {
12891 self.reveal.is_presented()
12892 }
12893
12894 fn item_rect(&self, panel: usize, index: usize) -> Option<Rect> {
12895 self.panels
12896 .get(panel)?
12897 .item_rect(&self.theme, self.row_height, index)
12898 }
12899
12900 fn layer_properties(&self) -> LayerProperties {
12901 LayerProperties {
12902 opacity: self.reveal.value,
12903 translation: Vector::new(
12904 0.0,
12905 -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
12906 ),
12907 }
12908 }
12909
12910 fn highlight_amount_for(&self, path: &[usize]) -> f32 {
12911 if self.highlight_visual.as_deref() == Some(path) {
12912 self.highlight_animation.value
12913 } else {
12914 0.0
12915 }
12916 }
12917
12918 fn press_amount_for(&self, path: &[usize]) -> f32 {
12919 if self.press_visual.as_deref() == Some(path) {
12920 self.press_animation.value
12921 } else {
12922 0.0
12923 }
12924 }
12925}
12926
12927struct ContextMenuSurface {
12928 state: Rc<RefCell<ContextMenuPresentationState>>,
12929}
12930
12931impl ContextMenuSurface {
12932 fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
12933 Self { state }
12934 }
12935}
12936
12937impl Widget for ContextMenuSurface {
12938 fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
12939 let state = self.state.borrow();
12940 if state.is_presented() {
12941 state.surface_rect.size
12942 } else {
12943 Size::ZERO
12944 }
12945 }
12946
12947 fn paint(&self, ctx: &mut PaintCtx) {
12948 let state = self.state.borrow();
12949 if !state.is_presented() {
12950 return;
12951 }
12952
12953 let theme = state.theme;
12954 let metrics = theme.metrics;
12955 let palette = theme.palette;
12956 let interaction = theme.interaction;
12957 let item_padding = metrics.menu_item_padding;
12958 let surface_radius = metrics.corner_radius + 2.0;
12959 let submenu_width = menu_submenu_indicator_width(&theme);
12960
12961 for (panel_index, panel) in state.panels.iter().enumerate() {
12962 let menu = panel.frame_rect;
12963 paint_theme_shadow(ctx, menu, [surface_radius; 4], &theme.shadows.box_shadow.lg);
12964 draw_control_frame(
12965 ctx,
12966 menu,
12967 surface_radius,
12968 metrics,
12969 palette.surface_raised,
12970 palette.border,
12971 None,
12972 );
12973
12974 for (index, item) in panel.items.iter().enumerate() {
12975 let Some(row) = state.item_rect(panel_index, index) else {
12976 continue;
12977 };
12978 let mut path = panel.prefix.clone();
12979 path.push(index);
12980
12981 if item.separator_before {
12982 let line = Rect::new(
12983 row.x(),
12984 row.y() - (metrics.menu_padding.top * 0.5),
12985 row.width(),
12986 1.0,
12987 );
12988 ctx.fill(rounded_rect_path(line, 0.5), palette.border);
12989 }
12990
12991 let highlighted = state.highlighted.as_deref() == Some(path.as_slice());
12992 let highlight_amount = state.highlight_amount_for(&path);
12993 let press_amount = state.press_amount_for(&path);
12994 let label_style = theme.text_style(item.text_color(&theme));
12995 let shortcut_width = item
12996 .shortcut
12997 .as_ref()
12998 .map(|_| metrics.menu_shortcut_width)
12999 .unwrap_or(0.0);
13000 let indicator_width = if item.has_submenu() {
13001 submenu_width
13002 } else {
13003 0.0
13004 };
13005 let label_slot = Rect::new(
13006 row.x() + item_padding.left,
13007 row.y(),
13008 (row.width()
13009 - item_padding.left
13010 - item_padding.right
13011 - shortcut_width
13012 - indicator_width)
13013 .max(0.0),
13014 row.height(),
13015 );
13016 if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
13017 let highlight_background = mix_color(
13018 palette.control,
13019 palette.accent,
13020 interaction.selected_blend * highlight_amount,
13021 );
13022 let background = if press_amount > 0.0 {
13023 mix_color(
13024 highlight_background,
13025 palette.control_active,
13026 interaction.pressed_blend * press_amount,
13027 )
13028 } else {
13029 highlight_background
13030 };
13031 ctx.fill(
13032 rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
13033 background,
13034 );
13035 }
13036
13037 ctx.push_clip_rect(label_slot);
13038 paint_aligned_text(
13039 ctx,
13040 label_slot,
13041 &item.label,
13042 &label_style,
13043 label_style.line_height,
13044 0.0,
13045 );
13046 ctx.pop_clip();
13047
13048 if let Some(shortcut) = &item.shortcut {
13049 let shortcut_style = theme.placeholder_text_style();
13050 let shortcut_slot = Rect::new(
13051 row.max_x()
13052 - item_padding.right
13053 - indicator_width
13054 - metrics.menu_shortcut_width,
13055 row.y(),
13056 metrics.menu_shortcut_width,
13057 row.height(),
13058 );
13059 ctx.push_clip_rect(shortcut_slot);
13060 paint_aligned_text(
13061 ctx,
13062 shortcut_slot,
13063 shortcut,
13064 &shortcut_style,
13065 shortcut_style.line_height,
13066 1.0,
13067 );
13068 ctx.pop_clip();
13069 }
13070
13071 if item.has_submenu() {
13072 let indicator_style = theme.text_style(item.text_color(&theme));
13073 let indicator_slot = Rect::new(
13074 row.max_x() - item_padding.right - indicator_width,
13075 row.y(),
13076 indicator_width,
13077 row.height(),
13078 );
13079 ctx.push_clip_rect(indicator_slot);
13080 paint_aligned_text(
13081 ctx,
13082 indicator_slot,
13083 "\u{203a}",
13084 &indicator_style,
13085 indicator_style.line_height,
13086 1.0,
13087 );
13088 ctx.pop_clip();
13089 }
13090 }
13091 }
13092 }
13093
13094 fn layer_options(&self) -> LayerOptions {
13095 let presented = self.state.borrow().is_presented();
13096 LayerOptions {
13097 paint_boundary: PaintBoundaryMode::Explicit,
13098 composition_mode: if presented {
13099 LayerCompositionMode::Overlay
13100 } else {
13101 LayerCompositionMode::Normal
13102 },
13103 }
13104 }
13105
13106 fn layer_properties(&self) -> LayerProperties {
13107 self.state.borrow().layer_properties()
13108 }
13109
13110 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
13111 self.state
13112 .borrow()
13113 .is_presented()
13114 .then_some(StackSurfaceOptions {
13115 transient: true,
13116 ..StackSurfaceOptions::default()
13117 })
13118 }
13119}
13120
13121struct ContextMenuFocusSurface {
13122 state: Rc<RefCell<ContextMenuPresentationState>>,
13123}
13124
13125impl ContextMenuFocusSurface {
13126 fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
13127 Self { state }
13128 }
13129}
13130
13131impl Widget for ContextMenuFocusSurface {
13132 fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
13133 let state = self.state.borrow();
13134 if state.is_presented() {
13135 state.surface_rect.size
13136 } else {
13137 Size::ZERO
13138 }
13139 }
13140
13141 fn paint(&self, ctx: &mut PaintCtx) {
13142 let state = self.state.borrow();
13143 if !state.is_presented() || !state.focus_animation.is_presented() {
13144 return;
13145 }
13146
13147 let progress = state.focus_animation.value;
13148 if progress <= AnimatedScalar::EPSILON {
13149 return;
13150 }
13151
13152 let metrics = state.theme.metrics;
13153 let palette = state.theme.palette;
13154 for panel in &state.panels {
13155 draw_focus_ring_frame(
13156 ctx,
13157 panel.frame_rect,
13158 metrics.corner_radius + 2.0,
13159 metrics,
13160 palette
13161 .focus_ring
13162 .with_alpha(palette.focus_ring.alpha * progress),
13163 );
13164 }
13165 }
13166
13167 fn layer_options(&self) -> LayerOptions {
13168 LayerOptions {
13169 paint_boundary: PaintBoundaryMode::Explicit,
13170 composition_mode: LayerCompositionMode::Normal,
13171 }
13172 }
13173
13174 fn layer_properties(&self) -> LayerProperties {
13175 self.state.borrow().layer_properties()
13176 }
13177
13178 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
13179 let state = self.state.borrow();
13180 (state.is_presented() && state.focus_animation.is_presented()).then_some(
13181 StackSurfaceOptions {
13182 transient: true,
13183 hit_test: false,
13184 ..StackSurfaceOptions::default()
13185 },
13186 )
13187 }
13188}
13189
13190pub struct ContextMenu {
13191 theme: Box<DefaultTheme>,
13192 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
13193 name: String,
13194 trigger: SingleChild,
13195 items: Vec<MenuItem>,
13196 items_provider: Option<Box<dyn Fn() -> Vec<MenuItem>>>,
13197 open: bool,
13198 open_path: Vec<usize>,
13199 highlighted: Option<Vec<usize>>,
13200 highlight_visual: Option<Vec<usize>>,
13201 pressed: Option<Vec<usize>>,
13202 press_visual: Option<Vec<usize>>,
13203 highlight_animation: AnimatedScalar,
13204 press_animation: AnimatedScalar,
13205 panels: Vec<ContextMenuPanel>,
13206 surface: SingleChild,
13207 focus_surface: SingleChild,
13208 surface_state: Rc<RefCell<ContextMenuPresentationState>>,
13209 activation_button: PointerButton,
13210 primary_trigger_press: Option<u64>,
13211 anchor_to_pointer: Option<bool>,
13212 open_position: Option<Point>,
13213 on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
13214 on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
13215 on_activate_path: Option<Box<dyn FnMut(Vec<usize>, MenuItem)>>,
13216 on_activate_path_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, Vec<usize>, MenuItem)>>,
13217}
13218
13219impl ContextMenu {
13220 pub fn new<W>(name: impl Into<String>, trigger: W) -> Self
13221 where
13222 W: Widget + 'static,
13223 {
13224 let surface_state = Rc::new(RefCell::new(ContextMenuPresentationState::new()));
13225 Self {
13226 theme: Box::new(DefaultTheme::default()),
13227 theme_reader: None,
13228 name: name.into(),
13229 trigger: SingleChild::new(trigger),
13230 items: Vec::new(),
13231 items_provider: None,
13232 open: false,
13233 open_path: Vec::new(),
13234 highlighted: None,
13235 highlight_visual: None,
13236 pressed: None,
13237 press_visual: None,
13238 highlight_animation: AnimatedScalar::new(0.0),
13239 press_animation: AnimatedScalar::new(0.0),
13240 panels: Vec::new(),
13241 surface: SingleChild::new(ContextMenuSurface::new(Rc::clone(&surface_state))),
13242 focus_surface: SingleChild::new(ContextMenuFocusSurface::new(Rc::clone(
13243 &surface_state,
13244 ))),
13245 surface_state,
13246 activation_button: PointerButton::Secondary,
13247 primary_trigger_press: None,
13248 anchor_to_pointer: None,
13249 open_position: None,
13250 on_activate: None,
13251 on_activate_with_ctx: None,
13252 on_activate_path: None,
13253 on_activate_path_with_ctx: None,
13254 }
13255 }
13256
13257 pub fn theme(mut self, theme: DefaultTheme) -> Self {
13258 self.theme = Box::new(theme);
13259 self.theme_reader = None;
13260 self
13261 }
13262
13263 pub fn theme_when<F>(mut self, theme: F) -> Self
13264 where
13265 F: Fn() -> DefaultTheme + 'static,
13266 {
13267 self.theme_reader = Some(Box::new(theme));
13268 self
13269 }
13270
13271 pub fn item(mut self, item: MenuItem) -> Self {
13272 self.items.push(item);
13273 self
13274 }
13275
13276 pub fn items<I>(mut self, items: I) -> Self
13277 where
13278 I: IntoIterator<Item = MenuItem>,
13279 {
13280 self.items.extend(items);
13281 self
13282 }
13283
13284 pub fn items_when<F>(mut self, provider: F) -> Self
13287 where
13288 F: Fn() -> Vec<MenuItem> + 'static,
13289 {
13290 self.items_provider = Some(Box::new(provider));
13291 self
13292 }
13293
13294 pub fn trigger_id(&self) -> WidgetId {
13298 self.trigger.child().id()
13299 }
13300
13301 pub fn on_activate<F>(mut self, on_activate: F) -> Self
13307 where
13308 F: FnMut(usize, MenuItem) + 'static,
13309 {
13310 self.on_activate = Some(Box::new(on_activate));
13311 self
13312 }
13313
13314 pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
13316 where
13317 F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
13318 {
13319 self.on_activate_with_ctx = Some(Box::new(on_activate));
13320 self
13321 }
13322
13323 pub fn on_activate_path<F>(mut self, on_activate: F) -> Self
13326 where
13327 F: FnMut(Vec<usize>, MenuItem) + 'static,
13328 {
13329 self.on_activate_path = Some(Box::new(on_activate));
13330 self
13331 }
13332
13333 pub fn on_activate_path_with_ctx<F>(mut self, on_activate: F) -> Self
13336 where
13337 F: FnMut(&mut EventCtx, Vec<usize>, MenuItem) + 'static,
13338 {
13339 self.on_activate_path_with_ctx = Some(Box::new(on_activate));
13340 self
13341 }
13342
13343 pub fn activation_button(mut self, activation_button: PointerButton) -> Self {
13350 self.activation_button = activation_button;
13351 self
13352 }
13353
13354 pub fn anchor_to_pointer(mut self, anchor_to_pointer: bool) -> Self {
13359 self.anchor_to_pointer = Some(anchor_to_pointer);
13360 self
13361 }
13362
13363 fn anchors_to_pointer(&self) -> bool {
13364 self.anchor_to_pointer
13365 .unwrap_or(self.activation_button == PointerButton::Secondary)
13366 }
13367
13368 fn row_height(&self) -> f32 {
13369 menu_row_height(&self.resolved_theme())
13370 }
13371
13372 fn measured_menu_width_for_items(&self, ctx: &mut MeasureCtx, items: &[MenuItem]) -> f32 {
13373 let theme = self.resolved_theme();
13374 let label_style = theme.body_text_style();
13375 let shortcut_style = theme.placeholder_text_style();
13376 let mut width: f32 = 220.0;
13377 for item in items {
13378 let label = measure_text(ctx, item.label(), &label_style).width;
13379 let shortcut = item
13380 .shortcut
13381 .as_ref()
13382 .map(|text| measure_text(ctx, text, &shortcut_style).width)
13383 .unwrap_or(0.0);
13384 width = width.max(
13385 label
13386 + shortcut
13387 + theme.metrics.menu_item_padding.left
13388 + theme.metrics.menu_item_padding.right
13389 + theme.metrics.menu_shortcut_width
13390 + if item.has_submenu() {
13391 menu_submenu_indicator_width(&theme)
13392 } else {
13393 0.0
13394 },
13395 );
13396 }
13397 width
13398 }
13399
13400 fn resolved_theme(&self) -> DefaultTheme {
13401 self.theme_reader
13402 .as_ref()
13403 .map(|theme| theme())
13404 .unwrap_or(*self.theme)
13405 }
13406
13407 fn trigger_rect(&self) -> Rect {
13408 self.trigger.child().bounds()
13409 }
13410
13411 fn items_at_prefix(&self, prefix: &[usize]) -> Option<&[MenuItem]> {
13412 let mut items = self.items.as_slice();
13413 for index in prefix {
13414 items = items.get(*index)?.submenu_items();
13415 }
13416 Some(items)
13417 }
13418
13419 fn item_at_path(&self, path: &[usize]) -> Option<&MenuItem> {
13420 let (&index, prefix) = path.split_last()?;
13421 self.items_at_prefix(prefix)?.get(index)
13422 }
13423
13424 fn item_rect(&self, bounds: Rect, path: &[usize]) -> Option<Rect> {
13425 if !self.open {
13426 return None;
13427 }
13428 let (&index, prefix) = path.split_last()?;
13429 let panel = self.panels.get(prefix.len())?;
13430 if panel.prefix != prefix {
13431 return None;
13432 }
13433 let theme = self.resolved_theme();
13434 panel
13435 .item_rect(&theme, self.row_height(), index)
13436 .map(|rect| rect.translate(bounds.origin.to_vector()))
13437 }
13438
13439 fn item_at(&self, bounds: Rect, position: Point) -> Option<Vec<usize>> {
13440 self.panels.iter().rev().find_map(|panel| {
13441 panel.items.iter().enumerate().find_map(|(index, _)| {
13442 let mut path = panel.prefix.clone();
13443 path.push(index);
13444 self.item_rect(bounds, &path)
13445 .filter(|rect| rect.contains(position))
13446 .map(|_| path)
13447 })
13448 })
13449 }
13450
13451 fn surface_rect(&self) -> Rect {
13452 self.panels
13453 .iter()
13454 .map(|panel| panel.frame_rect)
13455 .reduce(Rect::union)
13456 .unwrap_or(Rect::ZERO)
13457 }
13458
13459 fn sync_surface_state(&self, bounds: Rect) {
13460 let theme = self.resolved_theme();
13461 let translation = bounds.origin.to_vector();
13462 let mut state = self.surface_state.borrow_mut();
13463 state.theme = theme;
13464 state.panels = self
13465 .panels
13466 .iter()
13467 .cloned()
13468 .map(|mut panel| {
13469 panel.frame_rect = panel.frame_rect.translate(translation);
13470 panel
13471 })
13472 .collect();
13473 state.highlighted = self.highlighted.clone();
13474 state.highlight_visual = self.highlight_visual.clone();
13475 state.pressed = self.pressed.clone();
13476 state.press_visual = self.press_visual.clone();
13477 state.highlight_animation = self.highlight_animation;
13478 state.press_animation = self.press_animation;
13479 state.surface_rect = self.surface_rect().translate(translation);
13480 state.row_height = self.row_height();
13481 }
13482
13483 fn refresh_surface_interaction_state(&self, ctx: &mut EventCtx) {
13484 let surface_id = self.surface.child().id();
13485 let mut state = self.surface_state.borrow_mut();
13486 let changed = state.highlighted != self.highlighted
13487 || state.highlight_visual != self.highlight_visual
13488 || state.pressed != self.pressed
13489 || state.press_visual != self.press_visual
13490 || state.highlight_animation != self.highlight_animation
13491 || state.press_animation != self.press_animation;
13492 state.highlighted = self.highlighted.clone();
13493 state.highlight_visual = self.highlight_visual.clone();
13494 state.pressed = self.pressed.clone();
13495 state.press_visual = self.press_visual.clone();
13496 state.highlight_animation = self.highlight_animation;
13497 state.press_animation = self.press_animation;
13498 let presented = state.is_presented();
13499 drop(state);
13500
13501 if changed && presented {
13502 request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
13503 }
13504 }
13505
13506 fn set_highlighted(&mut self, highlighted: Option<Vec<usize>>, ctx: &mut EventCtx) {
13507 if self.highlighted == highlighted {
13508 return;
13509 }
13510 let theme = self.resolved_theme();
13511 self.highlighted = highlighted.clone();
13512 if let Some(path) = highlighted {
13513 self.highlight_visual = Some(path);
13514 self.highlight_animation = AnimatedScalar::new(0.0);
13515 set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
13516 } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
13517 self.highlight_visual = None;
13518 }
13519 self.refresh_surface_interaction_state(ctx);
13520 ctx.request_paint();
13521 ctx.request_semantics();
13522 }
13523
13524 fn set_pressed(&mut self, pressed: Option<Vec<usize>>, ctx: &mut EventCtx) {
13525 if self.pressed == pressed {
13526 return;
13527 }
13528 let theme = self.resolved_theme();
13529 self.pressed = pressed.clone();
13530 if let Some(path) = pressed {
13531 self.press_visual = Some(path);
13532 self.press_animation = AnimatedScalar::new(0.0);
13533 set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
13534 } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
13535 self.press_visual = None;
13536 }
13537 self.refresh_surface_interaction_state(ctx);
13538 ctx.request_paint();
13539 ctx.request_semantics();
13540 }
13541
13542 fn advance_row_animations(&mut self, time: f64) -> bool {
13543 let highlight_animating = self.highlight_animation.advance(time);
13544 if !highlight_animating
13545 && self.highlighted.is_none()
13546 && self.highlight_animation.value <= AnimatedScalar::EPSILON
13547 {
13548 self.highlight_visual = None;
13549 }
13550
13551 let press_animating = self.press_animation.advance(time);
13552 if !press_animating
13553 && self.pressed.is_none()
13554 && self.press_animation.value <= AnimatedScalar::EPSILON
13555 {
13556 self.press_visual = None;
13557 }
13558
13559 highlight_animating | press_animating
13560 }
13561
13562 fn set_open_path(&mut self, ctx: &mut EventCtx, open_path: Vec<usize>) {
13563 if self.open_path == open_path {
13564 return;
13565 }
13566 self.open_path = open_path;
13567 ctx.request_measure();
13568 ctx.request_paint();
13569 ctx.request_semantics();
13570 }
13571
13572 fn update_pointer_highlight(&mut self, ctx: &mut EventCtx, highlighted: Option<Vec<usize>>) {
13573 if let Some(path) = highlighted {
13574 let opens_submenu = self
13575 .item_at_path(&path)
13576 .is_some_and(|item| item.enabled && item.has_submenu());
13577 let open_path = if opens_submenu {
13578 path.clone()
13579 } else {
13580 path[..path.len().saturating_sub(1)].to_vec()
13581 };
13582 self.set_open_path(ctx, open_path);
13583 self.set_highlighted(Some(path), ctx);
13584 } else {
13585 self.set_highlighted(None, ctx);
13586 }
13587 }
13588
13589 fn open_highlighted_submenu(&mut self, ctx: &mut EventCtx) -> bool {
13590 let Some(path) = self.highlighted.clone() else {
13591 return false;
13592 };
13593 let first_enabled = self.item_at_path(&path).and_then(|item| {
13594 item.enabled
13595 .then(|| item.submenu_items().iter().position(|child| child.enabled))
13596 .flatten()
13597 });
13598 if self
13599 .item_at_path(&path)
13600 .is_none_or(|item| !item.enabled || !item.has_submenu())
13601 {
13602 return false;
13603 }
13604 self.set_open_path(ctx, path.clone());
13605 if let Some(index) = first_enabled {
13606 let mut child = path;
13607 child.push(index);
13608 self.set_highlighted(Some(child), ctx);
13609 }
13610 true
13611 }
13612
13613 fn close_current_submenu(&mut self, ctx: &mut EventCtx) -> bool {
13614 let Some(path) = self.highlighted.clone() else {
13615 return false;
13616 };
13617 if path.len() > 1 {
13618 let owner = path[..path.len() - 1].to_vec();
13619 let parent_open_path = owner[..owner.len().saturating_sub(1)].to_vec();
13620 self.set_open_path(ctx, parent_open_path);
13621 self.set_highlighted(Some(owner), ctx);
13622 true
13623 } else if self.open_path == path {
13624 self.set_open_path(ctx, Vec::new());
13625 true
13626 } else {
13627 false
13628 }
13629 }
13630
13631 fn move_highlight(&mut self, delta: isize, ctx: &mut EventCtx) {
13632 let prefix = self
13633 .highlighted
13634 .as_deref()
13635 .map(|path| &path[..path.len().saturating_sub(1)])
13636 .unwrap_or(&[])
13637 .to_vec();
13638 let Some(items) = self.items_at_prefix(&prefix) else {
13639 return;
13640 };
13641 if items.is_empty() {
13642 return;
13643 }
13644 let current = self
13645 .highlighted
13646 .as_deref()
13647 .and_then(|path| path.last().copied());
13648 let len = items.len() as isize;
13649 let mut index = current.map_or(if delta > 0 { -1 } else { len }, |index| index as isize);
13650 loop {
13651 let next = (index + delta).clamp(0, len - 1);
13652 if next == index {
13653 return;
13654 }
13655 index = next;
13656 if items[index as usize].enabled {
13657 break;
13658 }
13659 }
13660 let mut path = prefix.clone();
13661 path.push(index as usize);
13662 self.set_open_path(ctx, prefix);
13663 self.set_highlighted(Some(path), ctx);
13664 }
13665
13666 fn move_highlight_to_edge(&mut self, first: bool, ctx: &mut EventCtx) {
13667 let prefix = self
13668 .highlighted
13669 .as_deref()
13670 .map(|path| &path[..path.len().saturating_sub(1)])
13671 .unwrap_or(&[])
13672 .to_vec();
13673 let Some(items) = self.items_at_prefix(&prefix) else {
13674 return;
13675 };
13676 let index = if first {
13677 items.iter().position(|item| item.enabled)
13678 } else {
13679 items.iter().rposition(|item| item.enabled)
13680 };
13681 if let Some(index) = index {
13682 let mut path = prefix.clone();
13683 path.push(index);
13684 self.set_open_path(ctx, prefix);
13685 self.set_highlighted(Some(path), ctx);
13686 }
13687 }
13688
13689 fn visible_path_for_semantics_id(
13690 &self,
13691 root: WidgetId,
13692 target: WidgetId,
13693 ) -> Option<Vec<usize>> {
13694 self.panels.iter().find_map(|panel| {
13695 panel.items.iter().enumerate().find_map(|(index, _)| {
13696 let mut path = panel.prefix.clone();
13697 path.push(index);
13698 (virtual_menu_item_path_id(root, &path) == target).then_some(path)
13699 })
13700 })
13701 }
13702
13703 fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
13704 if self.open == open {
13705 return;
13706 }
13707
13708 if open && let Some(provider) = &self.items_provider {
13709 self.items = provider();
13710 }
13711 if !open {
13712 self.open_position = None;
13713 }
13714
13715 self.open = open;
13716 self.open_path.clear();
13717 self.highlighted = if open {
13718 self.items
13719 .iter()
13720 .position(|item| item.enabled)
13721 .map(|index| vec![index])
13722 } else {
13723 None
13724 };
13725 self.highlight_visual = self.highlighted.clone();
13726 self.highlight_animation = AnimatedScalar::new(self.highlighted.is_some() as u8 as f32);
13727 self.pressed = None;
13728 self.press_visual = None;
13729 self.press_animation = AnimatedScalar::new(0.0);
13730 self.panels.clear();
13731
13732 let surface_id = self.surface.child().id();
13733 let focus_surface_id = self.focus_surface.child().id();
13734 let theme = self.resolved_theme();
13735 let mut state = self.surface_state.borrow_mut();
13736 state.theme = theme;
13737 state.panels.clear();
13738 state.highlighted = self.highlighted.clone();
13739 state.highlight_visual = self.highlight_visual.clone();
13740 state.pressed = self.pressed.clone();
13741 state.press_visual = self.press_visual.clone();
13742 state.highlight_animation = self.highlight_animation;
13743 state.press_animation = self.press_animation;
13744 let was_presented = state.is_presented();
13745 let should_animate = if open {
13746 let motion = theme.motion;
13747 state.reveal.set_target(
13748 1.0,
13749 ctx.current_time(),
13750 motion.entrance_duration(),
13751 motion.entrance_easing(),
13752 )
13753 } else {
13754 state.reveal = AnimatedScalar::new(0.0);
13755 false
13756 };
13757 let is_presented = state.is_presented();
13758 drop(state);
13759
13760 if open || was_presented != is_presented {
13761 ctx.request_measure();
13762 request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
13763 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
13764 }
13765 if should_animate {
13766 ctx.request_animation_frame();
13767 }
13768 ctx.request_paint();
13769 ctx.request_semantics();
13770 }
13771
13772 fn activate_path(&mut self, ctx: &mut EventCtx, path: Vec<usize>) {
13773 let Some(item) = self.item_at_path(&path).cloned() else {
13774 return;
13775 };
13776 if !item.enabled || item.has_submenu() {
13777 return;
13778 }
13779 let Some(root_index) = path.first().copied() else {
13780 return;
13781 };
13782 if let Some(on_activate) = &mut self.on_activate {
13783 on_activate(root_index, item.clone());
13784 }
13785 if let Some(on_activate) = &mut self.on_activate_with_ctx {
13786 on_activate(ctx, root_index, item.clone());
13787 }
13788 if let Some(on_activate) = &mut self.on_activate_path {
13789 on_activate(path.clone(), item.clone());
13790 }
13791 if let Some(on_activate) = &mut self.on_activate_path_with_ctx {
13792 on_activate(ctx, path, item);
13793 }
13794 }
13795}
13796
13797impl Widget for ContextMenu {
13798 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
13799 if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
13800 self.set_open(ctx, false);
13801 ctx.set_handled();
13802 }
13803 }
13804
13805 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
13806 match event {
13807 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move && self.open => {
13808 let highlighted = self.item_at(ctx.bounds(), pointer.position);
13809 self.update_pointer_highlight(ctx, highlighted);
13810 }
13811 Event::Pointer(pointer)
13812 if pointer.kind == PointerEventKind::Down
13813 && pointer.button == Some(self.activation_button)
13814 && if self.activation_button == PointerButton::Primary {
13815 ctx.phase() == EventPhase::Capture
13816 } else {
13817 ctx.phase() != EventPhase::Capture
13818 }
13819 && self.trigger_rect().contains(pointer.position) =>
13820 {
13821 if self.activation_button == PointerButton::Primary {
13826 if self.open {
13827 self.set_open(ctx, false);
13828 } else {
13829 self.primary_trigger_press = Some(pointer.pointer_id);
13830 ctx.request_pointer_capture(pointer.pointer_id);
13831 }
13832 } else {
13833 let open = !self.open;
13834 self.open_position = (open && self.anchors_to_pointer()).then(|| {
13835 let origin = ctx.bounds().origin;
13836 Point::new(pointer.position.x - origin.x, pointer.position.y - origin.y)
13837 });
13838 self.set_open(ctx, open);
13839 if open {
13840 ctx.request_focus();
13841 }
13842 }
13843 ctx.set_handled();
13844 }
13845 Event::Pointer(pointer)
13846 if pointer.kind == PointerEventKind::Up
13847 && pointer.button == Some(PointerButton::Primary)
13848 && self.primary_trigger_press == Some(pointer.pointer_id) =>
13849 {
13850 self.primary_trigger_press = None;
13851 ctx.release_pointer_capture(pointer.pointer_id);
13852 if self.trigger_rect().contains(pointer.position) {
13853 self.open_position = None;
13854 self.set_open(ctx, true);
13855 ctx.request_focus();
13856 }
13857 ctx.set_handled();
13858 }
13859 Event::Pointer(pointer)
13860 if pointer.kind == PointerEventKind::Down
13861 && pointer.button == Some(PointerButton::Primary)
13862 && self.open =>
13863 {
13864 if let Some(path) = self.item_at(ctx.bounds(), pointer.position) {
13865 self.update_pointer_highlight(ctx, Some(path.clone()));
13866 self.set_pressed(
13867 self.item_at_path(&path)
13868 .filter(|item| item.enabled)
13869 .map(|_| path),
13870 ctx,
13871 );
13872 ctx.request_pointer_capture(pointer.pointer_id);
13873 ctx.set_handled();
13874 } else if !self.trigger_rect().contains(pointer.position) {
13875 self.set_open(ctx, false);
13876 }
13877 }
13878 Event::Pointer(pointer)
13879 if pointer.kind == PointerEventKind::Up
13880 && pointer.button == Some(PointerButton::Primary)
13881 && self.open =>
13882 {
13883 let highlighted = self.item_at(ctx.bounds(), pointer.position);
13884 if let Some(path) = self
13885 .pressed
13886 .clone()
13887 .zip(highlighted)
13888 .filter(|(left, right)| left == right)
13889 .map(|(path, _)| path)
13890 {
13891 if self.item_at_path(&path).is_some_and(MenuItem::has_submenu) {
13892 self.set_open_path(ctx, path);
13893 } else {
13894 self.activate_path(ctx, path);
13895 self.set_open(ctx, false);
13896 }
13897 }
13898 self.set_pressed(None, ctx);
13899 ctx.release_pointer_capture(pointer.pointer_id);
13900 ctx.set_handled();
13901 }
13902 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
13903 if self.primary_trigger_press == Some(pointer.pointer_id) {
13904 self.primary_trigger_press = None;
13905 ctx.release_pointer_capture(pointer.pointer_id);
13906 ctx.set_handled();
13907 }
13908 if self.pressed.is_some() {
13909 self.set_pressed(None, ctx);
13910 ctx.release_pointer_capture(pointer.pointer_id);
13911 ctx.set_handled();
13912 }
13913 }
13914 Event::Keyboard(key)
13915 if self.activation_button == PointerButton::Primary
13916 && ctx.is_focused()
13917 && key.state == KeyState::Pressed
13918 && !self.open
13919 && matches!(key.key.as_str(), "Enter" | " ") =>
13920 {
13921 self.open_position = None;
13922 self.set_open(ctx, true);
13923 ctx.request_focus();
13924 ctx.set_handled();
13925 }
13926 Event::Keyboard(key)
13927 if ctx.is_focused() && key.state == KeyState::Pressed && self.open =>
13928 {
13929 match key.key.as_str() {
13930 "ArrowDown" => self.move_highlight(1, ctx),
13931 "ArrowUp" => self.move_highlight(-1, ctx),
13932 "Home" => self.move_highlight_to_edge(true, ctx),
13933 "End" => self.move_highlight_to_edge(false, ctx),
13934 "ArrowRight" => {
13935 self.open_highlighted_submenu(ctx);
13936 }
13937 "ArrowLeft" => {
13938 self.close_current_submenu(ctx);
13939 }
13940 "Enter" | " " => {
13941 if !self.open_highlighted_submenu(ctx)
13942 && let Some(path) = self.highlighted.clone()
13943 {
13944 self.activate_path(ctx, path);
13945 self.set_open(ctx, false);
13946 }
13947 }
13948 "Escape" => {
13949 self.set_open(ctx, false);
13950 }
13951 _ => return,
13952 }
13953 self.refresh_surface_interaction_state(ctx);
13954 ctx.request_paint();
13955 ctx.request_semantics();
13956 ctx.set_handled();
13957 }
13958 Event::Semantics(semantics) if self.open && semantics.target != ctx.widget_id() => {
13959 let Some(path) =
13960 self.visible_path_for_semantics_id(ctx.widget_id(), semantics.target)
13961 else {
13962 return;
13963 };
13964 let has_submenu = self
13965 .item_at_path(&path)
13966 .is_some_and(|item| item.enabled && item.has_submenu());
13967 match semantics.action {
13968 sui_core::SemanticsActionRequest::Activate
13969 | sui_core::SemanticsActionRequest::Expand
13970 if has_submenu =>
13971 {
13972 self.set_highlighted(Some(path), ctx);
13973 self.open_highlighted_submenu(ctx);
13974 }
13975 sui_core::SemanticsActionRequest::Collapse if has_submenu => {
13976 self.set_open_path(ctx, path[..path.len().saturating_sub(1)].to_vec());
13977 self.set_highlighted(Some(path), ctx);
13978 }
13979 sui_core::SemanticsActionRequest::Activate => {
13980 self.activate_path(ctx, path);
13981 self.set_open(ctx, false);
13982 }
13983 sui_core::SemanticsActionRequest::Focus => {
13984 self.set_highlighted(Some(path), ctx);
13985 ctx.request_focus();
13986 }
13987 _ => return,
13988 }
13989 ctx.set_handled();
13990 }
13991 Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
13992 let open = match semantics.action {
13993 sui_core::SemanticsActionRequest::Activate => Some(!self.open),
13994 sui_core::SemanticsActionRequest::Expand => Some(true),
13995 sui_core::SemanticsActionRequest::Collapse => Some(false),
13996 _ => None,
13997 };
13998 if let Some(open) = open {
13999 self.open_position = None;
14000 self.set_open(ctx, open);
14001 if open {
14002 ctx.request_focus();
14003 }
14004 ctx.set_handled();
14005 }
14006 }
14007 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
14008 let surface_id = self.surface.child().id();
14009 let focus_surface_id = self.focus_surface.child().id();
14010 let mut state = self.surface_state.borrow_mut();
14011 let was_presented = state.is_presented();
14012 let was_focus_presented = state.focus_animation.is_presented();
14013 let previous = state.reveal.value;
14014 let previous_focus = state.focus_animation.value;
14015 let reveal_animating = state.reveal.advance(*time);
14016 let focus_animating = state.focus_animation.advance(*time);
14017 let reveal_changed = state.reveal.changed_since(previous);
14018 let focus_changed = state.focus_animation.changed_since(previous_focus);
14019 let is_presented = state.is_presented();
14020 let is_focus_presented = state.focus_animation.is_presented();
14021 drop(state);
14022
14023 let previous_highlight = self.highlight_animation.value;
14024 let previous_press = self.press_animation.value;
14025 let row_animating = self.advance_row_animations(*time);
14026 let row_changed = self.highlight_animation.changed_since(previous_highlight)
14027 || self.press_animation.changed_since(previous_press);
14028 if row_changed {
14029 self.refresh_surface_interaction_state(ctx);
14030 request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
14031 }
14032
14033 if reveal_changed {
14034 request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
14035 request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
14036 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
14037 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
14038 }
14039 if focus_changed {
14040 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
14041 }
14042 if was_presented != is_presented {
14043 ctx.request_measure();
14044 request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
14045 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
14046 }
14047 if was_focus_presented != is_focus_presented {
14048 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
14049 }
14050 if reveal_animating || row_animating || focus_animating {
14051 ctx.request_animation_frame();
14052 }
14053 ctx.set_handled();
14054 }
14055 _ => {}
14056 }
14057 }
14058
14059 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
14060 let trigger_size = self.trigger.measure(ctx, constraints.loosen());
14061 if self.open {
14062 let theme = self.resolved_theme();
14063 let pointer_anchored = self.open_position.is_some();
14064 self.panels.clear();
14065 let mut prefix = Vec::new();
14066 while let Some(items) = self.items_at_prefix(&prefix).map(<[MenuItem]>::to_vec) {
14067 let mut width = self.measured_menu_width_for_items(ctx, &items);
14068 if prefix.is_empty() && !pointer_anchored {
14069 width = width.max(trigger_size.width);
14070 }
14071 let height = themed_menu_height_for_rows(&theme, self.row_height(), items.len());
14072 self.panels.push(ContextMenuPanel {
14073 prefix: prefix.clone(),
14074 items: items.clone(),
14075 frame_rect: Rect::from_origin_size(Point::ZERO, Size::new(width, height)),
14076 opens_left: false,
14077 });
14078 if prefix.len() >= self.open_path.len() {
14079 break;
14080 }
14081 let next = self.open_path[prefix.len()];
14082 if items
14083 .get(next)
14084 .is_none_or(|item| !item.enabled || !item.has_submenu())
14085 {
14086 break;
14087 }
14088 prefix.push(next);
14089 }
14090
14091 let estimated_width = self
14092 .panels
14093 .iter()
14094 .map(|panel| panel.frame_rect.width())
14095 .sum::<f32>();
14096 let estimated_height = self
14097 .panels
14098 .iter()
14099 .map(|panel| panel.frame_rect.height())
14100 .sum::<f32>();
14101 let estimated_size = Size::new(estimated_width, estimated_height);
14102 {
14103 let mut state = self.surface_state.borrow_mut();
14104 state.theme = theme;
14105 state.panels = self.panels.clone();
14106 state.highlighted = self.highlighted.clone();
14107 state.highlight_visual = self.highlight_visual.clone();
14108 state.pressed = self.pressed.clone();
14109 state.press_visual = self.press_visual.clone();
14110 state.highlight_animation = self.highlight_animation;
14111 state.press_animation = self.press_animation;
14112 state.surface_rect = Rect::from_origin_size(Point::ZERO, estimated_size);
14113 state.row_height = self.row_height();
14114 }
14115 self.surface
14116 .measure(ctx, Constraints::tight(estimated_size));
14117 self.focus_surface
14118 .measure(ctx, Constraints::tight(estimated_size));
14119 } else {
14120 self.panels.clear();
14121 }
14122 constraints.clamp(trigger_size)
14123 }
14124
14125 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
14126 self.trigger.arrange(
14127 ctx,
14128 Rect::from_origin_size(bounds.origin, self.trigger.child().measured_size()),
14129 );
14130 if self.open && !self.panels.is_empty() {
14131 let theme = self.resolved_theme();
14132 let anchor = self.open_position.map_or_else(
14133 || self.trigger.child().bounds(),
14134 |position| {
14135 Rect::from_origin_size(
14136 Point::new(bounds.x() + position.x, bounds.y() + position.y),
14137 Size::ZERO,
14138 )
14139 },
14140 );
14141 let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
14142 let result = place_overlay(
14143 &OverlayPlacementRequest::new(
14144 anchor,
14145 self.panels[0].frame_rect.size,
14146 viewport,
14147 OverlayPlacement::BOTTOM_START,
14148 )
14149 .fallbacks([
14150 OverlayPlacement::TOP_START,
14151 OverlayPlacement::RIGHT_START,
14152 OverlayPlacement::LEFT_START,
14153 ])
14154 .gap(if self.open_position.is_some() {
14155 0.0
14156 } else {
14157 theme.metrics.popover_gap
14158 })
14159 .margin(theme.metrics.popover_gap.max(4.0)),
14160 );
14161 self.panels[0].frame_rect = result
14162 .bounds
14163 .translate(Vector::new(-bounds.x(), -bounds.y()));
14164
14165 for depth in 1..self.panels.len() {
14166 let owner_path = self.panels[depth].prefix.clone();
14167 let Some(anchor) = self.item_rect(bounds, &owner_path) else {
14168 continue;
14169 };
14170 let margin = theme.metrics.popover_gap.max(4.0);
14171 let remaining_cascade_width = self.panels[depth..]
14172 .iter()
14173 .map(|panel| panel.frame_rect.width())
14174 .sum::<f32>();
14175 let room_left = (anchor.x() - viewport.x() - margin).max(0.0);
14176 let room_right = (viewport.max_x() - anchor.max_x() - margin).max(0.0);
14177 let prefer_left = self.panels[depth - 1].opens_left
14178 || (room_right < remaining_cascade_width
14179 && room_left >= remaining_cascade_width);
14180 let (placement, fallbacks) = if prefer_left {
14181 (
14182 OverlayPlacement::LEFT_START,
14183 [
14184 OverlayPlacement::RIGHT_START,
14185 OverlayPlacement::LEFT_END,
14186 OverlayPlacement::RIGHT_END,
14187 ],
14188 )
14189 } else {
14190 (
14191 OverlayPlacement::RIGHT_START,
14192 [
14193 OverlayPlacement::LEFT_START,
14194 OverlayPlacement::RIGHT_END,
14195 OverlayPlacement::LEFT_END,
14196 ],
14197 )
14198 };
14199 let result = place_overlay(
14200 &OverlayPlacementRequest::new(
14201 anchor,
14202 self.panels[depth].frame_rect.size,
14203 viewport,
14204 placement,
14205 )
14206 .fallbacks(fallbacks)
14207 .gap(0.0)
14208 .margin(margin),
14209 );
14210 self.panels[depth].opens_left = result.placement.side == OverlaySide::Left;
14211 self.panels[depth].frame_rect = result
14212 .bounds
14213 .translate(Vector::new(-bounds.x(), -bounds.y()));
14214 }
14215 }
14216 self.sync_surface_state(bounds);
14217 let state = self.surface_state.borrow();
14218 let surface_bounds = if state.is_presented() {
14219 state.surface_rect
14220 } else {
14221 Rect::from_origin_size(bounds.origin, Size::ZERO)
14222 };
14223 drop(state);
14224 self.surface.arrange(ctx, surface_bounds);
14225 self.focus_surface.arrange(ctx, surface_bounds);
14226 }
14227
14228 fn paint(&self, ctx: &mut PaintCtx) {
14229 self.trigger.paint(ctx);
14230 if self.surface_state.borrow().is_presented() {
14231 self.surface.paint(ctx);
14232 self.focus_surface.paint(ctx);
14233 }
14234 }
14235
14236 fn semantics(&self, ctx: &mut SemanticsCtx) {
14237 let mut node =
14238 SemanticsNode::new(ctx.widget_id(), SemanticsRole::ContextMenu, ctx.bounds());
14239 node.name = Some(self.name.clone());
14240 node.state.focused = ctx.is_focused();
14241 node.state.expanded = Some(self.open);
14242 node.popup = Some(SemanticsPopupKind::Menu);
14243 node.value = self
14244 .highlighted
14245 .as_deref()
14246 .and_then(|path| self.item_at_path(path))
14247 .map(|item| SemanticsValue::Text(item.label.clone()));
14248 node.actions = vec![
14249 SemanticsAction::Focus,
14250 SemanticsAction::Expand,
14251 SemanticsAction::Collapse,
14252 SemanticsAction::Activate,
14253 ];
14254 ctx.push(node);
14255 if self.open {
14256 for panel in &self.panels {
14257 let parent = if panel.prefix.is_empty() {
14258 ctx.widget_id()
14259 } else {
14260 virtual_menu_item_path_id(ctx.widget_id(), &panel.prefix)
14261 };
14262 for (index, item) in panel.items.iter().enumerate() {
14263 let mut path = panel.prefix.clone();
14264 path.push(index);
14265 let Some(row) = self.item_rect(ctx.bounds(), &path) else {
14266 continue;
14267 };
14268 ctx.push(context_menu_item_semantics_node(
14269 ctx.widget_id(),
14270 parent,
14271 &path,
14272 item,
14273 row,
14274 self.highlighted.as_deref() == Some(path.as_slice()),
14275 self.open_path.starts_with(&path),
14276 ));
14277 }
14278 }
14279 }
14280 self.trigger.semantics(ctx);
14281 }
14282
14283 fn accepts_focus(&self) -> bool {
14284 true
14285 }
14286
14287 fn overlay_options(&self) -> Option<OverlayOptions> {
14288 (self.open || self.surface_state.borrow().is_presented()).then_some(
14289 OverlayOptions::new(OverlayKind::Menu)
14290 .dismiss(if self.open {
14291 OverlayDismissPolicy::TRANSIENT
14292 } else {
14293 OverlayDismissPolicy::NONE
14294 })
14295 .focus(OverlayFocusBehavior::NONE),
14296 )
14297 }
14298
14299 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
14300 if !focused && self.open {
14301 self.set_open(ctx, false);
14302 }
14303 let focus_surface_id = self.focus_surface.child().id();
14304 {
14305 let mut state = self.surface_state.borrow_mut();
14306 let was_focus_presented = state.focus_animation.is_presented();
14307 let theme = state.theme;
14308 set_focus_animation_target(
14309 &mut state.focus_animation,
14310 focused as u8 as f32,
14311 &theme,
14312 ctx,
14313 );
14314 if was_focus_presented != state.focus_animation.is_presented() {
14315 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
14316 }
14317 }
14318 request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
14319 ctx.request_semantics();
14320 }
14321
14322 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
14323 self.trigger.visit_children(visitor);
14324 if self.surface_state.borrow().is_presented() {
14325 self.surface.visit_children(visitor);
14326 self.focus_surface.visit_children(visitor);
14327 }
14328 }
14329
14330 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
14331 self.trigger.visit_children_mut(visitor);
14332 if self.surface_state.borrow().is_presented() {
14333 self.surface.visit_children_mut(visitor);
14334 self.focus_surface.visit_children_mut(visitor);
14335 }
14336 }
14337}
14338
14339#[derive(Debug, Clone)]
14340struct DialogFocusState {
14341 theme: DefaultTheme,
14342 frame: Rect,
14343 shown: bool,
14344 animation: AnimatedScalar,
14345}
14346
14347impl DialogFocusState {
14348 fn new() -> Self {
14349 Self {
14350 theme: DefaultTheme::default(),
14351 frame: Rect::ZERO,
14352 shown: false,
14353 animation: AnimatedScalar::new(0.0),
14354 }
14355 }
14356}
14357
14358struct DialogFocusSurface {
14359 state: Rc<RefCell<DialogFocusState>>,
14360}
14361
14362impl DialogFocusSurface {
14363 fn new(state: Rc<RefCell<DialogFocusState>>) -> Self {
14364 Self { state }
14365 }
14366}
14367
14368impl Widget for DialogFocusSurface {
14369 fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
14370 let state = self.state.borrow();
14371 if state.shown {
14372 state.frame.size
14373 } else {
14374 Size::ZERO
14375 }
14376 }
14377
14378 fn paint(&self, ctx: &mut PaintCtx) {
14379 let state = self.state.borrow();
14380 if !state.shown || !state.animation.is_presented() {
14381 return;
14382 }
14383 let progress = state.animation.value;
14384 if progress <= AnimatedScalar::EPSILON {
14385 return;
14386 }
14387 let metrics = state.theme.metrics;
14388 draw_focus_ring_frame(
14389 ctx,
14390 ctx.bounds(),
14391 metrics.corner_radius + 3.0,
14392 metrics,
14393 state
14394 .theme
14395 .palette
14396 .focus_ring
14397 .with_alpha(state.theme.palette.focus_ring.alpha * progress),
14398 );
14399 }
14400
14401 fn layer_options(&self) -> LayerOptions {
14402 LayerOptions {
14403 paint_boundary: PaintBoundaryMode::Explicit,
14404 composition_mode: LayerCompositionMode::Normal,
14405 }
14406 }
14407
14408 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
14409 let state = self.state.borrow();
14410 state.shown.then_some(StackSurfaceOptions {
14411 transient: true,
14412 hit_test: false,
14413 ..StackSurfaceOptions::default()
14414 })
14415 }
14416}
14417
14418pub struct Dialog {
14419 theme: Box<DefaultTheme>,
14420 title: String,
14421 description: Option<String>,
14422 shown: bool,
14423 modal: bool,
14424 dismiss_on_scrim: bool,
14425 max_width: Option<f32>,
14426 body: SingleChild,
14427 actions: WidgetChildren,
14428 body_frame: Rect,
14429 dialog_frame: Rect,
14430 title_measurement: Option<TextMeasurement>,
14431 description_measurement: Option<TextMeasurement>,
14432 reveal: AnimatedScalar,
14433 focus_animation: AnimatedScalar,
14434 focus_state: Rc<RefCell<DialogFocusState>>,
14435 focus_surface: SingleChild,
14436 entrance_started: bool,
14437 on_dismiss: Option<Box<dyn FnMut()>>,
14438 overlay_kind: OverlayKind,
14439}
14440
14441impl Dialog {
14442 pub fn new<W>(title: impl Into<String>, body: W) -> Self
14443 where
14444 W: Widget + 'static,
14445 {
14446 let focus_state = Rc::new(RefCell::new(DialogFocusState::new()));
14447 Self {
14448 theme: Box::new(DefaultTheme::default()),
14449 title: title.into(),
14450 description: None,
14451 shown: true,
14452 modal: true,
14453 dismiss_on_scrim: false,
14454 max_width: None,
14455 body: SingleChild::new(body),
14456 actions: WidgetChildren::new(),
14457 body_frame: Rect::ZERO,
14458 dialog_frame: Rect::ZERO,
14459 title_measurement: None,
14460 description_measurement: None,
14461 reveal: AnimatedScalar::new(0.0),
14462 focus_animation: AnimatedScalar::new(0.0),
14463 focus_surface: SingleChild::new(DialogFocusSurface::new(Rc::clone(&focus_state))),
14464 focus_state,
14465 entrance_started: false,
14466 on_dismiss: None,
14467 overlay_kind: OverlayKind::Dialog,
14468 }
14469 }
14470
14471 pub fn theme(mut self, theme: DefaultTheme) -> Self {
14472 self.theme = Box::new(theme);
14473 self
14474 }
14475
14476 pub fn description(mut self, description: impl Into<String>) -> Self {
14477 self.description = Some(description.into());
14478 self
14479 }
14480
14481 pub fn shown(mut self, shown: bool) -> Self {
14482 self.shown = shown;
14483 if !shown {
14484 self.reveal = AnimatedScalar::new(0.0);
14485 self.focus_animation = AnimatedScalar::new(0.0);
14486 self.entrance_started = false;
14487 let mut focus = self.focus_state.borrow_mut();
14488 focus.shown = false;
14489 focus.animation = AnimatedScalar::new(0.0);
14490 }
14491 self
14492 }
14493
14494 pub fn modal(mut self, modal: bool) -> Self {
14495 self.modal = modal;
14496 self
14497 }
14498
14499 pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
14500 self.dismiss_on_scrim = dismiss_on_scrim;
14501 self
14502 }
14503
14504 pub fn max_width(mut self, max_width: f32) -> Self {
14505 self.max_width = Some(max_width.max(self.theme.metrics.dialog_min_width));
14506 self
14507 }
14508
14509 pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
14510 where
14511 F: FnMut() + 'static,
14512 {
14513 self.on_dismiss = Some(Box::new(on_dismiss));
14514 self
14515 }
14516
14517 pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
14518 where
14519 F: FnMut() + 'static,
14520 {
14521 self.actions.push(
14522 Button::new(label.into())
14523 .min_width(self.theme.metrics.dialog_action_min_width)
14524 .on_press(on_press),
14525 );
14526 self
14527 }
14528
14529 pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
14530 where
14531 F: FnMut() + 'static,
14532 {
14533 self.actions.push(
14534 Button::new(label.into())
14535 .min_width(self.theme.metrics.dialog_action_min_width)
14536 .on_press(on_press),
14537 );
14538 self
14539 }
14540
14541 fn resolved_max_width(&self) -> f32 {
14542 self.max_width
14543 .unwrap_or(self.theme.metrics.dialog_max_width)
14544 }
14545
14546 fn title_style(&self) -> TextStyle {
14547 text_token_style(&self.theme, self.theme.text.lg, self.theme.palette.text)
14548 }
14549
14550 fn dismiss(&mut self) {
14551 if let Some(on_dismiss) = &mut self.on_dismiss {
14552 on_dismiss();
14553 }
14554 }
14555
14556 fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
14557 if self.entrance_started {
14558 return;
14559 }
14560 self.entrance_started = true;
14561 let motion = self.theme.motion;
14562 if self.reveal.set_target(
14563 1.0,
14564 ctx.current_time(),
14565 motion.entrance_duration(),
14566 motion.entrance_easing(),
14567 ) {
14568 ctx.request_animation_frame();
14569 }
14570 }
14571}
14572
14573impl Widget for Dialog {
14574 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
14575 if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.shown {
14576 self.dismiss();
14577 ctx.request_semantics();
14578 ctx.set_handled();
14579 }
14580 }
14581
14582 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
14583 if !self.shown {
14584 return;
14585 }
14586
14587 match event {
14588 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
14589 let previous = self.reveal.value;
14590 let animating = self.reveal.advance(*time);
14591 if self.reveal.changed_since(previous) {
14592 ctx.request_effect();
14593 if !self.modal {
14594 ctx.request_transform();
14595 }
14596 }
14597 let previous_focus = self.focus_animation.value;
14598 let was_focus_presented = self.focus_animation.is_presented();
14599 let focus_animating = self.focus_animation.advance(*time);
14600 if self.focus_animation.changed_since(previous_focus) {
14601 self.focus_state.borrow_mut().animation = self.focus_animation;
14602 request_child_invalidation(
14603 ctx,
14604 self.focus_surface.child().id(),
14605 InvalidationKind::Paint,
14606 );
14607 }
14608 if was_focus_presented != self.focus_animation.is_presented() {
14609 request_child_invalidation(
14610 ctx,
14611 self.focus_surface.child().id(),
14612 InvalidationKind::Visibility,
14613 );
14614 }
14615 if animating || focus_animating {
14616 ctx.request_animation_frame();
14617 }
14618 ctx.set_handled();
14619 }
14620 Event::Pointer(pointer)
14621 if pointer.kind == PointerEventKind::Down
14622 && pointer.button == Some(PointerButton::Primary)
14623 && self
14624 .dialog_frame
14625 .translate(ctx.bounds().origin.to_vector())
14626 .contains(pointer.position) =>
14627 {
14628 ctx.request_focus();
14629 ctx.request_semantics();
14630 }
14631 Event::Pointer(pointer)
14632 if pointer.kind == PointerEventKind::Down
14633 && pointer.button == Some(PointerButton::Primary)
14634 && !self
14635 .dialog_frame
14636 .translate(ctx.bounds().origin.to_vector())
14637 .contains(pointer.position) =>
14638 {
14639 if self.dismiss_on_scrim {
14640 self.dismiss();
14641 }
14642 if self.modal || self.dismiss_on_scrim {
14643 ctx.set_handled();
14644 }
14645 ctx.request_paint();
14646 ctx.request_semantics();
14647 }
14648 Event::Keyboard(key)
14649 if ctx.is_focused() && key.state == KeyState::Pressed && key.key == "Escape" =>
14650 {
14651 self.dismiss();
14652 ctx.request_paint();
14653 ctx.request_semantics();
14654 ctx.set_handled();
14655 }
14656 _ => {}
14657 }
14658 }
14659
14660 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
14661 if !self.shown {
14662 self.dialog_frame = Rect::ZERO;
14663 self.body_frame = Rect::ZERO;
14664 self.reveal = AnimatedScalar::new(0.0);
14665 self.focus_animation = AnimatedScalar::new(0.0);
14666 self.entrance_started = false;
14667 let mut focus = self.focus_state.borrow_mut();
14668 focus.shown = false;
14669 focus.frame = Rect::ZERO;
14670 focus.animation = AnimatedScalar::new(0.0);
14671 return Size::ZERO;
14672 }
14673 self.ensure_entrance_started(ctx);
14674
14675 let viewport = constraints.clamp(Size::new(
14676 if constraints.max.width.is_finite() {
14677 constraints.max.width
14678 } else {
14679 640.0
14680 },
14681 if constraints.max.height.is_finite() {
14682 constraints.max.height
14683 } else {
14684 420.0
14685 },
14686 ));
14687 let metrics = self.theme.metrics;
14688 let outer_margin = metrics.dialog_outer_margin;
14689 let padding = metrics.dialog_padding;
14690 let title_style = self.title_style();
14691 let description_style = self.theme.placeholder_text_style();
14692 self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
14693 self.description_measurement = self
14694 .description
14695 .as_ref()
14696 .map(|text| measure_text(ctx, text, &description_style));
14697
14698 let dialog_width = (viewport.width - (outer_margin * 2.0))
14699 .min(self.resolved_max_width())
14700 .max(metrics.dialog_min_width);
14701 let mut footer_height: f32 = 0.0;
14702 for button in self.actions.as_mut_slice().iter_mut() {
14703 let button_size = button.measure(
14704 ctx,
14705 Constraints::new(
14706 Size::ZERO,
14707 Size::new(dialog_width, metrics.min_height + metrics.dialog_action_gap),
14708 ),
14709 );
14710 footer_height = footer_height.max(button_size.height);
14711 }
14712
14713 let title_height = self
14714 .title_measurement
14715 .map(|measurement| measurement.height.max(title_style.line_height))
14716 .unwrap_or(title_style.line_height);
14717 let description_height = self
14718 .description_measurement
14719 .map(|measurement| measurement.height.max(description_style.line_height))
14720 .unwrap_or(0.0);
14721 let header_gap = if self.description.is_some() {
14722 metrics.dialog_description_gap
14723 } else {
14724 0.0
14725 };
14726 let body_top =
14727 padding.top + title_height + header_gap + description_height + metrics.dialog_body_gap;
14728 let footer_gap = if self.actions.is_empty() {
14729 0.0
14730 } else {
14731 metrics.dialog_footer_gap
14732 };
14733 let body_constraints = Constraints::new(
14734 Size::ZERO,
14735 Size::new(
14736 (dialog_width - padding.left - padding.right).max(0.0),
14737 (viewport.height
14738 - outer_margin * 2.0
14739 - body_top
14740 - footer_gap
14741 - footer_height
14742 - padding.bottom)
14743 .max(0.0),
14744 ),
14745 );
14746 let body_size = self.body.measure(ctx, body_constraints);
14747
14748 let dialog_height =
14749 body_top + body_size.height + footer_gap + footer_height + padding.bottom;
14750 let dialog_x = ((viewport.width - dialog_width) * 0.5).max(outer_margin);
14751 let dialog_y = ((viewport.height - dialog_height) * 0.5).max(outer_margin);
14752 self.dialog_frame = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
14753 self.body_frame = Rect::new(padding.left, body_top, body_size.width, body_size.height);
14754 {
14755 let mut focus = self.focus_state.borrow_mut();
14756 focus.theme = *self.theme;
14757 focus.shown = true;
14758 focus.frame = self.dialog_frame;
14759 focus.animation = self.focus_animation;
14760 }
14761 self.focus_surface
14762 .measure(ctx, Constraints::tight(self.dialog_frame.size));
14763
14764 viewport
14765 }
14766
14767 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
14768 if !self.shown {
14769 return;
14770 }
14771
14772 let dialog = self.dialog_frame.translate(bounds.origin.to_vector());
14773 self.focus_state.borrow_mut().frame = dialog;
14774 self.focus_surface.arrange(ctx, dialog);
14775 self.body.arrange(
14776 ctx,
14777 Rect::new(
14778 dialog.x() + self.body_frame.x(),
14779 dialog.y() + self.body_frame.y(),
14780 self.body_frame.width(),
14781 self.body_frame.height(),
14782 ),
14783 );
14784
14785 if !self.actions.is_empty() {
14786 let metrics = self.theme.metrics;
14787 let padding = metrics.dialog_padding;
14788 let action_gap = metrics.dialog_action_gap;
14789 let footer_width = self
14790 .actions
14791 .as_slice()
14792 .iter()
14793 .map(|button| button.measured_size().width)
14794 .sum::<f32>()
14795 + (action_gap * self.actions.len().saturating_sub(1) as f32);
14796 let footer_height = self
14797 .actions
14798 .as_slice()
14799 .iter()
14800 .map(|button| button.measured_size().height)
14801 .fold(0.0, f32::max);
14802 let mut x = dialog.x() + dialog.width() - padding.right - footer_width;
14803 let y = dialog.y() + dialog.height() - padding.bottom - footer_height;
14804 for button in self.actions.as_mut_slice().iter_mut() {
14805 let size = button.measured_size();
14806 button.arrange(ctx, Rect::new(x, y, size.width, size.height));
14807 x += size.width + action_gap;
14808 }
14809 }
14810 }
14811
14812 fn paint(&self, ctx: &mut PaintCtx) {
14813 if !self.shown {
14814 return;
14815 }
14816
14817 let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
14818
14819 if self.modal {
14820 ctx.fill_bounds(self.theme.surfaces.overlay_scrim);
14821 }
14822
14823 let metrics = self.theme.metrics;
14824 let palette = self.theme.palette;
14825 let surface_radius = metrics.corner_radius + 3.0;
14828 paint_theme_shadow(
14829 ctx,
14830 dialog,
14831 [surface_radius; 4],
14832 &self.theme.shadows.box_shadow.xl,
14833 );
14834 draw_control_frame(
14835 ctx,
14836 dialog,
14837 surface_radius,
14838 metrics,
14839 palette.surface_raised,
14840 palette.border,
14841 None,
14842 );
14843
14844 let title_style = self.title_style();
14845 let description_style = self.theme.placeholder_text_style();
14846 let padding = metrics.dialog_padding;
14847 let text_x = dialog.x() + padding.left;
14848 let text_y = dialog.y() + padding.top;
14849 let text_width = (dialog.width() - padding.left - padding.right).max(0.0);
14850 let title_height = self
14851 .title_measurement
14852 .map(|measurement| measurement.height.max(title_style.line_height))
14853 .unwrap_or(title_style.line_height);
14854 let title_slot = Rect::new(text_x, text_y, text_width, title_height);
14855 ctx.push_clip_rect(title_slot);
14856 paint_aligned_text(
14857 ctx,
14858 title_slot,
14859 &self.title,
14860 &title_style,
14861 title_style.line_height,
14862 0.0,
14863 );
14864 ctx.pop_clip();
14865 if let Some(description) = &self.description {
14866 let description_height = self
14867 .description_measurement
14868 .map(|measurement| measurement.height.max(description_style.line_height))
14869 .unwrap_or(description_style.line_height);
14870 let description_slot = Rect::new(
14871 text_x,
14872 title_slot.max_y() + metrics.dialog_description_gap,
14873 text_width,
14874 description_height,
14875 );
14876 ctx.push_clip_rect(description_slot);
14877 paint_aligned_text(
14878 ctx,
14879 description_slot,
14880 description,
14881 &description_style,
14882 description_style.line_height,
14883 0.0,
14884 );
14885 ctx.pop_clip();
14886 }
14887
14888 self.body.paint(ctx);
14889 for button in self.actions.as_slice() {
14890 button.paint(ctx);
14891 }
14892 self.focus_surface.paint(ctx);
14893 }
14894
14895 fn layer_options(&self) -> LayerOptions {
14896 LayerOptions {
14897 paint_boundary: PaintBoundaryMode::Explicit,
14898 composition_mode: if self.shown {
14899 if self.modal {
14900 LayerCompositionMode::Effect
14901 } else {
14902 LayerCompositionMode::Overlay
14903 }
14904 } else {
14905 LayerCompositionMode::Normal
14906 },
14907 }
14908 }
14909
14910 fn layer_properties(&self) -> LayerProperties {
14911 let translation = if self.modal {
14912 Vector::ZERO
14913 } else {
14914 Vector::new(
14915 0.0,
14916 self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
14917 )
14918 };
14919 LayerProperties::new(self.reveal.value, translation)
14920 }
14921
14922 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
14923 self.shown.then_some(StackSurfaceOptions {
14924 transient: true,
14925 ..StackSurfaceOptions::default()
14926 })
14927 }
14928
14929 fn overlay_options(&self) -> Option<OverlayOptions> {
14930 self.shown.then_some(
14931 OverlayOptions::new(self.overlay_kind)
14932 .modal(self.modal)
14933 .dismiss(OverlayDismissPolicy {
14934 escape: true,
14935 outside_pointer: self.dismiss_on_scrim,
14936 })
14937 .focus(OverlayFocusBehavior::CONTAINED),
14938 )
14939 }
14940
14941 fn semantics(&self, ctx: &mut SemanticsCtx) {
14942 if !self.shown {
14943 return;
14944 }
14945
14946 let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
14947 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Dialog, dialog);
14948 node.name = Some(self.title.clone());
14949 node.description = self.description.clone();
14950 node.state.focused = ctx.is_focused();
14951 node.state.expanded = Some(self.shown);
14952 node.state.modal = self.modal;
14953 node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
14954 ctx.push(node);
14955 self.body.semantics(ctx);
14956 for button in self.actions.as_slice() {
14957 button.semantics(ctx);
14958 }
14959 }
14960
14961 fn accepts_focus(&self) -> bool {
14962 true
14963 }
14964
14965 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
14966 let was_presented = self.focus_animation.is_presented();
14967 set_focus_animation_target(
14968 &mut self.focus_animation,
14969 focused as u8 as f32,
14970 &self.theme,
14971 ctx,
14972 );
14973 self.focus_state.borrow_mut().animation = self.focus_animation;
14974 request_child_invalidation(
14975 ctx,
14976 self.focus_surface.child().id(),
14977 InvalidationKind::Paint,
14978 );
14979 if was_presented != self.focus_animation.is_presented() {
14980 request_child_invalidation(
14981 ctx,
14982 self.focus_surface.child().id(),
14983 InvalidationKind::Visibility,
14984 );
14985 }
14986 ctx.request_semantics();
14987 }
14988
14989 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
14990 if self.shown {
14991 self.body.visit_children(visitor);
14992 self.actions.visit_children(visitor);
14993 self.focus_surface.visit_children(visitor);
14994 }
14995 }
14996
14997 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
14998 if self.shown {
14999 self.body.visit_children_mut(visitor);
15000 self.actions.visit_children_mut(visitor);
15001 self.focus_surface.visit_children_mut(visitor);
15002 }
15003 }
15004}
15005
15006pub struct CommandPalette {
15012 inner: Dialog,
15013}
15014
15015impl CommandPalette {
15016 pub fn new<W>(name: impl Into<String>, content: W) -> Self
15017 where
15018 W: Widget + 'static,
15019 {
15020 let mut inner = Dialog::new(name, content).dismiss_on_scrim(true);
15021 inner.overlay_kind = OverlayKind::CommandPalette;
15022 Self { inner }
15023 }
15024
15025 pub fn theme(mut self, theme: DefaultTheme) -> Self {
15026 self.inner = self.inner.theme(theme);
15027 self
15028 }
15029
15030 pub fn shown(mut self, shown: bool) -> Self {
15031 self.inner = self.inner.shown(shown);
15032 self
15033 }
15034
15035 pub fn description(mut self, description: impl Into<String>) -> Self {
15036 self.inner = self.inner.description(description);
15037 self
15038 }
15039
15040 pub fn max_width(mut self, max_width: f32) -> Self {
15041 self.inner = self.inner.max_width(max_width);
15042 self
15043 }
15044
15045 pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
15046 where
15047 F: FnMut() + 'static,
15048 {
15049 self.inner = self.inner.on_dismiss(on_dismiss);
15050 self
15051 }
15052}
15053
15054impl Widget for CommandPalette {
15055 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
15056 self.inner.command(ctx, command);
15057 }
15058
15059 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
15060 self.inner.event(ctx, event);
15061 }
15062
15063 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15064 self.inner.measure(ctx, constraints)
15065 }
15066
15067 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
15068 self.inner.arrange(ctx, bounds);
15069 }
15070
15071 fn paint(&self, ctx: &mut PaintCtx) {
15072 self.inner.paint(ctx);
15073 }
15074
15075 fn layer_options(&self) -> LayerOptions {
15076 self.inner.layer_options()
15077 }
15078
15079 fn layer_properties(&self) -> LayerProperties {
15080 self.inner.layer_properties()
15081 }
15082
15083 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
15084 self.inner.stack_surface_options()
15085 }
15086
15087 fn overlay_options(&self) -> Option<OverlayOptions> {
15088 self.inner.overlay_options()
15089 }
15090
15091 fn semantics(&self, ctx: &mut SemanticsCtx) {
15092 self.inner.semantics(ctx);
15093 }
15094
15095 fn accepts_focus(&self) -> bool {
15096 self.inner.accepts_focus()
15097 }
15098
15099 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
15100 self.inner.focus_changed(ctx, focused);
15101 }
15102
15103 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
15104 self.inner.visit_children(visitor);
15105 }
15106
15107 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
15108 self.inner.visit_children_mut(visitor);
15109 }
15110}
15111
15112pub type Modal = Dialog;
15113
15114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15115pub enum SideSheetPlacement {
15116 Left,
15117 #[default]
15118 Right,
15119 Bottom,
15120}
15121
15122#[derive(Clone, Debug)]
15124pub struct SheetState {
15125 shown: Signal<bool>,
15126}
15127
15128impl SheetState {
15129 pub fn new(shown: bool) -> Self {
15130 Self {
15131 shown: Signal::named("SheetState", shown),
15132 }
15133 }
15134
15135 pub fn is_shown(&self) -> bool {
15136 self.shown.get()
15137 }
15138
15139 pub fn show(&self) -> bool {
15140 self.shown.set(true)
15141 }
15142
15143 pub fn hide(&self) -> bool {
15144 self.shown.set(false)
15145 }
15146
15147 pub fn toggle(&self) -> bool {
15148 self.shown.update(|shown| *shown = !*shown)
15149 }
15150}
15151
15152impl Default for SheetState {
15153 fn default() -> Self {
15154 Self::new(false)
15155 }
15156}
15157
15158pub struct SideSheet {
15165 theme: Box<DefaultTheme>,
15166 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
15167 title: String,
15168 description: Option<String>,
15169 shown: bool,
15170 state: Option<SheetState>,
15171 modal: bool,
15172 dismiss_on_scrim: bool,
15173 placement: SideSheetPlacement,
15174 width: Option<f32>,
15175 height: Option<f32>,
15176 body: SingleChild,
15177 header_action: Option<SingleChild>,
15178 actions: WidgetChildren,
15179 sheet_frame: Rect,
15180 body_frame: Rect,
15181 header_action_frame: Rect,
15182 title_measurement: Option<TextMeasurement>,
15183 description_measurement: Option<TextMeasurement>,
15184 reveal: AnimatedScalar,
15185 focus_animation: AnimatedScalar,
15186 entrance_started: bool,
15187 focus_requested: bool,
15188 previous_focus: Option<WidgetId>,
15189 on_dismiss: Option<Box<dyn FnMut()>>,
15190}
15191
15192impl SideSheet {
15193 pub fn new<W>(title: impl Into<String>, body: W) -> Self
15194 where
15195 W: Widget + 'static,
15196 {
15197 Self {
15198 theme: Box::new(DefaultTheme::default()),
15199 theme_reader: None,
15200 title: title.into(),
15201 description: None,
15202 shown: true,
15203 state: None,
15204 modal: true,
15205 dismiss_on_scrim: true,
15206 placement: SideSheetPlacement::Right,
15207 width: None,
15208 height: None,
15209 body: SingleChild::new(body),
15210 header_action: None,
15211 actions: WidgetChildren::new(),
15212 sheet_frame: Rect::ZERO,
15213 body_frame: Rect::ZERO,
15214 header_action_frame: Rect::ZERO,
15215 title_measurement: None,
15216 description_measurement: None,
15217 reveal: AnimatedScalar::new(0.0),
15218 focus_animation: AnimatedScalar::new(0.0),
15219 entrance_started: false,
15220 focus_requested: false,
15221 previous_focus: None,
15222 on_dismiss: None,
15223 }
15224 }
15225
15226 pub fn theme(mut self, theme: DefaultTheme) -> Self {
15227 self.theme = Box::new(theme);
15228 self.theme_reader = None;
15229 self
15230 }
15231
15232 pub fn theme_when<F>(mut self, theme: F) -> Self
15233 where
15234 F: Fn() -> DefaultTheme + 'static,
15235 {
15236 self.theme_reader = Some(Box::new(theme));
15237 self
15238 }
15239
15240 pub fn description(mut self, description: impl Into<String>) -> Self {
15241 self.description = Some(description.into());
15242 self
15243 }
15244
15245 pub fn shown(mut self, shown: bool) -> Self {
15246 self.set_shown(shown);
15247 self
15248 }
15249
15250 pub fn is_shown(&self) -> bool {
15251 self.shown
15252 }
15253
15254 pub fn set_shown(&mut self, shown: bool) -> bool {
15255 self.state = None;
15256 if self.shown == shown {
15257 return false;
15258 }
15259 self.shown = shown;
15260 if !self.shown {
15261 self.reveal = AnimatedScalar::new(0.0);
15262 self.focus_animation = AnimatedScalar::new(0.0);
15263 self.entrance_started = false;
15264 self.focus_requested = false;
15265 self.previous_focus = None;
15266 }
15267 true
15268 }
15269
15270 pub fn state(mut self, state: SheetState) -> Self {
15271 self.shown = state.is_shown();
15272 self.state = Some(state);
15273 self
15274 }
15275
15276 pub fn modal(mut self, modal: bool) -> Self {
15277 self.modal = modal;
15278 self
15279 }
15280
15281 pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
15282 self.dismiss_on_scrim = dismiss_on_scrim;
15283 self
15284 }
15285
15286 pub fn placement(mut self, placement: SideSheetPlacement) -> Self {
15287 self.placement = placement;
15288 self
15289 }
15290
15291 pub fn width(mut self, width: f32) -> Self {
15292 self.width = Some(width.max(0.0));
15293 self
15294 }
15295
15296 pub fn height(mut self, height: f32) -> Self {
15298 self.height = Some(height.max(0.0));
15299 self
15300 }
15301
15302 pub fn header_action<W>(mut self, action: W) -> Self
15303 where
15304 W: Widget + 'static,
15305 {
15306 self.header_action = Some(SingleChild::new(action));
15307 self
15308 }
15309
15310 pub fn action<W>(mut self, action: W) -> Self
15311 where
15312 W: Widget + 'static,
15313 {
15314 self.actions.push(action);
15315 self
15316 }
15317
15318 pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15319 where
15320 F: FnMut() + 'static,
15321 {
15322 let theme = self.resolved_theme();
15323 self.actions.push(
15324 Button::new(label)
15325 .theme(theme)
15326 .min_width(theme.metrics.dialog_action_min_width)
15327 .on_press(on_press),
15328 );
15329 self
15330 }
15331
15332 pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15333 where
15334 F: FnMut() + 'static,
15335 {
15336 let theme = self.resolved_theme();
15337 self.actions.push(
15338 Button::new(label)
15339 .theme(theme)
15340 .appearance(ButtonAppearance::Outline)
15341 .tone(SemanticTone::Neutral)
15342 .min_width(theme.metrics.dialog_action_min_width)
15343 .on_press(on_press),
15344 );
15345 self
15346 }
15347
15348 pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
15349 where
15350 F: FnMut() + 'static,
15351 {
15352 self.on_dismiss = Some(Box::new(on_dismiss));
15353 self
15354 }
15355
15356 fn resolved_theme(&self) -> DefaultTheme {
15357 self.theme_reader
15358 .as_ref()
15359 .map(|theme| theme())
15360 .unwrap_or(*self.theme)
15361 }
15362
15363 fn resolved_width(&self, viewport_width: f32, theme: &DefaultTheme) -> f32 {
15364 self.width
15365 .unwrap_or(theme.metrics.dialog_max_width.min(420.0))
15366 .max(theme.metrics.dialog_min_width.min(viewport_width))
15367 .min(viewport_width)
15368 .max(0.0)
15369 }
15370
15371 fn resolved_height(&self, viewport_height: f32, theme: &DefaultTheme) -> f32 {
15372 self.height
15373 .unwrap_or((viewport_height * 0.62).min(560.0))
15374 .max(theme.metrics.touch_target_size * 3.0)
15375 .min(viewport_height)
15376 .max(0.0)
15377 }
15378
15379 fn title_style(theme: &DefaultTheme) -> TextStyle {
15380 text_token_style(theme, theme.text.lg, theme.palette.text)
15381 }
15382
15383 fn dismiss(&mut self, ctx: &mut EventCtx) {
15384 if let Some(state) = &self.state {
15385 state.hide();
15386 self.shown = false;
15387 ctx.request_measure();
15388 ctx.request_paint();
15389 }
15390 if let Some(on_dismiss) = &mut self.on_dismiss {
15391 on_dismiss();
15392 }
15393 if let Some(previous_focus) = self.previous_focus.take() {
15394 ctx.request_focus_for(previous_focus);
15395 }
15396 }
15397
15398 fn contains_widget(&self, target: WidgetId) -> bool {
15399 struct Finder {
15400 target: WidgetId,
15401 found: bool,
15402 }
15403
15404 impl WidgetPodVisitor for Finder {
15405 fn visit(&mut self, child: &WidgetPod) {
15406 if self.found {
15407 return;
15408 }
15409 if child.id() == self.target {
15410 self.found = true;
15411 } else {
15412 child.visit_children(self);
15413 }
15414 }
15415 }
15416
15417 fn inspect(pod: &WidgetPod, finder: &mut Finder) {
15418 if finder.found {
15419 return;
15420 }
15421 if pod.id() == finder.target {
15422 finder.found = true;
15423 } else {
15424 pod.visit_children(finder);
15425 }
15426 }
15427
15428 let mut finder = Finder {
15429 target,
15430 found: false,
15431 };
15432 inspect(self.body.child(), &mut finder);
15433 if let Some(action) = &self.header_action {
15434 inspect(action.child(), &mut finder);
15435 }
15436 for action in self.actions.as_slice() {
15437 inspect(action, &mut finder);
15438 }
15439 finder.found
15440 }
15441
15442 fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
15443 if self.entrance_started {
15444 return;
15445 }
15446 self.entrance_started = true;
15447 let motion = self.resolved_theme().motion;
15448 let reveal_animating = self.reveal.set_target(
15449 1.0,
15450 ctx.current_time(),
15451 f64::from(motion.duration_slower),
15452 motion.easing_decelerate,
15453 );
15454 if reveal_animating || !self.focus_requested {
15455 ctx.request_animation_frame();
15456 }
15457 }
15458
15459 fn reveal_offset(&self) -> Vector {
15460 let horizontal_distance = self.sheet_frame.width() * (1.0 - self.reveal.value);
15461 let vertical_distance = self.sheet_frame.height() * (1.0 - self.reveal.value);
15462 match self.placement {
15463 SideSheetPlacement::Left => Vector::new(-horizontal_distance, 0.0),
15464 SideSheetPlacement::Right => Vector::new(horizontal_distance, 0.0),
15465 SideSheetPlacement::Bottom => Vector::new(0.0, vertical_distance),
15466 }
15467 }
15468
15469 fn presented_sheet(&self, origin: Point) -> Rect {
15470 self.sheet_frame
15471 .translate(origin.to_vector() + self.reveal_offset())
15472 }
15473}
15474
15475impl Widget for SideSheet {
15476 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
15477 if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.is_shown() {
15478 self.dismiss(ctx);
15479 ctx.set_handled();
15480 }
15481 }
15482
15483 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
15484 if let Some(state) = &self.state {
15485 self.shown = state.is_shown();
15486 }
15487 if !self.shown {
15488 return;
15489 }
15490 match event {
15491 Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
15492 if !self.focus_requested {
15493 self.focus_requested = true;
15494 let current_focus = ctx.focused_widget_id();
15495 let focus_is_inside = current_focus.is_some_and(|focused| {
15496 focused == ctx.widget_id() || self.contains_widget(focused)
15497 });
15498 if !focus_is_inside {
15499 self.previous_focus = current_focus;
15500 ctx.request_focus();
15501 }
15502 }
15503 let previous = self.reveal.value;
15504 let previous_focus = self.focus_animation.value;
15505 if self.reveal.advance(*time) | self.focus_animation.advance(*time) {
15506 ctx.request_animation_frame();
15507 }
15508 if self.reveal.changed_since(previous)
15509 || self.focus_animation.changed_since(previous_focus)
15510 {
15511 ctx.request_paint();
15512 }
15513 ctx.set_handled();
15514 }
15515 Event::Semantics(semantics)
15516 if semantics.target == ctx.widget_id()
15517 && matches!(semantics.action, sui_core::SemanticsActionRequest::Collapse) =>
15518 {
15519 self.dismiss(ctx);
15520 ctx.request_semantics();
15521 ctx.set_handled();
15522 }
15523 Event::Pointer(pointer)
15524 if pointer.kind == PointerEventKind::Down
15525 && pointer.button == Some(PointerButton::Primary) =>
15526 {
15527 if self
15528 .presented_sheet(ctx.bounds().origin)
15529 .contains(pointer.position)
15530 {
15531 ctx.request_focus();
15532 ctx.request_semantics();
15533 } else {
15534 if self.dismiss_on_scrim {
15535 self.dismiss(ctx);
15536 }
15537 if self.modal || self.dismiss_on_scrim {
15538 ctx.set_handled();
15539 }
15540 ctx.request_semantics();
15541 }
15542 }
15543 Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape" => {
15544 self.dismiss(ctx);
15545 ctx.request_semantics();
15546 ctx.set_handled();
15547 }
15548 _ => {}
15549 }
15550 }
15551
15552 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15553 if let Some(state) = &self.state {
15554 self.shown = ctx.observe(&state.shown);
15555 }
15556 if !self.shown {
15557 self.sheet_frame = Rect::ZERO;
15558 self.body_frame = Rect::ZERO;
15559 self.header_action_frame = Rect::ZERO;
15560 self.reveal = AnimatedScalar::new(0.0);
15561 self.focus_animation = AnimatedScalar::new(0.0);
15562 self.entrance_started = false;
15563 self.focus_requested = false;
15564 self.previous_focus = None;
15565 return Size::ZERO;
15566 }
15567 self.ensure_entrance_started(ctx);
15568
15569 let viewport = constraints.clamp(Size::new(
15570 if constraints.max.width.is_finite() {
15571 constraints.max.width
15572 } else {
15573 960.0
15574 },
15575 if constraints.max.height.is_finite() {
15576 constraints.max.height
15577 } else {
15578 640.0
15579 },
15580 ));
15581 let theme = self.resolved_theme();
15582 let metrics = theme.metrics;
15583 let padding = metrics.dialog_padding;
15584 let (sheet_x, sheet_y, sheet_width, sheet_height) = match self.placement {
15585 SideSheetPlacement::Left => (
15586 0.0,
15587 0.0,
15588 self.resolved_width(viewport.width, &theme),
15589 viewport.height,
15590 ),
15591 SideSheetPlacement::Right => {
15592 let width = self.resolved_width(viewport.width, &theme);
15593 (viewport.width - width, 0.0, width, viewport.height)
15594 }
15595 SideSheetPlacement::Bottom => {
15596 let height = self.resolved_height(viewport.height, &theme);
15597 (0.0, viewport.height - height, viewport.width, height)
15598 }
15599 };
15600 self.sheet_frame = Rect::new(sheet_x, sheet_y, sheet_width, sheet_height);
15601
15602 let title_style = Self::title_style(&theme);
15603 let description_style = theme.placeholder_text_style();
15604 self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
15605 self.description_measurement = self
15606 .description
15607 .as_ref()
15608 .map(|description| measure_text(ctx, description, &description_style));
15609
15610 let header_action_size = if let Some(action) = &mut self.header_action {
15611 action.measure(
15612 ctx,
15613 Constraints::new(
15614 Size::ZERO,
15615 Size::new(
15616 (sheet_width - padding.left - padding.right).max(0.0),
15617 metrics.touch_target_size,
15618 ),
15619 ),
15620 )
15621 } else {
15622 Size::ZERO
15623 };
15624 let title_height = self
15625 .title_measurement
15626 .map(|measurement| measurement.height.max(title_style.line_height))
15627 .unwrap_or(title_style.line_height)
15628 .max(header_action_size.height);
15629 let description_height = self
15630 .description_measurement
15631 .map(|measurement| measurement.height.max(description_style.line_height))
15632 .unwrap_or(0.0);
15633 let description_gap = if self.description.is_some() {
15634 metrics.dialog_description_gap
15635 } else {
15636 0.0
15637 };
15638 let body_top = padding.top
15639 + title_height
15640 + description_gap
15641 + description_height
15642 + metrics.dialog_body_gap;
15643
15644 let mut footer_height: f32 = 0.0;
15645 for action in self.actions.as_mut_slice() {
15646 footer_height = footer_height.max(
15647 action
15648 .measure(
15649 ctx,
15650 Constraints::new(
15651 Size::ZERO,
15652 Size::new(sheet_width, metrics.touch_target_size),
15653 ),
15654 )
15655 .height,
15656 );
15657 }
15658 let footer_gap = if self.actions.is_empty() {
15659 0.0
15660 } else {
15661 metrics.dialog_footer_gap
15662 };
15663 let body_height =
15664 (sheet_height - body_top - footer_gap - footer_height - padding.bottom).max(0.0);
15665 let body_width = (sheet_width - padding.left - padding.right).max(0.0);
15666 let _ = self.body.measure(
15667 ctx,
15668 Constraints::new(Size::ZERO, Size::new(body_width, body_height)),
15669 );
15670 self.body_frame = Rect::new(padding.left, body_top, body_width, body_height);
15671 self.header_action_frame = Rect::new(
15672 sheet_width - padding.right - header_action_size.width,
15673 padding.top,
15674 header_action_size.width,
15675 header_action_size.height,
15676 );
15677 viewport
15678 }
15679
15680 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
15681 if !self.shown {
15682 return;
15683 }
15684 let sheet = self.sheet_frame.translate(bounds.origin.to_vector());
15685 self.body
15686 .arrange(ctx, self.body_frame.translate(sheet.origin.to_vector()));
15687 if let Some(action) = &mut self.header_action {
15688 action.arrange(
15689 ctx,
15690 self.header_action_frame.translate(sheet.origin.to_vector()),
15691 );
15692 }
15693 if !self.actions.is_empty() {
15694 let theme = self.resolved_theme();
15695 let metrics = theme.metrics;
15696 let padding = metrics.dialog_padding;
15697 let gap = metrics.dialog_action_gap;
15698 let total_width = self
15699 .actions
15700 .as_slice()
15701 .iter()
15702 .map(|action| action.measured_size().width)
15703 .sum::<f32>()
15704 + gap * self.actions.len().saturating_sub(1) as f32;
15705 let footer_height = self
15706 .actions
15707 .as_slice()
15708 .iter()
15709 .map(|action| action.measured_size().height)
15710 .fold(0.0, f32::max);
15711 let mut x = sheet.max_x() - padding.right - total_width;
15712 let y = sheet.max_y() - padding.bottom - footer_height;
15713 for action in self.actions.as_mut_slice() {
15714 let size = action.measured_size();
15715 action.arrange(ctx, Rect::new(x, y, size.width, size.height));
15716 x += size.width + gap;
15717 }
15718 }
15719 }
15720
15721 fn paint(&self, ctx: &mut PaintCtx) {
15722 if !self.shown {
15723 return;
15724 }
15725 let theme = self.resolved_theme();
15726 if self.modal {
15727 let scrim = theme
15728 .surfaces
15729 .overlay_scrim
15730 .with_alpha(theme.surfaces.overlay_scrim.alpha * self.reveal.value);
15731 ctx.fill_bounds(scrim);
15732 }
15733
15734 let reveal_offset = self.reveal_offset();
15735 ctx.push_transform(Transform::translation(reveal_offset.x, reveal_offset.y));
15736 let sheet = self.sheet_frame.translate(ctx.bounds().origin.to_vector());
15737 let metrics = theme.metrics;
15738 paint_theme_shadow(ctx, sheet, [0.0; 4], &theme.shadows.box_shadow.xl);
15739 ctx.fill_rect(sheet, theme.palette.surface_raised);
15740 let border_width = physical_pixels(ctx, metrics.border_width.max(1.0));
15741 let border = match self.placement {
15742 SideSheetPlacement::Left => Rect::new(
15743 sheet.max_x() - border_width,
15744 sheet.y(),
15745 border_width,
15746 sheet.height(),
15747 ),
15748 SideSheetPlacement::Right => {
15749 Rect::new(sheet.x(), sheet.y(), border_width, sheet.height())
15750 }
15751 SideSheetPlacement::Bottom => {
15752 Rect::new(sheet.x(), sheet.y(), sheet.width(), border_width)
15753 }
15754 };
15755 ctx.fill_rect(border, theme.palette.border);
15756 if self.focus_animation.value > AnimatedScalar::EPSILON {
15757 let inset = physical_pixels(ctx, theme.metrics.focus_ring_width) * 0.5;
15758 ctx.stroke(
15759 rounded_rect_path(sheet.inflate(-inset, -inset), 0.0),
15760 theme
15761 .palette
15762 .focus_ring
15763 .with_alpha(theme.palette.focus_ring.alpha * self.focus_animation.value),
15764 StrokeStyle::new(physical_pixels(ctx, theme.metrics.focus_ring_width)),
15765 );
15766 }
15767
15768 let padding = metrics.dialog_padding;
15769 let title_style = Self::title_style(&theme);
15770 let action_width = if self.header_action.is_some() {
15771 self.header_action_frame.width() + metrics.dialog_action_gap
15772 } else {
15773 0.0
15774 };
15775 let title_height = self
15776 .title_measurement
15777 .map(|measurement| measurement.height.max(title_style.line_height))
15778 .unwrap_or(title_style.line_height)
15779 .max(self.header_action_frame.height());
15780 let title_slot = Rect::new(
15781 sheet.x() + padding.left,
15782 sheet.y() + padding.top,
15783 (sheet.width() - padding.left - padding.right - action_width).max(0.0),
15784 title_height,
15785 );
15786 paint_aligned_text(
15787 ctx,
15788 title_slot,
15789 &self.title,
15790 &title_style,
15791 title_style.line_height,
15792 0.0,
15793 );
15794 if let Some(description) = &self.description {
15795 let style = theme.placeholder_text_style();
15796 let height = self
15797 .description_measurement
15798 .map(|measurement| measurement.height.max(style.line_height))
15799 .unwrap_or(style.line_height);
15800 let slot = Rect::new(
15801 sheet.x() + padding.left,
15802 title_slot.max_y() + metrics.dialog_description_gap,
15803 (sheet.width() - padding.left - padding.right).max(0.0),
15804 height,
15805 );
15806 paint_aligned_text(ctx, slot, description, &style, style.line_height, 0.0);
15807 }
15808 self.body.paint(ctx);
15809 if let Some(action) = &self.header_action {
15810 action.paint(ctx);
15811 }
15812 self.actions.paint(ctx);
15813 ctx.pop_transform();
15814 }
15815
15816 fn layer_options(&self) -> LayerOptions {
15817 LayerOptions {
15818 paint_boundary: PaintBoundaryMode::Explicit,
15819 composition_mode: if self.shown {
15820 LayerCompositionMode::Overlay
15821 } else {
15822 LayerCompositionMode::Normal
15823 },
15824 }
15825 }
15826
15827 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
15828 self.shown.then_some(StackSurfaceOptions {
15829 transient: true,
15830 ..StackSurfaceOptions::default()
15831 })
15832 }
15833
15834 fn overlay_options(&self) -> Option<OverlayOptions> {
15835 self.is_shown().then_some(
15836 OverlayOptions::new(OverlayKind::Sheet)
15837 .modal(self.modal)
15838 .dismiss(OverlayDismissPolicy {
15839 escape: true,
15840 outside_pointer: self.dismiss_on_scrim,
15841 })
15842 .focus(OverlayFocusBehavior::CONTAINED),
15843 )
15844 }
15845
15846 fn semantics(&self, ctx: &mut SemanticsCtx) {
15847 if !self.shown {
15848 return;
15849 }
15850 let mut node = SemanticsNode::new(
15851 ctx.widget_id(),
15852 SemanticsRole::Dialog,
15853 self.sheet_frame.translate(ctx.bounds().origin.to_vector()),
15854 );
15855 node.name = Some(self.title.clone());
15856 node.description = self.description.clone();
15857 node.state.focused = ctx.is_focused();
15858 node.state.expanded = Some(true);
15859 node.state.modal = self.modal;
15860 node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
15861 ctx.push(node);
15862 self.body.semantics(ctx);
15863 if let Some(action) = &self.header_action {
15864 action.semantics(ctx);
15865 }
15866 self.actions.semantics(ctx);
15867 }
15868
15869 fn accepts_focus(&self) -> bool {
15870 self.shown
15871 }
15872
15873 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
15874 let theme = self.resolved_theme();
15875 set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
15876 ctx.request_paint();
15877 ctx.request_semantics();
15878 }
15879
15880 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
15881 if self.shown {
15882 self.body.visit_children(visitor);
15883 if let Some(action) = &self.header_action {
15884 action.visit_children(visitor);
15885 }
15886 self.actions.visit_children(visitor);
15887 }
15888 }
15889
15890 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
15891 if self.shown {
15892 self.body.visit_children_mut(visitor);
15893 if let Some(action) = &mut self.header_action {
15894 action.visit_children_mut(visitor);
15895 }
15896 self.actions.visit_children_mut(visitor);
15897 }
15898 }
15899}
15900
15901pub type Drawer = SideSheet;
15903
15904pub struct BottomSheet {
15909 inner: SideSheet,
15910}
15911
15912impl BottomSheet {
15913 pub fn new<W>(title: impl Into<String>, body: W) -> Self
15914 where
15915 W: Widget + 'static,
15916 {
15917 Self {
15918 inner: SideSheet::new(title, body).placement(SideSheetPlacement::Bottom),
15919 }
15920 }
15921
15922 pub fn theme(mut self, theme: DefaultTheme) -> Self {
15923 self.inner = self.inner.theme(theme);
15924 self
15925 }
15926
15927 pub fn theme_when<F>(mut self, theme: F) -> Self
15928 where
15929 F: Fn() -> DefaultTheme + 'static,
15930 {
15931 self.inner = self.inner.theme_when(theme);
15932 self
15933 }
15934
15935 pub fn description(mut self, description: impl Into<String>) -> Self {
15936 self.inner = self.inner.description(description);
15937 self
15938 }
15939
15940 pub fn shown(mut self, shown: bool) -> Self {
15941 self.inner = self.inner.shown(shown);
15942 self
15943 }
15944
15945 pub fn state(mut self, state: SheetState) -> Self {
15946 self.inner = self.inner.state(state);
15947 self
15948 }
15949
15950 pub fn modal(mut self, modal: bool) -> Self {
15951 self.inner = self.inner.modal(modal);
15952 self
15953 }
15954
15955 pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
15956 self.inner = self.inner.dismiss_on_scrim(dismiss);
15957 self
15958 }
15959
15960 pub fn height(mut self, height: f32) -> Self {
15961 self.inner = self.inner.height(height);
15962 self
15963 }
15964
15965 pub fn header_action<W>(mut self, action: W) -> Self
15966 where
15967 W: Widget + 'static,
15968 {
15969 self.inner = self.inner.header_action(action);
15970 self
15971 }
15972
15973 pub fn action<W>(mut self, action: W) -> Self
15974 where
15975 W: Widget + 'static,
15976 {
15977 self.inner = self.inner.action(action);
15978 self
15979 }
15980
15981 pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15982 where
15983 F: FnMut() + 'static,
15984 {
15985 self.inner = self.inner.primary_action(label, on_press);
15986 self
15987 }
15988
15989 pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15990 where
15991 F: FnMut() + 'static,
15992 {
15993 self.inner = self.inner.secondary_action(label, on_press);
15994 self
15995 }
15996
15997 pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
15998 where
15999 F: FnMut() + 'static,
16000 {
16001 self.inner = self.inner.on_dismiss(on_dismiss);
16002 self
16003 }
16004}
16005
16006impl Widget for BottomSheet {
16007 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
16008 self.inner.command(ctx, command);
16009 }
16010
16011 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
16012 self.inner.event(ctx, event);
16013 }
16014
16015 fn debug_name(&self) -> &'static str {
16016 "sui_widgets::BottomSheet"
16017 }
16018
16019 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
16020 self.inner.measure(ctx, constraints)
16021 }
16022
16023 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
16024 self.inner.arrange(ctx, bounds);
16025 }
16026
16027 fn paint(&self, ctx: &mut PaintCtx) {
16028 self.inner.paint(ctx);
16029 }
16030
16031 fn layer_options(&self) -> LayerOptions {
16032 self.inner.layer_options()
16033 }
16034
16035 fn layer_properties(&self) -> LayerProperties {
16036 self.inner.layer_properties()
16037 }
16038
16039 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
16040 self.inner.stack_surface_options()
16041 }
16042
16043 fn overlay_options(&self) -> Option<OverlayOptions> {
16044 self.inner.overlay_options()
16045 }
16046
16047 fn semantics(&self, ctx: &mut SemanticsCtx) {
16048 self.inner.semantics(ctx);
16049 }
16050
16051 fn accepts_focus(&self) -> bool {
16052 self.inner.accepts_focus()
16053 }
16054
16055 fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
16056 self.inner.focus_changed(ctx, focused);
16057 }
16058
16059 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
16060 self.inner.visit_children(visitor);
16061 }
16062
16063 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
16064 self.inner.visit_children_mut(visitor);
16065 }
16066}
16067
16068pub struct ProgressBar {
16069 theme: Box<DefaultTheme>,
16070 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
16071 name: String,
16072 min: f64,
16073 max: f64,
16074 value: f64,
16075 tone: SemanticTone,
16076 min_width: Option<f32>,
16077 height: Option<f32>,
16078 show_value: bool,
16079}
16080
16081impl ProgressBar {
16082 pub fn new(name: impl Into<String>) -> Self {
16083 Self {
16084 theme: Box::new(DefaultTheme::default()),
16085 theme_reader: None,
16086 name: name.into(),
16087 min: 0.0,
16088 max: 1.0,
16089 value: 0.0,
16090 tone: SemanticTone::Accent,
16091 min_width: None,
16092 height: None,
16093 show_value: false,
16094 }
16095 }
16096
16097 pub fn theme(mut self, theme: DefaultTheme) -> Self {
16098 self.theme = Box::new(theme);
16099 self.theme_reader = None;
16100 self
16101 }
16102
16103 pub fn theme_when<F>(mut self, theme: F) -> Self
16104 where
16105 F: Fn() -> DefaultTheme + 'static,
16106 {
16107 self.theme_reader = Some(Box::new(theme));
16108 self
16109 }
16110
16111 pub fn range(mut self, min: f64, max: f64) -> Self {
16112 self.min = min.min(max);
16113 self.max = max.max(min);
16114 self.value = self.value.clamp(self.min, self.max);
16115 self
16116 }
16117
16118 pub fn value(mut self, value: f64) -> Self {
16119 self.value = value.clamp(self.min, self.max);
16120 self
16121 }
16122
16123 pub fn tone(mut self, tone: SemanticTone) -> Self {
16124 self.tone = tone;
16125 self
16126 }
16127
16128 pub fn min_width(mut self, min_width: f32) -> Self {
16129 self.min_width = Some(min_width.max(0.0));
16130 self
16131 }
16132
16133 pub fn height(mut self, height: f32) -> Self {
16134 self.height = Some(height.max(1.0));
16135 self
16136 }
16137
16138 pub fn show_value(mut self, show_value: bool) -> Self {
16139 self.show_value = show_value;
16140 self
16141 }
16142
16143 fn fraction(&self) -> f32 {
16144 if (self.max - self.min).abs() <= f64::EPSILON {
16145 0.0
16146 } else {
16147 ((self.value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) as f32
16148 }
16149 }
16150
16151 fn resolved_theme(&self) -> DefaultTheme {
16152 self.theme_reader
16153 .as_ref()
16154 .map(|theme| theme())
16155 .unwrap_or(*self.theme)
16156 }
16157}
16158
16159pub fn paint_progress_bar(
16160 ctx: &mut PaintCtx,
16161 rect: Rect,
16162 theme: &DefaultTheme,
16163 fraction: f32,
16164 tone: SemanticTone,
16165) {
16166 if rect.width() <= 0.0 || rect.height() <= 0.0 {
16167 return;
16168 }
16169
16170 let metrics = theme.metrics;
16171 let palette = theme.palette;
16172 let (tone, _) = theme.semantic_tone_colors(tone);
16173 draw_control_shape(
16174 ctx,
16175 rect,
16176 metrics.corner_radius,
16177 physical_pixels(ctx, metrics.border_width).min(rect.height() * 0.5),
16178 palette.control,
16179 palette.border,
16180 );
16181
16182 let fill = Rect::new(
16183 rect.x(),
16184 rect.y(),
16185 rect.width() * fraction.clamp(0.0, 1.0),
16186 rect.height(),
16187 );
16188 if fill.width() > 0.0 {
16189 ctx.fill(rounded_rect_path(fill, metrics.corner_radius), tone);
16190 }
16191}
16192
16193impl Widget for ProgressBar {
16194 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
16195 let theme = self.resolved_theme();
16196 let metrics = theme.metrics;
16197 let min_height = if let Some(height) = self.height {
16198 height
16199 } else if self.show_value {
16200 metrics
16201 .progress_bar_value_height
16202 .max(text_token_style(&theme, theme.text.sm, theme.palette.text).line_height)
16203 } else {
16204 metrics.progress_bar_height
16205 };
16206 constraints.clamp(Size::new(
16207 self.min_width.unwrap_or(metrics.progress_bar_min_width),
16208 min_height,
16209 ))
16210 }
16211
16212 fn paint(&self, ctx: &mut PaintCtx) {
16213 let theme = self.resolved_theme();
16214 let metrics = theme.metrics;
16215 let (_, tone_text) = theme.semantic_tone_colors(self.tone);
16216 paint_progress_bar(ctx, ctx.bounds(), &theme, self.fraction(), self.tone);
16217 if self.show_value {
16218 let label = format!("{:.0}%", self.fraction() * 100.0);
16219 let text_style = numeric_text_style(text_token_style(&theme, theme.text.sm, tone_text));
16220 let label_padding = Insets {
16221 top: 0.0,
16222 bottom: 0.0,
16223 ..metrics.progress_bar_label_padding
16224 };
16225 let label_slot = inset_rect(ctx.bounds(), label_padding);
16226 ctx.push_clip_rect(label_slot);
16227 paint_aligned_text(
16228 ctx,
16229 label_slot,
16230 &label,
16231 &text_style,
16232 text_style.line_height,
16233 0.5,
16234 );
16235 ctx.pop_clip();
16236 }
16237 }
16238
16239 fn semantics(&self, ctx: &mut SemanticsCtx) {
16240 let mut node =
16241 SemanticsNode::new(ctx.widget_id(), SemanticsRole::ProgressBar, ctx.bounds());
16242 node.name = Some(self.name.clone());
16243 node.value = Some(SemanticsValue::Range {
16244 value: self.value,
16245 min: self.min,
16246 max: self.max,
16247 });
16248 ctx.push(node);
16249 }
16250}
16251
16252pub struct Spinner {
16253 theme: Box<DefaultTheme>,
16254 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
16255 name: String,
16256 size: f32,
16257 label: Option<String>,
16258}
16259
16260impl Spinner {
16261 pub fn new(name: impl Into<String>) -> Self {
16262 Self {
16263 theme: Box::new(DefaultTheme::default()),
16264 theme_reader: None,
16265 name: name.into(),
16266 size: 20.0,
16267 label: None,
16268 }
16269 }
16270
16271 pub fn theme(mut self, theme: DefaultTheme) -> Self {
16272 self.theme = Box::new(theme);
16273 self.theme_reader = None;
16274 self
16275 }
16276
16277 pub fn theme_when<F>(mut self, theme: F) -> Self
16278 where
16279 F: Fn() -> DefaultTheme + 'static,
16280 {
16281 self.theme_reader = Some(Box::new(theme));
16282 self
16283 }
16284
16285 pub fn size(mut self, size: f32) -> Self {
16286 self.size = size.max(8.0);
16287 self
16288 }
16289
16290 pub fn label(mut self, label: impl Into<String>) -> Self {
16291 self.label = Some(label.into());
16292 self
16293 }
16294
16295 fn indicator_rect(&self, bounds: Rect) -> Rect {
16296 Rect::new(
16297 bounds.x(),
16298 bounds.y() + ((bounds.height() - self.size) * 0.5),
16299 self.size,
16300 self.size,
16301 )
16302 }
16303
16304 fn resolved_theme(&self) -> DefaultTheme {
16305 self.theme_reader
16306 .as_ref()
16307 .map(|theme| theme())
16308 .unwrap_or(*self.theme)
16309 }
16310}
16311
16312impl Widget for Spinner {
16313 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
16314 let theme = self.resolved_theme();
16315 let text_style = text_token_style(&theme, theme.text.sm, theme.palette.text);
16316 let label_measurement = self
16317 .label
16318 .as_ref()
16319 .map(|label| measure_text(ctx, label, &text_style));
16320 let label_width = label_measurement
16321 .map(|measurement| measurement.width + 12.0)
16322 .unwrap_or(0.0);
16323 let label_height = label_measurement
16324 .map(|measurement| measurement.height.max(text_style.line_height))
16325 .unwrap_or(0.0);
16326 constraints.clamp(Size::new(
16327 self.size + label_width,
16328 self.size.max(20.0).max(label_height),
16329 ))
16330 }
16331
16332 fn paint(&self, ctx: &mut PaintCtx) {
16333 let theme = self.resolved_theme();
16334 let palette = theme.palette;
16335 let indicator = self.indicator_rect(ctx.bounds());
16336 let center = rect_center(indicator);
16337 let radius = indicator.width().min(indicator.height()) * 0.4;
16338 let dot_radius = (indicator.width() * 0.09).max(1.5);
16339 for index in 0..10 {
16340 let angle = (index as f32 / 10.0) * std::f32::consts::TAU;
16341 let alpha = 0.22 + ((index as f32) / 10.0) * 0.72;
16342 let color = Color::rgba(
16343 palette.accent.red,
16344 palette.accent.green,
16345 palette.accent.blue,
16346 alpha,
16347 );
16348 let dot = Point::new(
16349 center.x + angle.cos() * radius,
16350 center.y + angle.sin() * radius,
16351 );
16352 ctx.fill(Path::circle(dot, dot_radius), color);
16353 }
16354
16355 if let Some(label) = &self.label {
16356 let text_style = text_token_style(&theme, theme.text.sm, palette.text);
16357 let text_slot = Rect::new(
16358 indicator.max_x() + 12.0,
16359 ctx.bounds().y(),
16360 ctx.bounds().width() - indicator.width() - 12.0,
16361 ctx.bounds().height(),
16362 );
16363 ctx.push_clip_rect(text_slot);
16364 paint_aligned_text(
16365 ctx,
16366 text_slot,
16367 label,
16368 &text_style,
16369 text_style.line_height,
16370 0.0,
16371 );
16372 ctx.pop_clip();
16373 }
16374 }
16375
16376 fn semantics(&self, ctx: &mut SemanticsCtx) {
16377 let mut node =
16378 SemanticsNode::new(ctx.widget_id(), SemanticsRole::BusyIndicator, ctx.bounds());
16379 node.name = Some(self.name.clone());
16380 node.description = self.label.clone();
16381 node.state.busy = true;
16382 ctx.push(node);
16383 }
16384}
16385
16386pub type BusyIndicator = Spinner;
16387
16388fn measure_text(ctx: &mut MeasureCtx, text: &str, style: &TextStyle) -> TextMeasurement {
16389 ctx.layout()
16390 .measure_text(text.to_string(), style.clone())
16391 .unwrap_or(TextMeasurement {
16392 width: 0.0,
16393 height: style.line_height,
16394 bounds: Rect::new(0.0, 0.0, 0.0, style.line_height),
16395 ascent: style.font_size,
16396 descent: 0.0,
16397 cap_height: Some(style.font_size),
16398 })
16399}
16400
16401fn text_token_style(theme: &DefaultTheme, token: ThemeTextToken, color: Color) -> TextStyle {
16402 TextStyle {
16403 font_size: token.size.max(1.0),
16404 line_height: token.line_height.max(1.0),
16405 color,
16406 ..theme.body_text_style()
16407 }
16408}
16409
16410fn semibold_control_text_style(theme: &DefaultTheme, color: Color) -> TextStyle {
16411 let mut style = theme.text_style(color);
16412 style.weight = FontWeight::SEMIBOLD;
16413 style
16414}
16415
16416fn numeric_text_style(mut style: TextStyle) -> TextStyle {
16417 style.features.enable(FontFeature::TABULAR_FIGURES);
16418 style
16419}
16420
16421fn numeric_text_style_if_numeric(text: &str, style: TextStyle) -> TextStyle {
16422 if text_contains_ascii_digit(text) {
16423 numeric_text_style(style)
16424 } else {
16425 style
16426 }
16427}
16428
16429fn text_contains_ascii_digit(text: &str) -> bool {
16430 text.chars().any(|c| c.is_ascii_digit())
16431}
16432
16433fn rect_center(rect: Rect) -> Point {
16434 Point::new(
16435 rect.x() + (rect.width() * 0.5),
16436 rect.y() + (rect.height() * 0.5),
16437 )
16438}
16439
16440fn inset_rect(rect: Rect, padding: Insets) -> Rect {
16441 Rect::new(
16442 rect.x() + padding.left,
16443 rect.y() + padding.top,
16444 (rect.width() - padding.left - padding.right).max(0.0),
16445 (rect.height() - padding.top - padding.bottom).max(0.0),
16446 )
16447}
16448
16449fn rounded_rect_path(rect: Rect, radius: f32) -> Path {
16450 Path::rounded_rect(rect, radius.min(rect.width().min(rect.height()) * 0.5))
16451}
16452
16453fn tab_indicator_rect<F>(
16454 mut tab_rect: F,
16455 from_index: usize,
16456 selected_index: usize,
16457 progress: f32,
16458 padding: Insets,
16459 thickness: f32,
16460) -> Option<Rect>
16461where
16462 F: FnMut(usize) -> Option<Rect>,
16463{
16464 let to = tab_indicator_from_tab_rect(tab_rect(selected_index)?, padding, thickness);
16465 let from = tab_rect(from_index)
16466 .map(|rect| tab_indicator_from_tab_rect(rect, padding, thickness))
16467 .unwrap_or(to);
16468 Some(lerp_rect(from, to, progress))
16469}
16470
16471fn tab_indicator_from_tab_rect(rect: Rect, padding: Insets, thickness: f32) -> Rect {
16472 Rect::new(
16473 rect.x() + padding.left,
16474 rect.max_y() - thickness,
16475 (rect.width() - padding.left - padding.right).max(0.0),
16476 thickness,
16477 )
16478}
16479
16480fn sliding_inset_rect<F>(
16481 mut item_rect: F,
16482 from_index: usize,
16483 selected_index: usize,
16484 progress: f32,
16485 insets: Insets,
16486) -> Option<Rect>
16487where
16488 F: FnMut(usize) -> Option<Rect>,
16489{
16490 let to = inset_rect(item_rect(selected_index)?, insets);
16491 let from = item_rect(from_index)
16492 .map(|rect| inset_rect(rect, insets))
16493 .unwrap_or(to);
16494 Some(lerp_rect(from, to, progress))
16495}
16496
16497fn tab_panel_transition_translation(
16498 from_index: usize,
16499 selected_index: usize,
16500 progress: f32,
16501 metrics: ControlMetrics,
16502) -> Vector {
16503 if from_index == selected_index {
16504 return Vector::ZERO;
16505 }
16506
16507 let remaining = 1.0 - progress.clamp(0.0, 1.0);
16508 if remaining <= AnimatedScalar::EPSILON {
16509 return Vector::ZERO;
16510 }
16511
16512 let direction = if selected_index > from_index {
16513 1.0
16514 } else {
16515 -1.0
16516 };
16517 Vector::new(direction * metrics.tab_panel_gap * remaining, 0.0)
16518}
16519
16520fn lerp_rect(from: Rect, to: Rect, progress: f32) -> Rect {
16521 let progress = progress.clamp(0.0, 1.0);
16522 Rect::new(
16523 f32::interpolate(from.x(), to.x(), progress),
16524 f32::interpolate(from.y(), to.y(), progress),
16525 f32::interpolate(from.width(), to.width(), progress),
16526 f32::interpolate(from.height(), to.height(), progress),
16527 )
16528}
16529
16530fn tab_state_visuals(
16531 theme: &DefaultTheme,
16532 selected: bool,
16533 hovered: bool,
16534 pressed: bool,
16535 hover_amount: f32,
16536 press_amount: f32,
16537) -> Option<(Color, Color)> {
16538 let palette = theme.palette;
16539 let interaction = theme.interaction;
16540 if selected {
16541 Some((
16542 mix_color(
16543 palette.surface_raised,
16544 palette.accent,
16545 interaction.tab_selected_blend,
16546 ),
16547 palette.border.with_alpha(0.72),
16548 ))
16549 } else if pressed || press_amount > 0.0 {
16550 Some((
16551 mix_color(
16552 if hover_amount > 0.0 {
16553 mix_color(
16554 palette.control,
16555 palette.control_hover,
16556 interaction.hover_blend * hover_amount,
16557 )
16558 } else {
16559 palette.control
16560 },
16561 palette.control_active,
16562 interaction.pressed_blend * press_amount,
16563 ),
16564 palette.border_hover,
16565 ))
16566 } else if hovered || hover_amount > 0.0 {
16567 Some((
16568 mix_color(
16569 palette.control,
16570 palette.control_hover,
16571 interaction.hover_blend * hover_amount,
16572 ),
16573 palette.border_hover,
16574 ))
16575 } else {
16576 None
16577 }
16578}
16579
16580fn draw_control_frame(
16581 ctx: &mut PaintCtx,
16582 bounds: Rect,
16583 radius: f32,
16584 metrics: ControlMetrics,
16585 background: Color,
16586 border: Color,
16587 focus_ring: Option<Color>,
16588) {
16589 draw_control_shape(
16590 ctx,
16591 bounds,
16592 radius,
16593 physical_pixels(ctx, metrics.border_width),
16594 background,
16595 border,
16596 );
16597
16598 if let Some(focus_ring) = focus_ring {
16599 draw_focus_ring_frame(ctx, bounds, radius, metrics, focus_ring);
16600 }
16601}
16602
16603fn draw_focus_ring_frame(
16604 ctx: &mut PaintCtx,
16605 bounds: Rect,
16606 radius: f32,
16607 metrics: ControlMetrics,
16608 focus_ring: Color,
16609) {
16610 let focus_ring_outset = physical_pixels(ctx, metrics.focus_ring_outset);
16611 ctx.stroke(
16612 rounded_rect_path(
16613 bounds.inflate(focus_ring_outset, focus_ring_outset),
16614 radius + focus_ring_outset,
16615 ),
16616 focus_ring,
16617 StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
16618 );
16619}
16620
16621fn draw_control_shape(
16622 ctx: &mut PaintCtx,
16623 bounds: Rect,
16624 radius: f32,
16625 border_width: f32,
16626 background: Color,
16627 border: Color,
16628) {
16629 let shape = rounded_rect_path(bounds, radius);
16630 ctx.fill(shape.clone(), background);
16631 ctx.stroke(shape, border, StrokeStyle::new(border_width));
16632}
16633
16634fn mix_color(left: Color, right: Color, amount: f32) -> Color {
16635 crate::animation::Interpolate::interpolate(left, right, amount)
16636}
16637
16638fn draw_popover_arrival_overlay(
16639 ctx: &mut PaintCtx,
16640 rect: Rect,
16641 metrics: ControlMetrics,
16642 background: Color,
16643 border: Color,
16644 arrival_effect: ResolvedEffectStyle,
16645) {
16646 let overlay_inset = physical_pixels(ctx, 1.0);
16647 let overlay_rect = rect.inflate(-overlay_inset, -overlay_inset);
16648 let overlay_radius = (metrics.corner_radius + 2.0 - overlay_inset).max(0.0);
16649 let overlay_fill = mix_color(background, arrival_effect.color, 0.35)
16650 .with_alpha((0.10 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.22));
16651 let stroke_color = apply_hdr_policy_cap(
16652 mix_color(border, arrival_effect.color, 0.55),
16653 arrival_effect
16654 .color
16655 .red
16656 .max(arrival_effect.color.green.max(arrival_effect.color.blue)),
16657 )
16658 .with_alpha((0.16 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.30));
16659
16660 ctx.fill(
16661 rounded_rect_path(overlay_rect, overlay_radius),
16662 overlay_fill,
16663 );
16664 ctx.stroke(
16665 rounded_rect_path(
16666 overlay_rect.inflate(-overlay_inset * 0.5, -overlay_inset * 0.5),
16667 (overlay_radius - (overlay_inset * 0.5)).max(0.0),
16668 ),
16669 stroke_color,
16670 StrokeStyle::new(physical_pixels(ctx, 1.0)),
16671 );
16672}
16673
16674fn tooltip_tail(trigger: Rect, bubble: Rect, placement: TooltipPlacement) -> Path {
16675 let center_x = rect_center(trigger)
16676 .x
16677 .clamp(bubble.x() + 12.0, bubble.max_x() - 12.0);
16678 let mut builder = PathBuilder::new();
16679 match placement {
16680 TooltipPlacement::Above => {
16681 builder
16682 .move_to(Point::new(center_x - 6.0, bubble.max_y() - 1.0))
16683 .line_to(Point::new(center_x + 6.0, bubble.max_y() - 1.0))
16684 .line_to(Point::new(center_x, bubble.max_y() + 8.0));
16685 }
16686 TooltipPlacement::Below => {
16687 builder
16688 .move_to(Point::new(center_x - 6.0, bubble.y() + 1.0))
16689 .line_to(Point::new(center_x + 6.0, bubble.y() + 1.0))
16690 .line_to(Point::new(center_x, bubble.y() - 8.0));
16691 }
16692 }
16693 builder.build()
16694}
16695
16696fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
16697 if value <= 0.0 {
16698 return 0.0;
16699 }
16700 ctx.dpi().physical_pixels_to_logical(value)
16701}
16702
16703#[cfg(test)]
16704mod tests;