Skip to main content

sui_widgets/
controls.rs

1mod interaction;
2use crate::{
3    ControlMetrics, DefaultTheme, HdrThemeMode, Interpolate, MotionScalar, ResolvedEffectStyle,
4    ResolvedHdrStyle, SemanticTone, ThemeColorScheme, WidgetColorRole, WidgetLuminanceRole,
5    WidgetMaterialRole,
6    editable_text::{
7        CaretBlink, EditableTextController, EditableTextLineMode, TextChangeCallbacks,
8        keyboard_text, single_line_text,
9    },
10    editor::{EditorCommand, EditorCommandResult, selection_range},
11    overlay::{OverlayPlacement, OverlayPlacementRequest, place_overlay},
12    paint_theme_shadow, resolve_luminance_role, resolve_widget_hdr_style,
13    selection::{SelectionChange, SelectionClipboardBehavior, SelectionOwnerId, SelectionScope},
14    text_align::{
15        HorizontalTextAlignmentMode, aligned_text_rect_for_layout,
16        aligned_text_rect_for_layout_with_mode, aligned_text_rect_for_text, paint_aligned_text,
17        paint_single_line_aligned_text,
18    },
19    text_command::TextCommand,
20};
21use interaction::PressInteraction;
22use std::{cell::RefCell, ops::Range, rc::Rc, sync::Arc};
23use sui_core::{
24    Color, EditableTextSemantics, Event, ImeEvent, InvalidationKind, InvalidationRequest,
25    InvalidationTarget, KeyState, Path, PathBuilder, Point, PointerButton, PointerEventKind, Rect,
26    SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsPopupKind, SemanticsRole,
27    SemanticsTextRange, SemanticsValue, Size, ToggleState, Vector, WakeEvent, WidgetId,
28};
29use sui_layout::{Axis, Constraints, IntrinsicSize, Padding as Insets};
30use sui_lucide::LucideIcon;
31use sui_reactive::Observable;
32use sui_runtime::{
33    ArrangeCtx, Command, EventCtx, EventPhase, LayerOptions, MeasureCtx, OVERLAY_DISMISS_REQUEST,
34    OverlayDismissPolicy, OverlayFocusBehavior, OverlayKind, OverlayOptions, PaintBoundaryMode,
35    PaintCtx, SemanticsCtx, SingleChild, StackSurfaceOptions, Widget, WidgetPodMutVisitor,
36    WidgetPodVisitor,
37};
38use sui_scene::{LayerCompositionMode, LayerProperties, StrokeStyle};
39use sui_text::{
40    FontFeature, PersistentTextLayout, TextCursor, TextMeasurement, TextSelection, TextStyle,
41};
42use unicode_segmentation::UnicodeSegmentation;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum IconGlyph {
46    Add,
47    Remove,
48    Check,
49    ChevronDown,
50    ChevronUp,
51    ChevronLeft,
52    ChevronRight,
53    Close,
54    Maximize,
55    Restore,
56    FitView,
57    ActualSize,
58    MoreHorizontal,
59    MoreVertical,
60    Search,
61    Undo,
62    Redo,
63    Brush,
64    Eraser,
65    PaintBucket,
66    Hand,
67    Lock,
68    Unlock,
69    Trash,
70    Download,
71    // Content/object glyphs (used by application chrome: chat, file browser, etc.).
72    Sparkles,
73    Chat,
74    History,
75    Folder,
76    File,
77    FileText,
78    Link,
79    Send,
80    ArrowUp,
81    Stop,
82    Attach,
83    Hourglass,
84    Alert,
85    Storage,
86    // Media/device glyphs for realtime call and device surfaces.
87    AudioLines,
88    Mic,
89    MicOff,
90    Camera,
91    CameraOff,
92    Video,
93    VideoOff,
94    Phone,
95    PhoneOff,
96    Monitor,
97    ScreenShare,
98}
99
100impl IconGlyph {
101    pub const fn lucide_icon(self) -> LucideIcon {
102        match self {
103            Self::Add => LucideIcon::Plus,
104            Self::Remove => LucideIcon::Minus,
105            Self::Check => LucideIcon::Check,
106            Self::ChevronDown => LucideIcon::ChevronDown,
107            Self::ChevronUp => LucideIcon::ChevronUp,
108            Self::ChevronLeft => LucideIcon::ChevronLeft,
109            Self::ChevronRight => LucideIcon::ChevronRight,
110            Self::Close => LucideIcon::X,
111            Self::Maximize => LucideIcon::Maximize,
112            Self::Restore => LucideIcon::Copy,
113            Self::FitView => LucideIcon::ScanSearch,
114            Self::ActualSize => LucideIcon::Scan,
115            Self::MoreHorizontal => LucideIcon::Ellipsis,
116            Self::MoreVertical => LucideIcon::EllipsisVertical,
117            Self::Search => LucideIcon::Search,
118            Self::Undo => LucideIcon::Undo2,
119            Self::Redo => LucideIcon::Redo2,
120            Self::Brush => LucideIcon::Brush,
121            Self::Eraser => LucideIcon::Eraser,
122            Self::PaintBucket => LucideIcon::PaintBucket,
123            Self::Hand => LucideIcon::Hand,
124            Self::Lock => LucideIcon::Lock,
125            Self::Unlock => LucideIcon::LockOpen,
126            Self::Trash => LucideIcon::Trash2,
127            Self::Download => LucideIcon::Download,
128            Self::Sparkles => LucideIcon::Sparkles,
129            Self::Chat => LucideIcon::MessageSquare,
130            Self::History => LucideIcon::History,
131            Self::Folder => LucideIcon::Folder,
132            Self::File => LucideIcon::File,
133            Self::FileText => LucideIcon::FileText,
134            Self::Link => LucideIcon::Link,
135            Self::Send => LucideIcon::Send,
136            Self::ArrowUp => LucideIcon::ArrowUp,
137            Self::Stop => LucideIcon::Square,
138            Self::Attach => LucideIcon::Paperclip,
139            Self::Hourglass => LucideIcon::Hourglass,
140            Self::Alert => LucideIcon::TriangleAlert,
141            Self::Storage => LucideIcon::HardDrive,
142            Self::AudioLines => LucideIcon::AudioLines,
143            Self::Mic => LucideIcon::Mic,
144            Self::MicOff => LucideIcon::MicOff,
145            Self::Camera => LucideIcon::Camera,
146            Self::CameraOff => LucideIcon::CameraOff,
147            Self::Video => LucideIcon::Video,
148            Self::VideoOff => LucideIcon::VideoOff,
149            Self::Phone => LucideIcon::Phone,
150            Self::PhoneOff => LucideIcon::PhoneOff,
151            Self::Monitor => LucideIcon::Monitor,
152            Self::ScreenShare => LucideIcon::ScreenShare,
153        }
154    }
155}
156
157pub const BUILTIN_ICON_GLYPHS: &[IconGlyph] = &[
158    IconGlyph::Add,
159    IconGlyph::Remove,
160    IconGlyph::Check,
161    IconGlyph::ChevronDown,
162    IconGlyph::ChevronUp,
163    IconGlyph::ChevronLeft,
164    IconGlyph::ChevronRight,
165    IconGlyph::Close,
166    IconGlyph::Maximize,
167    IconGlyph::Restore,
168    IconGlyph::FitView,
169    IconGlyph::ActualSize,
170    IconGlyph::MoreHorizontal,
171    IconGlyph::MoreVertical,
172    IconGlyph::Search,
173    IconGlyph::Undo,
174    IconGlyph::Redo,
175    IconGlyph::Brush,
176    IconGlyph::Eraser,
177    IconGlyph::PaintBucket,
178    IconGlyph::Hand,
179    IconGlyph::Lock,
180    IconGlyph::Unlock,
181    IconGlyph::Trash,
182    IconGlyph::Download,
183    IconGlyph::Sparkles,
184    IconGlyph::Chat,
185    IconGlyph::History,
186    IconGlyph::Folder,
187    IconGlyph::File,
188    IconGlyph::FileText,
189    IconGlyph::Link,
190    IconGlyph::Send,
191    IconGlyph::ArrowUp,
192    IconGlyph::Stop,
193    IconGlyph::Attach,
194    IconGlyph::Hourglass,
195    IconGlyph::Alert,
196    IconGlyph::Storage,
197    IconGlyph::AudioLines,
198    IconGlyph::Mic,
199    IconGlyph::MicOff,
200    IconGlyph::Camera,
201    IconGlyph::CameraOff,
202    IconGlyph::Video,
203    IconGlyph::VideoOff,
204    IconGlyph::Phone,
205    IconGlyph::PhoneOff,
206    IconGlyph::Monitor,
207    IconGlyph::ScreenShare,
208];
209
210pub fn register_builtin_icon_resources(
211    _application: &mut sui_runtime::Application,
212) -> sui_core::Result<()> {
213    // Built-in widgets paint Lucide geometry directly. Keep this compatibility hook so
214    // applications do not need to change their startup path.
215    Ok(())
216}
217
218pub struct Separator {
219    theme: Box<DefaultTheme>,
220    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
221    axis: Axis,
222    name: Option<String>,
223    inset: f32,
224    thickness: Option<f32>,
225    length: Option<f32>,
226}
227
228impl Separator {
229    pub fn new(axis: Axis) -> Self {
230        Self {
231            theme: Box::new(DefaultTheme::default()),
232            theme_reader: None,
233            axis,
234            name: None,
235            inset: 0.0,
236            thickness: None,
237            length: None,
238        }
239    }
240
241    pub fn horizontal() -> Self {
242        Self::new(Axis::Horizontal)
243    }
244
245    pub fn vertical() -> Self {
246        Self::new(Axis::Vertical)
247    }
248
249    pub fn theme(mut self, theme: DefaultTheme) -> Self {
250        self.theme = Box::new(theme);
251        self.theme_reader = None;
252        self
253    }
254
255    pub fn theme_when<F>(mut self, theme: F) -> Self
256    where
257        F: Fn() -> DefaultTheme + 'static,
258    {
259        self.theme_reader = Some(Box::new(theme));
260        self
261    }
262
263    pub fn name(mut self, name: impl Into<String>) -> Self {
264        self.name = Some(name.into());
265        self
266    }
267
268    pub fn inset(mut self, inset: f32) -> Self {
269        self.inset = inset.max(0.0);
270        self
271    }
272
273    pub fn thickness(mut self, thickness: f32) -> Self {
274        self.thickness = Some(thickness.max(0.0));
275        self
276    }
277
278    pub fn length(mut self, length: f32) -> Self {
279        self.length = Some(length.max(0.0));
280        self
281    }
282
283    fn resolved_thickness(&self) -> f32 {
284        self.thickness
285            .unwrap_or(self.resolved_theme().metrics.separator_thickness)
286            .max(1.0)
287    }
288
289    fn resolved_theme(&self) -> DefaultTheme {
290        self.theme_reader
291            .as_ref()
292            .map(|reader| reader())
293            .unwrap_or_else(|| *self.theme)
294    }
295}
296
297impl Widget for Separator {
298    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
299        let thickness = self.resolved_thickness();
300        let length = self.length.unwrap_or(64.0);
301        let size = match self.axis {
302            Axis::Horizontal => Size::new(length, thickness + (self.inset * 2.0)),
303            Axis::Vertical => Size::new(thickness + (self.inset * 2.0), length),
304        };
305
306        constraints.clamp(Size::new(
307            if self.axis == Axis::Horizontal && constraints.max.width.is_finite() {
308                constraints.max.width
309            } else {
310                size.width
311            },
312            if self.axis == Axis::Vertical && constraints.max.height.is_finite() {
313                constraints.max.height
314            } else {
315                size.height
316            },
317        ))
318    }
319
320    fn paint(&self, ctx: &mut PaintCtx) {
321        let theme = self.resolved_theme();
322        let thickness = physical_pixels(ctx, self.resolved_thickness());
323        let line = match self.axis {
324            Axis::Horizontal => Rect::new(
325                ctx.bounds().x() + self.inset,
326                ctx.bounds().y() + ((ctx.bounds().height() - thickness) * 0.5),
327                (ctx.bounds().width() - (self.inset * 2.0)).max(0.0),
328                thickness,
329            ),
330            Axis::Vertical => Rect::new(
331                ctx.bounds().x() + ((ctx.bounds().width() - thickness) * 0.5),
332                ctx.bounds().y() + self.inset,
333                thickness,
334                (ctx.bounds().height() - (self.inset * 2.0)).max(0.0),
335            ),
336        };
337        ctx.fill(
338            rounded_rect_path(line, thickness * 0.5),
339            theme.palette.border,
340        );
341    }
342
343    fn semantics(&self, ctx: &mut SemanticsCtx) {
344        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Separator, ctx.bounds());
345        node.name = self.name.clone();
346        ctx.push(node);
347    }
348}
349
350pub struct Icon {
351    theme: Box<DefaultTheme>,
352    glyph: IconGlyph,
353    size: Option<f32>,
354    color: Option<Color>,
355    color_reader: Option<Box<dyn Fn() -> Color>>,
356    label: Option<String>,
357}
358
359impl Icon {
360    pub fn new(glyph: IconGlyph) -> Self {
361        Self {
362            theme: Box::new(DefaultTheme::default()),
363            glyph,
364            size: None,
365            color: None,
366            color_reader: None,
367            label: None,
368        }
369    }
370
371    pub fn theme(mut self, theme: DefaultTheme) -> Self {
372        self.theme = Box::new(theme);
373        self
374    }
375
376    pub fn size(mut self, size: f32) -> Self {
377        self.size = Some(size.max(0.0));
378        self
379    }
380
381    pub fn color(mut self, color: Color) -> Self {
382        self.color = Some(color);
383        self.color_reader = None;
384        self
385    }
386
387    pub fn color_when<F>(mut self, color: F) -> Self
388    where
389        F: Fn() -> Color + 'static,
390    {
391        self.color_reader = Some(Box::new(color));
392        self
393    }
394
395    pub fn label(mut self, label: impl Into<String>) -> Self {
396        self.label = Some(label.into());
397        self
398    }
399
400    fn resolved_color(&self) -> Color {
401        self.color_reader
402            .as_ref()
403            .map(|reader| reader())
404            .or(self.color)
405            .unwrap_or(self.theme.palette.text)
406    }
407
408    fn resolved_size(&self) -> f32 {
409        self.size.unwrap_or(self.theme.metrics.icon_size)
410    }
411}
412
413impl Widget for Icon {
414    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
415        let side = self.resolved_size();
416        constraints.clamp(Size::new(side, side))
417    }
418
419    fn paint(&self, ctx: &mut PaintCtx) {
420        draw_icon_glyph(
421            ctx,
422            self.glyph,
423            center_square(ctx.bounds(), self.resolved_size()),
424            self.resolved_color(),
425        );
426    }
427
428    fn semantics(&self, ctx: &mut SemanticsCtx) {
429        if let Some(label) = &self.label {
430            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Image, ctx.bounds());
431            node.name = Some(label.clone());
432            ctx.push(node);
433        }
434    }
435}
436
437const CARET_BLINK_PERIOD_SECONDS: f64 = 1.0;
438const SELECT_CHEVRON_SLOT_WIDTH: f32 = 28.0;
439const SELECT_CHEVRON_ICON_SIZE: f32 = 20.0;
440#[cfg(test)]
441const SELECT_MENU_GAP: f32 = 6.0;
442
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444enum SelectMenuPlacement {
445    Below,
446    Above,
447}
448
449type AnimatedScalar = MotionScalar;
450
451fn request_child_invalidation(ctx: &mut EventCtx, widget_id: WidgetId, kind: InvalidationKind) {
452    ctx.request(InvalidationRequest::new(
453        InvalidationTarget::Widget(widget_id),
454        kind,
455    ));
456}
457
458fn set_animation_target(
459    animation: &mut AnimatedScalar,
460    target: f32,
461    duration: f64,
462    easing: crate::Easing,
463    ctx: &mut EventCtx,
464) {
465    animation.set_target_event(target, duration, easing, ctx);
466}
467
468fn set_hover_animation_target(
469    animation: &mut AnimatedScalar,
470    target: f32,
471    theme: &DefaultTheme,
472    ctx: &mut EventCtx,
473) {
474    set_animation_target(
475        animation,
476        target,
477        theme.motion.hover_duration(),
478        theme.motion.hover_easing(),
479        ctx,
480    );
481}
482
483fn set_press_animation_target(
484    animation: &mut AnimatedScalar,
485    target: f32,
486    theme: &DefaultTheme,
487    ctx: &mut EventCtx,
488) {
489    set_animation_target(
490        animation,
491        target,
492        theme.motion.press_duration(),
493        theme.motion.press_easing(),
494        ctx,
495    );
496}
497
498fn set_toggle_animation_target(
499    animation: &mut AnimatedScalar,
500    target: f32,
501    theme: &DefaultTheme,
502    ctx: &mut EventCtx,
503) {
504    set_animation_target(
505        animation,
506        target,
507        theme.motion.toggle_duration(),
508        theme.motion.toggle_easing(),
509        ctx,
510    );
511}
512
513fn set_focus_animation_target(
514    animation: &mut AnimatedScalar,
515    target: f32,
516    theme: &DefaultTheme,
517    ctx: &mut EventCtx,
518) {
519    set_animation_target(
520        animation,
521        target,
522        theme.motion.focus_duration(),
523        theme.motion.focus_easing(),
524        ctx,
525    );
526}
527
528fn mix_color(from: Color, to: Color, t: f32) -> Color {
529    Color::interpolate(from, to, t)
530}
531
532/// The visual treatment used by pressable controls.
533///
534/// Appearance and semantic tone are deliberately independent: a destructive
535/// action can be rendered as a filled, tonal, outlined, or low-emphasis ghost
536/// control without remapping the application's theme palette.
537#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
538pub enum ButtonAppearance {
539    /// A solid semantic-color fill for primary and high-emphasis actions.
540    Filled,
541    /// A soft semantic-color wash with semantic ink.
542    #[default]
543    Tonal,
544    /// A transparent surface with a visible semantic outline.
545    Outline,
546    /// A borderless, transparent surface that reveals a wash on interaction.
547    Ghost,
548}
549
550/// Whether an editor paints its own field chrome.
551#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
552pub enum FieldAppearance {
553    /// Paint the standard field background, border, hover, and focus ring.
554    #[default]
555    Framed,
556    /// Paint only editor content. Intended for use inside [`crate::FramedField`].
557    Bare,
558}
559
560/// The whole-row visual treatment used by checkbox, switch, and radio controls.
561///
562/// This affects only the row surrounding the label and indicator. The checkbox,
563/// switch track, or radio indicator always keeps its own stateful chrome.
564#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
565pub enum ChoiceAppearance {
566    /// A quiet row that is transparent at rest and reveals a soft wash while
567    /// hovered, pressed, or focused.
568    #[default]
569    Plain,
570    /// A filled, bordered row suitable for inspectors and dense settings panes.
571    Framed,
572}
573
574#[derive(Clone, Copy, Debug, PartialEq)]
575struct ChoiceFrameVisuals {
576    background: Color,
577    border: Color,
578}
579
580fn choice_frame_visuals(
581    theme: &DefaultTheme,
582    appearance: ChoiceAppearance,
583    framed_background: Color,
584    framed_border: Color,
585    hover_progress: f32,
586    press_progress: f32,
587    focus_progress: f32,
588) -> ChoiceFrameVisuals {
589    if appearance == ChoiceAppearance::Framed {
590        return ChoiceFrameVisuals {
591            background: framed_background,
592            border: framed_border,
593        };
594    }
595
596    let hover_wash = theme.surfaces.hover;
597    let press_wash = theme
598        .palette
599        .text
600        .with_alpha(if theme.surfaces.dark { 0.10 } else { 0.07 });
601    let focus_wash =
602        theme
603            .palette
604            .focus
605            .with_alpha(if theme.surfaces.dark { 0.085 } else { 0.055 });
606    let background = composite_translucent_wash(
607        animated_translucent_wash(press_wash, press_progress),
608        composite_translucent_wash(
609            animated_translucent_wash(focus_wash, focus_progress),
610            animated_translucent_wash(hover_wash, hover_progress),
611        ),
612    );
613
614    ChoiceFrameVisuals {
615        background,
616        border: Color::TRANSPARENT,
617    }
618}
619
620fn animated_translucent_wash(color: Color, progress: f32) -> Color {
621    color.with_alpha(color.alpha * progress.clamp(0.0, 1.0))
622}
623
624/// Source-over composition that preserves translucency. `Color::over` is for
625/// flattening a wash onto an opaque surface, while plain choice rows must stay
626/// transparent so their animated RGB channels never interpolate through black.
627fn composite_translucent_wash(foreground: Color, background: Color) -> Color {
628    let foreground_alpha = foreground.alpha.clamp(0.0, 1.0);
629    let background_alpha = background.alpha.clamp(0.0, 1.0);
630    let output_alpha = foreground_alpha + background_alpha * (1.0 - foreground_alpha);
631    if output_alpha <= f32::EPSILON {
632        return Color::TRANSPARENT;
633    }
634    let background_weight = background_alpha * (1.0 - foreground_alpha);
635    Color::new(
636        foreground.space,
637        (foreground.red * foreground_alpha + background.red * background_weight) / output_alpha,
638        (foreground.green * foreground_alpha + background.green * background_weight) / output_alpha,
639        (foreground.blue * foreground_alpha + background.blue * background_weight) / output_alpha,
640        output_alpha,
641    )
642}
643
644fn field_background(
645    theme: &DefaultTheme,
646    read_only: bool,
647    hover_progress: f32,
648    focus_progress: f32,
649) -> Color {
650    let palette = theme.palette;
651    let base = if read_only {
652        palette.surface
653    } else {
654        palette.field
655    };
656    let hover_target = if !read_only && theme.colors.scheme == ThemeColorScheme::Light {
657        palette.surface
658    } else {
659        base
660    };
661    let hovered = mix_color(
662        base,
663        hover_target,
664        hover_progress.clamp(0.0, 1.0) * theme.interaction.hover_blend,
665    );
666    mix_color(
667        hovered,
668        palette.surface_focus,
669        focus_progress.clamp(0.0, 1.0),
670    )
671}
672
673#[derive(Clone, Copy, Debug, PartialEq)]
674struct SemanticButtonVisuals {
675    background: Color,
676    border: Color,
677    content: Color,
678}
679
680fn semantic_button_visuals(
681    theme: &DefaultTheme,
682    appearance: ButtonAppearance,
683    tone: SemanticTone,
684    enabled: bool,
685    hover_progress: f32,
686    press_progress: f32,
687) -> SemanticButtonVisuals {
688    let palette = theme.palette;
689    let interaction = theme.interaction;
690    let hover = if enabled {
691        hover_progress.clamp(0.0, 1.0) * interaction.hover_blend
692    } else {
693        0.0
694    };
695    let press = if enabled {
696        press_progress.clamp(0.0, 1.0) * interaction.pressed_blend
697    } else {
698        0.0
699    };
700    let (solid, solid_text) = theme.semantic_tone_colors(tone);
701    let (soft, soft_text) = theme.semantic_tone_soft_colors(tone);
702    let ink = if tone == SemanticTone::Neutral {
703        palette.text
704    } else {
705        solid
706    };
707    let outline = if tone == SemanticTone::Neutral {
708        palette.border
709    } else {
710        solid.with_alpha(0.72)
711    };
712
713    let (base, hovered, pressed, border, content) = match appearance {
714        ButtonAppearance::Filled => {
715            let hovered = if tone == SemanticTone::Accent {
716                palette.accent_hover
717            } else {
718                mix_color(solid, solid_text, 0.10)
719            };
720            let pressed = if tone == SemanticTone::Accent {
721                palette.accent_pressed
722            } else {
723                mix_color(solid, palette.text, 0.16)
724            };
725            (solid, hovered, pressed, solid, solid_text)
726        }
727        ButtonAppearance::Tonal => (
728            soft,
729            mix_color(soft, solid, 0.12),
730            mix_color(soft, solid, 0.24),
731            if tone == SemanticTone::Neutral {
732                palette.border
733            } else {
734                solid.with_alpha(0.30)
735            },
736            soft_text,
737        ),
738        ButtonAppearance::Outline => (
739            Color::TRANSPARENT,
740            soft,
741            mix_color(soft, solid, 0.16),
742            outline,
743            ink,
744        ),
745        ButtonAppearance::Ghost => (
746            Color::TRANSPARENT,
747            soft,
748            mix_color(soft, solid, 0.16),
749            Color::TRANSPARENT,
750            ink,
751        ),
752    };
753    let background = mix_color(mix_color(base, hovered, hover), pressed, press);
754
755    if enabled {
756        SemanticButtonVisuals {
757            background,
758            border,
759            content,
760        }
761    } else {
762        let background = if matches!(
763            appearance,
764            ButtonAppearance::Outline | ButtonAppearance::Ghost
765        ) {
766            Color::TRANSPARENT
767        } else {
768            mix_color(background, palette.control, 0.72).with_alpha(interaction.disabled_opacity)
769        };
770        SemanticButtonVisuals {
771            background,
772            border: border.with_alpha(interaction.disabled_content_opacity),
773            content: palette
774                .text_muted
775                .with_alpha(interaction.disabled_content_opacity),
776        }
777    }
778}
779
780#[derive(Clone, Copy, Debug, PartialEq)]
781pub struct IconButtonPaint {
782    pub appearance: ButtonAppearance,
783    pub tone: SemanticTone,
784    pub selected: bool,
785    pub enabled: bool,
786    pub hover_progress: f32,
787    pub press_progress: f32,
788    pub focus_progress: f32,
789    pub icon_size: Option<f32>,
790}
791
792impl IconButtonPaint {
793    pub const fn new() -> Self {
794        Self {
795            appearance: ButtonAppearance::Tonal,
796            tone: SemanticTone::Neutral,
797            selected: false,
798            enabled: true,
799            hover_progress: 0.0,
800            press_progress: 0.0,
801            focus_progress: 0.0,
802            icon_size: None,
803        }
804    }
805
806    pub const fn appearance(mut self, appearance: ButtonAppearance) -> Self {
807        self.appearance = appearance;
808        self
809    }
810
811    pub const fn tone(mut self, tone: SemanticTone) -> Self {
812        self.tone = tone;
813        self
814    }
815
816    pub const fn selected(mut self, selected: bool) -> Self {
817        self.selected = selected;
818        self
819    }
820
821    pub const fn enabled(mut self, enabled: bool) -> Self {
822        self.enabled = enabled;
823        self
824    }
825
826    pub const fn hovered(mut self, hovered: bool) -> Self {
827        self.hover_progress = if hovered { 1.0 } else { 0.0 };
828        self
829    }
830
831    pub const fn pressed(mut self, pressed: bool) -> Self {
832        self.press_progress = if pressed { 1.0 } else { 0.0 };
833        self
834    }
835
836    pub const fn focused(mut self, focused: bool) -> Self {
837        self.focus_progress = if focused { 1.0 } else { 0.0 };
838        self
839    }
840
841    pub fn hover_progress(mut self, progress: f32) -> Self {
842        self.hover_progress = progress;
843        self
844    }
845
846    pub fn press_progress(mut self, progress: f32) -> Self {
847        self.press_progress = progress;
848        self
849    }
850
851    pub fn focus_progress(mut self, progress: f32) -> Self {
852        self.focus_progress = progress;
853        self
854    }
855
856    pub const fn icon_size(mut self, icon_size: f32) -> Self {
857        self.icon_size = Some(icon_size);
858        self
859    }
860}
861
862impl Default for IconButtonPaint {
863    fn default() -> Self {
864        Self::new()
865    }
866}
867
868pub fn paint_icon_button(
869    ctx: &mut PaintCtx,
870    theme: &DefaultTheme,
871    rect: Rect,
872    icon: IconGlyph,
873    style: IconButtonPaint,
874) {
875    if let Some((bounds, color)) = paint_icon_button_frame(ctx, theme, rect, style) {
876        draw_icon_glyph(ctx, icon, bounds, color);
877    }
878}
879
880fn paint_icon_button_frame(
881    ctx: &mut PaintCtx,
882    theme: &DefaultTheme,
883    rect: Rect,
884    style: IconButtonPaint,
885) -> Option<(Rect, Color)> {
886    if rect.width() <= 0.0 || rect.height() <= 0.0 {
887        return None;
888    }
889
890    let palette = theme.palette;
891    let metrics = theme.metrics;
892    let interaction = theme.interaction;
893    let selected = style.selected;
894    let enabled = style.enabled;
895    let hover_progress = if enabled {
896        style.hover_progress.clamp(0.0, 1.0) * interaction.hover_blend
897    } else {
898        0.0
899    };
900    let press_progress = if enabled {
901        style.press_progress.clamp(0.0, 1.0) * interaction.pressed_blend
902    } else {
903        0.0
904    };
905    let focus_progress = if enabled {
906        style.focus_progress.clamp(0.0, 1.0)
907    } else {
908        0.0
909    };
910    let legacy_default =
911        style.appearance == ButtonAppearance::Tonal && style.tone == SemanticTone::Neutral;
912    let (background, border, icon_color) = if legacy_default {
913        let base_background = if selected {
914            palette.selection
915        } else {
916            palette.control
917        };
918        let hover_background = if selected {
919            mix_color(base_background, palette.control_hover, 0.35)
920        } else {
921            palette.control_hover
922        };
923        let press_background = if selected {
924            mix_color(base_background, palette.control_active, 0.45)
925        } else {
926            palette.control_active
927        };
928        let background = mix_color(
929            mix_color(base_background, hover_background, hover_progress),
930            press_background,
931            press_progress,
932        );
933        let border_base = if !enabled {
934            palette.border.with_alpha(0.55)
935        } else if selected {
936            mix_color(
937                palette.selection_border,
938                palette.accent_border_hover,
939                hover_progress,
940            )
941        } else {
942            mix_color(palette.border, palette.border_hover, hover_progress)
943        };
944        let border = if enabled && !selected {
945            mix_color(border_base, palette.border_focus, focus_progress)
946        } else {
947            border_base
948        };
949        let background = if enabled {
950            background
951        } else {
952            mix_color(background, palette.control, 0.72).with_alpha(interaction.disabled_opacity)
953        };
954        let icon_color = if !enabled {
955            palette
956                .text
957                .with_alpha(interaction.disabled_content_opacity)
958        } else {
959            palette.text
960        };
961        (background, border, icon_color)
962    } else {
963        let mut visuals = semantic_button_visuals(
964            theme,
965            style.appearance,
966            style.tone,
967            enabled,
968            style.hover_progress,
969            style.press_progress,
970        );
971        if selected && enabled {
972            let selection = if style.tone == SemanticTone::Neutral {
973                palette.text
974            } else {
975                theme.semantic_tone_color(style.tone)
976            };
977            visuals.background = if style.tone == SemanticTone::Neutral {
978                palette.selection
979            } else {
980                mix_color(visuals.background, selection, interaction.selected_blend)
981            };
982            visuals.border = if style.tone == SemanticTone::Neutral {
983                palette.selection_border
984            } else {
985                mix_color(visuals.border, selection, 0.72)
986            };
987            visuals.content = selection;
988        }
989        visuals.border = if enabled && !selected {
990            mix_color(visuals.border, palette.border_focus, focus_progress)
991        } else {
992            visuals.border
993        };
994        (visuals.background, visuals.border, visuals.content)
995    };
996    let icon_size = style
997        .icon_size
998        .unwrap_or(metrics.icon_size)
999        .min(rect.width().min(rect.height()))
1000        .max(0.0);
1001
1002    draw_control_frame(
1003        ctx,
1004        rect,
1005        metrics.corner_radius,
1006        metrics,
1007        background,
1008        border,
1009        (focus_progress > 0.0).then_some(
1010            palette
1011                .focus_ring
1012                .with_alpha(palette.focus_ring.alpha * focus_progress),
1013        ),
1014    );
1015    Some((center_square(rect, icon_size), icon_color))
1016}
1017
1018#[derive(Clone, Copy)]
1019enum ButtonIcon {
1020    Glyph(IconGlyph),
1021    Image(sui_core::ImageHandle),
1022}
1023
1024pub struct IconButton {
1025    theme: Box<DefaultTheme>,
1026    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1027    icon: ButtonIcon,
1028    label: String,
1029    semantic_description: Option<String>,
1030    appearance: ButtonAppearance,
1031    tone: SemanticTone,
1032    size: Option<f32>,
1033    icon_size: Option<f32>,
1034    selected: bool,
1035    selected_reader: Option<Box<dyn Fn() -> bool>>,
1036    enabled: bool,
1037    enabled_reader: Option<Box<dyn Fn() -> bool>>,
1038    interaction: PressInteraction,
1039    focus_animation: AnimatedScalar,
1040    on_press: Option<Box<dyn FnMut()>>,
1041    on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
1042}
1043
1044impl IconButton {
1045    pub fn new(icon: IconGlyph, label: impl Into<String>) -> Self {
1046        Self::with_icon(ButtonIcon::Glyph(icon), label.into())
1047    }
1048
1049    /// Use a registered mask image with the same interaction, tint and focus behavior
1050    /// as the built-in glyph buttons.
1051    pub fn from_image(icon: sui_core::ImageHandle, label: impl Into<String>) -> Self {
1052        Self::with_icon(ButtonIcon::Image(icon), label.into())
1053    }
1054
1055    fn with_icon(icon: ButtonIcon, label: String) -> Self {
1056        Self {
1057            theme: Box::new(DefaultTheme::default()),
1058            theme_reader: None,
1059            icon,
1060            label,
1061            semantic_description: None,
1062            appearance: ButtonAppearance::Tonal,
1063            tone: SemanticTone::Neutral,
1064            size: None,
1065            icon_size: None,
1066            selected: false,
1067            selected_reader: None,
1068            enabled: true,
1069            enabled_reader: None,
1070            interaction: PressInteraction::default(),
1071            focus_animation: AnimatedScalar::new(0.0),
1072            on_press: None,
1073            on_press_with_ctx: None,
1074        }
1075    }
1076
1077    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1078        self.theme = Box::new(theme);
1079        self.theme_reader = None;
1080        self
1081    }
1082
1083    pub fn description(mut self, description: impl Into<String>) -> Self {
1084        self.semantic_description = Some(description.into());
1085        self
1086    }
1087
1088    pub fn appearance(mut self, appearance: ButtonAppearance) -> Self {
1089        self.appearance = appearance;
1090        self
1091    }
1092
1093    pub fn tone(mut self, tone: SemanticTone) -> Self {
1094        self.tone = tone;
1095        self
1096    }
1097
1098    pub fn theme_when<F>(mut self, theme: F) -> Self
1099    where
1100        F: Fn() -> DefaultTheme + 'static,
1101    {
1102        self.theme_reader = Some(Box::new(theme));
1103        self
1104    }
1105
1106    pub fn size(mut self, size: f32) -> Self {
1107        self.size = Some(size.max(0.0));
1108        self
1109    }
1110
1111    pub fn icon_size(mut self, icon_size: f32) -> Self {
1112        self.icon_size = Some(icon_size.max(0.0));
1113        self
1114    }
1115
1116    pub fn selected(mut self, selected: bool) -> Self {
1117        self.selected = selected;
1118        self.selected_reader = None;
1119        self
1120    }
1121
1122    pub fn selected_when<F>(mut self, selected: F) -> Self
1123    where
1124        F: Fn() -> bool + 'static,
1125    {
1126        self.selected_reader = Some(Box::new(selected));
1127        self
1128    }
1129
1130    pub fn enabled(mut self, enabled: bool) -> Self {
1131        self.enabled = enabled;
1132        self.enabled_reader = None;
1133        self
1134    }
1135
1136    pub fn enabled_when<F>(mut self, enabled: F) -> Self
1137    where
1138        F: Fn() -> bool + 'static,
1139    {
1140        self.enabled_reader = Some(Box::new(enabled));
1141        self
1142    }
1143
1144    pub fn on_press<F>(mut self, on_press: F) -> Self
1145    where
1146        F: FnMut() + 'static,
1147    {
1148        self.on_press = Some(Box::new(on_press));
1149        self
1150    }
1151
1152    pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
1153    where
1154        F: FnMut(&mut EventCtx) + 'static,
1155    {
1156        self.on_press_with_ctx = Some(Box::new(on_press));
1157        self
1158    }
1159
1160    fn resolved_theme(&self) -> DefaultTheme {
1161        self.theme_reader
1162            .as_ref()
1163            .map(|theme| theme())
1164            .unwrap_or(*self.theme)
1165    }
1166
1167    fn resolved_size(&self) -> f32 {
1168        let theme = self.resolved_theme();
1169        self.size
1170            .unwrap_or(theme.metrics.icon_button_size)
1171            .max(theme.metrics.min_height)
1172    }
1173
1174    fn resolved_icon_size(&self) -> f32 {
1175        let theme = self.resolved_theme();
1176        self.icon_size
1177            .unwrap_or(theme.metrics.icon_size)
1178            .min(self.resolved_size())
1179            .max(0.0)
1180    }
1181
1182    fn is_selected(&self) -> bool {
1183        self.selected_reader
1184            .as_ref()
1185            .map(|selected| selected())
1186            .unwrap_or(self.selected)
1187    }
1188
1189    fn is_enabled(&self) -> bool {
1190        self.enabled_reader
1191            .as_ref()
1192            .map(|enabled| enabled())
1193            .unwrap_or(self.enabled)
1194    }
1195
1196    fn activate(&mut self, ctx: &mut EventCtx) {
1197        if !self.is_enabled() {
1198            return;
1199        }
1200        if let Some(on_press) = &mut self.on_press {
1201            on_press();
1202        }
1203        if let Some(on_press) = &mut self.on_press_with_ctx {
1204            on_press(ctx);
1205        }
1206    }
1207}
1208
1209impl Widget for IconButton {
1210    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1211        let enabled = self.is_enabled();
1212        let theme = &self.theme;
1213        let reader = &self.theme_reader;
1214        let activate = self.interaction.event(
1215            ctx,
1216            event,
1217            enabled,
1218            || reader.as_ref().map(|read| read()).unwrap_or(**theme),
1219            &mut self.focus_animation,
1220        );
1221        if activate {
1222            self.activate(ctx);
1223            ctx.request_paint();
1224            ctx.request_semantics();
1225            ctx.set_handled();
1226        }
1227    }
1228
1229    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1230        let side = self.resolved_size();
1231        constraints.clamp(Size::new(side, side))
1232    }
1233
1234    fn paint(&self, ctx: &mut PaintCtx) {
1235        let theme = self.resolved_theme();
1236        let style = IconButtonPaint::new()
1237            .appearance(self.appearance)
1238            .tone(self.tone)
1239            .selected(self.is_selected())
1240            .enabled(self.is_enabled())
1241            .hover_progress(self.interaction.hover_animation.value)
1242            .press_progress(self.interaction.press_animation.value)
1243            .focus_progress(self.focus_animation.value)
1244            .icon_size(self.resolved_icon_size());
1245        match self.icon {
1246            ButtonIcon::Glyph(icon) => paint_icon_button(ctx, &theme, ctx.bounds(), icon, style),
1247            ButtonIcon::Image(icon) => {
1248                if let Some((bounds, color)) =
1249                    paint_icon_button_frame(ctx, &theme, ctx.bounds(), style)
1250                {
1251                    ctx.draw_image_source(
1252                        bounds,
1253                        sui_scene::ImageSource::new(icon).with_tint(color),
1254                    );
1255                }
1256            }
1257        }
1258    }
1259
1260    fn semantics(&self, ctx: &mut SemanticsCtx) {
1261        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
1262        node.name = Some(self.label.clone());
1263        node.description = self.semantic_description.clone();
1264        node.state.focused = ctx.is_focused();
1265        node.state.hovered = self.interaction.hovered && self.is_enabled();
1266        node.state.selected = self.is_selected();
1267        node.state.disabled = !self.is_enabled();
1268        node.actions = if self.is_enabled() {
1269            vec![SemanticsAction::Focus, SemanticsAction::Activate]
1270        } else {
1271            Vec::new()
1272        };
1273        ctx.push(node);
1274    }
1275
1276    fn accepts_focus(&self) -> bool {
1277        self.is_enabled()
1278    }
1279
1280    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1281        let theme = self.resolved_theme();
1282        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1283        ctx.request_paint();
1284        ctx.request_semantics();
1285    }
1286}
1287
1288mod text_display;
1289pub use text_display::{Label, Link};
1290
1291pub struct Button {
1292    theme: Box<DefaultTheme>,
1293    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1294    label: String,
1295    semantic_name: Option<String>,
1296    semantic_description: Option<String>,
1297    appearance: ButtonAppearance,
1298    tone: SemanticTone,
1299    text_style: Option<TextStyle>,
1300    icon: Option<IconGlyph>,
1301    icon_size: Option<f32>,
1302    icon_gap: Option<f32>,
1303    padding: Option<Insets>,
1304    min_width: Option<f32>,
1305    min_height: Option<f32>,
1306    interaction: PressInteraction,
1307    focus_animation: AnimatedScalar,
1308    label_measurement: Option<TextMeasurement>,
1309    label_layout: Option<PersistentTextLayout>,
1310    enabled: bool,
1311    enabled_reader: Option<Box<dyn Fn() -> bool>>,
1312    on_press: Option<Box<dyn FnMut()>>,
1313    on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
1314}
1315
1316#[derive(Debug, Clone, Copy, PartialEq)]
1317struct ButtonVisuals {
1318    background: Color,
1319    border: Color,
1320    focus_ring: Option<Color>,
1321    label_color: Color,
1322    label_peak_lift: f32,
1323    chrome_style: Option<ResolvedHdrStyle>,
1324}
1325
1326impl Button {
1327    /// Creates a neutral, tonal button for an ordinary action.
1328    pub fn new(label: impl Into<String>) -> Self {
1329        Self {
1330            theme: Box::new(DefaultTheme::default()),
1331            theme_reader: None,
1332            label: label.into(),
1333            semantic_name: None,
1334            semantic_description: None,
1335            appearance: ButtonAppearance::Tonal,
1336            tone: SemanticTone::Neutral,
1337            text_style: None,
1338            icon: None,
1339            icon_size: None,
1340            icon_gap: None,
1341            padding: None,
1342            min_width: None,
1343            min_height: None,
1344            interaction: PressInteraction::default(),
1345            focus_animation: AnimatedScalar::new(0.0),
1346            label_measurement: None,
1347            label_layout: None,
1348            enabled: true,
1349            enabled_reader: None,
1350            on_press: None,
1351            on_press_with_ctx: None,
1352        }
1353    }
1354
1355    /// Creates a filled accent button for the primary action on a surface.
1356    pub fn primary(label: impl Into<String>) -> Self {
1357        Self::new(label).primary_action()
1358    }
1359
1360    /// Creates a filled danger button for a destructive or irreversible action.
1361    pub fn danger(label: impl Into<String>) -> Self {
1362        Self::new(label).danger_action()
1363    }
1364
1365    pub fn label(&self) -> &str {
1366        &self.label
1367    }
1368
1369    pub fn set_label(&mut self, label: impl Into<String>) {
1370        self.label = label.into();
1371    }
1372
1373    pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
1374        self.semantic_name = Some(name.into());
1375        self
1376    }
1377
1378    pub fn description(mut self, description: impl Into<String>) -> Self {
1379        self.semantic_description = Some(description.into());
1380        self
1381    }
1382
1383    /// Selects the button's visual emphasis without changing its semantic
1384    /// meaning. The default is [`ButtonAppearance::Tonal`].
1385    pub fn appearance(mut self, appearance: ButtonAppearance) -> Self {
1386        self.appearance = appearance;
1387        self
1388    }
1389
1390    /// Selects the semantic color family used by this button. The default is
1391    /// [`SemanticTone::Neutral`].
1392    pub fn tone(mut self, tone: SemanticTone) -> Self {
1393        self.tone = tone;
1394        self
1395    }
1396
1397    /// Promotes this button to a filled accent primary action.
1398    pub fn primary_action(mut self) -> Self {
1399        self.appearance = ButtonAppearance::Filled;
1400        self.tone = SemanticTone::Accent;
1401        self
1402    }
1403
1404    /// Promotes this button to a filled danger action.
1405    pub fn danger_action(mut self) -> Self {
1406        self.appearance = ButtonAppearance::Filled;
1407        self.tone = SemanticTone::Danger;
1408        self
1409    }
1410
1411    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1412        self.theme = Box::new(theme);
1413        self.theme_reader = None;
1414        self
1415    }
1416
1417    pub fn theme_when<F>(mut self, theme: F) -> Self
1418    where
1419        F: Fn() -> DefaultTheme + 'static,
1420    {
1421        self.theme_reader = Some(Box::new(theme));
1422        self
1423    }
1424
1425    pub fn text_style(mut self, text_style: TextStyle) -> Self {
1426        self.text_style = Some(text_style);
1427        self
1428    }
1429
1430    pub fn icon(mut self, icon: IconGlyph) -> Self {
1431        self.icon = Some(icon);
1432        self
1433    }
1434
1435    pub fn without_icon(mut self) -> Self {
1436        self.icon = None;
1437        self
1438    }
1439
1440    pub fn icon_size(mut self, icon_size: f32) -> Self {
1441        self.icon_size = Some(icon_size.max(0.0));
1442        self
1443    }
1444
1445    pub fn icon_gap(mut self, icon_gap: f32) -> Self {
1446        self.icon_gap = Some(icon_gap.max(0.0));
1447        self
1448    }
1449
1450    pub fn min_width(mut self, width: f32) -> Self {
1451        self.min_width = Some(width.max(0.0));
1452        self
1453    }
1454
1455    pub fn min_height(mut self, height: f32) -> Self {
1456        self.min_height = Some(height.max(0.0));
1457        self
1458    }
1459
1460    pub fn padding(mut self, padding: Insets) -> Self {
1461        self.padding = Some(padding);
1462        self
1463    }
1464
1465    pub fn enabled(mut self, enabled: bool) -> Self {
1466        self.enabled = enabled;
1467        self.enabled_reader = None;
1468        self
1469    }
1470
1471    pub fn enabled_when<F>(mut self, enabled: F) -> Self
1472    where
1473        F: Fn() -> bool + 'static,
1474    {
1475        self.enabled_reader = Some(Box::new(enabled));
1476        self
1477    }
1478
1479    pub fn on_press<F>(mut self, on_press: F) -> Self
1480    where
1481        F: FnMut() + 'static,
1482    {
1483        self.on_press = Some(Box::new(on_press));
1484        self
1485    }
1486
1487    pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
1488    where
1489        F: FnMut(&mut EventCtx) + 'static,
1490    {
1491        self.on_press_with_ctx = Some(Box::new(on_press));
1492        self
1493    }
1494
1495    fn activate(&mut self, ctx: &mut EventCtx) {
1496        if !self.is_enabled() {
1497            return;
1498        }
1499        if let Some(on_press) = &mut self.on_press {
1500            on_press();
1501        }
1502        if let Some(on_press) = &mut self.on_press_with_ctx {
1503            on_press(ctx);
1504        }
1505    }
1506
1507    fn is_enabled(&self) -> bool {
1508        self.enabled_reader
1509            .as_ref()
1510            .map(|enabled| enabled())
1511            .unwrap_or(self.enabled)
1512    }
1513
1514    fn resolved_theme(&self) -> DefaultTheme {
1515        self.theme_reader
1516            .as_ref()
1517            .map(|theme| theme())
1518            .unwrap_or(*self.theme)
1519    }
1520
1521    fn resolved_text_style(&self) -> TextStyle {
1522        self.text_style
1523            .clone()
1524            .unwrap_or_else(|| self.resolved_theme().button_text_style())
1525    }
1526
1527    fn resolved_padding(&self) -> Insets {
1528        self.padding
1529            .unwrap_or(self.resolved_theme().metrics.button_padding)
1530    }
1531
1532    fn resolved_icon_size(&self) -> f32 {
1533        self.icon_size
1534            .unwrap_or(self.resolved_theme().metrics.icon_size)
1535            .max(0.0)
1536    }
1537
1538    fn resolved_icon_gap(&self) -> f32 {
1539        self.icon_gap
1540            .unwrap_or(self.resolved_theme().metrics.icon_label_gap)
1541            .max(0.0)
1542    }
1543
1544    fn icon_extent(&self) -> Option<(f32, f32)> {
1545        self.icon.map(|_| {
1546            let icon_size = self.resolved_icon_size();
1547            let gap = if self.label.is_empty() {
1548                0.0
1549            } else {
1550                self.resolved_icon_gap()
1551            };
1552            (icon_size, gap)
1553        })
1554    }
1555
1556    fn resolved_min_size(&self) -> Size {
1557        let theme = self.resolved_theme();
1558        Size::new(
1559            self.min_width.unwrap_or(theme.metrics.button_min_width),
1560            self.min_height.unwrap_or(theme.metrics.min_height),
1561        )
1562    }
1563
1564    #[cfg(test)]
1565    fn resolved_visuals(&self, focused: bool) -> ButtonVisuals {
1566        self.resolved_visuals_with_focus_progress(focused as u8 as f32)
1567    }
1568
1569    fn resolved_visuals_with_focus_progress(&self, focus_progress: f32) -> ButtonVisuals {
1570        let theme = self.resolved_theme();
1571        let palette = theme.palette;
1572        let interaction = theme.interaction;
1573        let enabled = self.is_enabled();
1574        let focus_progress = if enabled {
1575            focus_progress.clamp(0.0, 1.0)
1576        } else {
1577            0.0
1578        };
1579        let hover_progress = if enabled {
1580            self.interaction.hover_animation.value * interaction.hover_blend
1581        } else {
1582            0.0
1583        };
1584        let press_progress = if enabled {
1585            self.interaction.press_animation.value * interaction.pressed_blend
1586        } else {
1587            0.0
1588        };
1589        let legacy_default =
1590            self.appearance == ButtonAppearance::Filled && self.tone == SemanticTone::Accent;
1591        if !legacy_default {
1592            let semantic = semantic_button_visuals(
1593                &theme,
1594                self.appearance,
1595                self.tone,
1596                enabled,
1597                self.interaction.hover_animation.value,
1598                self.interaction.press_animation.value,
1599            );
1600            let label_peak_lift = resolve_luminance_role(&theme.hdr, WidgetLuminanceRole::Standard);
1601            let label_color = if enabled {
1602                apply_hdr_policy_cap(
1603                    self.text_style
1604                        .as_ref()
1605                        .map(|style| style.color)
1606                        .unwrap_or(semantic.content),
1607                    label_peak_lift,
1608                )
1609            } else {
1610                apply_hdr_policy_cap(semantic.content, label_peak_lift)
1611            };
1612            return ButtonVisuals {
1613                background: semantic.background,
1614                border: if enabled {
1615                    mix_color(semantic.border, palette.border_focus, focus_progress)
1616                } else {
1617                    semantic.border
1618                },
1619                focus_ring: (focus_progress > 0.0).then_some(
1620                    palette
1621                        .focus_ring
1622                        .with_alpha(palette.focus_ring.alpha * focus_progress),
1623                ),
1624                label_color,
1625                label_peak_lift,
1626                chrome_style: None,
1627            };
1628        }
1629        let background = if !enabled {
1630            mix_color(palette.control, palette.accent, 0.08)
1631                .with_alpha(interaction.disabled_opacity)
1632        } else {
1633            mix_color(
1634                mix_color(palette.accent, palette.accent_hover, hover_progress),
1635                palette.accent_pressed,
1636                press_progress,
1637            )
1638        };
1639        let border_base = if !enabled {
1640            palette
1641                .accent_border
1642                .with_alpha(interaction.disabled_content_opacity)
1643        } else {
1644            mix_color(
1645                palette.accent_border,
1646                palette.accent_border_hover,
1647                hover_progress,
1648            )
1649        };
1650        let border = if enabled {
1651            mix_color(border_base, palette.accent_border_focus, focus_progress)
1652        } else {
1653            border_base
1654        };
1655        let label_peak_lift = resolve_luminance_role(&theme.hdr, WidgetLuminanceRole::Standard);
1656        let label_color = if enabled {
1657            apply_hdr_policy_cap(self.resolved_text_style().color, label_peak_lift)
1658        } else {
1659            apply_hdr_policy_cap(palette.text_muted, label_peak_lift)
1660        };
1661
1662        if matches!(theme.hdr.mode, HdrThemeMode::Disabled) {
1663            return ButtonVisuals {
1664                background,
1665                border,
1666                focus_ring: (focus_progress > 0.0).then_some(
1667                    palette
1668                        .focus_ring
1669                        .with_alpha(palette.focus_ring.alpha * focus_progress),
1670                ),
1671                label_color,
1672                label_peak_lift,
1673                chrome_style: None,
1674            };
1675        }
1676
1677        let chrome_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
1678            &theme.hdr,
1679            WidgetColorRole::Accent,
1680            WidgetLuminanceRole::SemanticAccent,
1681            WidgetMaterialRole::Flat,
1682            None,
1683        ));
1684        let focus_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
1685            &theme.hdr,
1686            WidgetColorRole::Accent,
1687            WidgetLuminanceRole::Focused,
1688            WidgetMaterialRole::Flat,
1689            None,
1690        ));
1691        let hdr_background = if !enabled {
1692            background
1693        } else {
1694            mix_color(
1695                mix_color(chrome_style.color, palette.accent_hover, hover_progress),
1696                palette.accent_pressed,
1697                press_progress,
1698            )
1699        };
1700        let hdr_border_base = if !enabled {
1701            border
1702        } else {
1703            mix_color(
1704                palette.accent_border,
1705                palette.accent_border_hover,
1706                hover_progress,
1707            )
1708        };
1709        let hdr_border = if enabled {
1710            mix_color(hdr_border_base, focus_style.color, focus_progress)
1711        } else {
1712            hdr_border_base
1713        };
1714
1715        ButtonVisuals {
1716            background: hdr_background,
1717            border: hdr_border,
1718            focus_ring: (focus_progress > 0.0).then_some(
1719                focus_style
1720                    .color
1721                    .with_alpha(palette.focus_ring.alpha * focus_progress),
1722            ),
1723            label_color,
1724            label_peak_lift,
1725            chrome_style: Some(chrome_style),
1726        }
1727    }
1728
1729    fn button_content_rects(&self, bounds: Rect, padding: Insets) -> (Option<Rect>, Rect, f32) {
1730        let content = inset_rect(bounds, padding);
1731        let Some((icon_size, icon_gap)) = self.icon_extent() else {
1732            return (None, content, 0.5);
1733        };
1734
1735        let measurement = self.label_measurement;
1736        let natural_label_width = measurement.map(|value| value.width).unwrap_or(0.0);
1737        let icon_size = icon_size
1738            .min(content.width())
1739            .min(content.height())
1740            .max(0.0);
1741        let gap = if icon_size > 0.0 && natural_label_width > 0.0 {
1742            icon_gap.min(content.width())
1743        } else {
1744            0.0
1745        };
1746        let label_width = natural_label_width.min((content.width() - icon_size - gap).max(0.0));
1747        let group_width = icon_size + gap + label_width;
1748        let start_x = content.x() + ((content.width() - group_width).max(0.0) * 0.5);
1749        let icon_rect = Rect::new(
1750            start_x,
1751            content.y() + ((content.height() - icon_size) * 0.5),
1752            icon_size,
1753            icon_size,
1754        );
1755        let label_base = Rect::new(
1756            start_x + icon_size + gap,
1757            content.y(),
1758            label_width,
1759            content.height(),
1760        );
1761        (Some(icon_rect), label_base, 0.0)
1762    }
1763}
1764
1765impl Widget for Button {
1766    fn supports_output_reuse(&self) -> bool {
1767        self.theme_reader.is_none() && self.enabled_reader.is_none()
1768    }
1769    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1770        let enabled = self.is_enabled();
1771        let theme = &self.theme;
1772        let reader = &self.theme_reader;
1773        let activate = self.interaction.event(
1774            ctx,
1775            event,
1776            enabled,
1777            || reader.as_ref().map(|read| read()).unwrap_or(**theme),
1778            &mut self.focus_animation,
1779        );
1780        if activate {
1781            self.activate(ctx);
1782            ctx.request_paint();
1783            ctx.request_semantics();
1784            ctx.set_handled();
1785        }
1786    }
1787
1788    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1789        let text_style = self.resolved_text_style();
1790        let padding = self.resolved_padding();
1791        let min_size = self.resolved_min_size();
1792        let label_layout = ctx
1793            .layout()
1794            .layout_document_persistent(
1795                self.label_layout.as_ref().map(|layout| layout.handle()),
1796                sui_text::TextLayoutRequest::new(sui_text::TextDocument::from_plain_text(
1797                    self.label.clone(),
1798                    text_style.clone(),
1799                )),
1800            )
1801            .ok();
1802        let measurement = label_layout
1803            .as_ref()
1804            .map(|layout| layout.measurement())
1805            .unwrap_or(TextMeasurement {
1806                width: 0.0,
1807                height: text_style.line_height,
1808                bounds: Rect::new(0.0, 0.0, 0.0, text_style.line_height),
1809                ascent: text_style.font_size,
1810                descent: 0.0,
1811                cap_height: Some(text_style.font_size),
1812            });
1813        self.label_measurement = Some(measurement);
1814        self.label_layout = label_layout;
1815
1816        let (icon_size, icon_gap) = self.icon_extent().unwrap_or((0.0, 0.0));
1817        let content_width = icon_size + icon_gap + measurement.width;
1818        let content_height = measurement
1819            .height
1820            .max(text_style.line_height)
1821            .max(icon_size);
1822        let width = (content_width + padding.left + padding.right).max(min_size.width);
1823        let height = (content_height + padding.top + padding.bottom).max(min_size.height);
1824
1825        constraints.clamp(Size::new(width, height))
1826    }
1827
1828    fn paint(&self, ctx: &mut PaintCtx) {
1829        let theme = self.resolved_theme();
1830        let metrics = theme.metrics;
1831        let text_style = self.resolved_text_style();
1832        let padding = self.resolved_padding();
1833        let visuals = self.resolved_visuals_with_focus_progress(self.focus_animation.value);
1834        draw_control_frame(
1835            ctx,
1836            ctx.bounds(),
1837            metrics.corner_radius,
1838            metrics,
1839            visuals.background,
1840            visuals.border,
1841            visuals.focus_ring,
1842        );
1843        let (icon_rect, label_slot, label_alignment) =
1844            self.button_content_rects(ctx.bounds(), padding);
1845        if let (Some(icon), Some(icon_rect)) = (self.icon, icon_rect) {
1846            draw_icon_glyph(ctx, icon, icon_rect, visuals.label_color);
1847        }
1848        ctx.push_clip_rect(label_slot);
1849        if self.is_enabled()
1850            && let Some(layout) = &self.label_layout
1851        {
1852            let layout_rect = aligned_text_rect_for_layout_with_mode(
1853                ctx,
1854                label_slot,
1855                layout.layout(),
1856                text_style.line_height,
1857                label_alignment,
1858                HorizontalTextAlignmentMode::Optical,
1859            );
1860            let layout_bounds = layout.measurement().bounds;
1861            ctx.draw_persistent_text_layout_with_color(
1862                Point::new(layout_rect.x() - layout_bounds.x(), layout_rect.y()),
1863                layout,
1864                visuals.label_color,
1865            );
1866            ctx.pop_clip();
1867            return;
1868        }
1869        let paint_style = TextStyle {
1870            color: visuals.label_color,
1871            ..text_style
1872        };
1873        paint_aligned_text(
1874            ctx,
1875            label_slot,
1876            &self.label,
1877            &paint_style,
1878            paint_style.line_height,
1879            label_alignment,
1880        );
1881        ctx.pop_clip();
1882    }
1883
1884    fn semantics(&self, ctx: &mut SemanticsCtx) {
1885        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
1886        node.name = Some(
1887            self.semantic_name
1888                .clone()
1889                .unwrap_or_else(|| self.label.clone()),
1890        );
1891        node.description = self.semantic_description.clone();
1892        node.state.focused = ctx.is_focused();
1893        node.state.hovered = self.interaction.hovered && self.is_enabled();
1894        node.state.disabled = !self.is_enabled();
1895        node.actions = if self.is_enabled() {
1896            vec![SemanticsAction::Focus, SemanticsAction::Activate]
1897        } else {
1898            Vec::new()
1899        };
1900        ctx.push(node);
1901    }
1902
1903    fn accepts_focus(&self) -> bool {
1904        self.is_enabled()
1905    }
1906
1907    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1908        let theme = self.resolved_theme();
1909        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1910        ctx.request_paint();
1911        ctx.request_semantics();
1912    }
1913}
1914
1915pub struct Checkbox {
1916    theme: Box<DefaultTheme>,
1917    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1918    label: String,
1919    checked: bool,
1920    appearance: ChoiceAppearance,
1921    text_style: Option<TextStyle>,
1922    padding: Option<Insets>,
1923    indicator_size: Option<f32>,
1924    gap: Option<f32>,
1925    hovered: bool,
1926    pressed: bool,
1927    hover_animation: AnimatedScalar,
1928    press_animation: AnimatedScalar,
1929    toggle_animation: AnimatedScalar,
1930    focus_animation: AnimatedScalar,
1931    label_measurement: Option<TextMeasurement>,
1932    on_toggle: Option<Box<dyn FnMut(bool)>>,
1933}
1934
1935#[derive(Clone, Copy, Debug, Default, PartialEq)]
1936pub struct CheckboxIndicatorState {
1937    pub checked: bool,
1938    pub hovered: bool,
1939    pub pressed: bool,
1940    pub focused: bool,
1941}
1942
1943impl CheckboxIndicatorState {
1944    pub fn new(checked: bool) -> Self {
1945        Self {
1946            checked,
1947            hovered: false,
1948            pressed: false,
1949            focused: false,
1950        }
1951    }
1952
1953    pub fn hovered(mut self, hovered: bool) -> Self {
1954        self.hovered = hovered;
1955        self
1956    }
1957
1958    pub fn pressed(mut self, pressed: bool) -> Self {
1959        self.pressed = pressed;
1960        self
1961    }
1962
1963    pub fn focused(mut self, focused: bool) -> Self {
1964        self.focused = focused;
1965        self
1966    }
1967}
1968
1969#[derive(Clone, Copy, Debug, Default)]
1970struct CheckboxIndicatorVisual {
1971    hover_progress: f32,
1972    press_progress: f32,
1973    toggle_progress: f32,
1974    focus_progress: f32,
1975}
1976
1977pub fn paint_checkbox_indicator(
1978    ctx: &mut PaintCtx,
1979    theme: &DefaultTheme,
1980    rect: Rect,
1981    state: CheckboxIndicatorState,
1982) {
1983    paint_checkbox_indicator_visual(
1984        ctx,
1985        theme,
1986        rect,
1987        CheckboxIndicatorVisual {
1988            hover_progress: state.hovered as u8 as f32,
1989            press_progress: state.pressed as u8 as f32,
1990            toggle_progress: state.checked as u8 as f32,
1991            focus_progress: state.focused as u8 as f32,
1992        },
1993    );
1994}
1995
1996fn paint_checkbox_indicator_visual(
1997    ctx: &mut PaintCtx,
1998    theme: &DefaultTheme,
1999    rect: Rect,
2000    visual: CheckboxIndicatorVisual,
2001) {
2002    if rect.width() <= 0.0 || rect.height() <= 0.0 {
2003        return;
2004    }
2005
2006    let palette = theme.palette;
2007    let metrics = theme.metrics;
2008    let interaction = theme.interaction;
2009    let hover_blend = visual.hover_progress * interaction.hover_blend;
2010    let press_blend = visual.press_progress * interaction.pressed_blend;
2011    let indicator_background = mix_color(
2012        mix_color(palette.control_active, palette.surface_focus, hover_blend),
2013        mix_color(
2014            mix_color(palette.accent, palette.accent_hover, hover_blend),
2015            palette.accent_pressed,
2016            press_blend,
2017        ),
2018        visual.toggle_progress,
2019    );
2020    let border = mix_color(
2021        mix_color(palette.border, palette.border_hover, visual.hover_progress),
2022        palette.border_focus,
2023        visual.focus_progress,
2024    );
2025    let indicator_border = mix_color(border, palette.accent_border_focus, visual.toggle_progress);
2026
2027    draw_control_shape(
2028        ctx,
2029        rect,
2030        metrics.indicator_corner_radius,
2031        metrics.border_width,
2032        indicator_background,
2033        indicator_border,
2034    );
2035    if visual.toggle_progress > 0.0 {
2036        let check_color = palette.accent_text.with_alpha(visual.toggle_progress);
2037        ctx.stroke(
2038            checkmark_path(rect.inflate(-4.0, -4.0)),
2039            check_color,
2040            StrokeStyle::new(physical_pixels(ctx, interaction.active_indicator_thickness)),
2041        );
2042    }
2043}
2044
2045impl Checkbox {
2046    pub fn new(label: impl Into<String>) -> Self {
2047        Self {
2048            theme: Box::new(DefaultTheme::default()),
2049            theme_reader: None,
2050            label: label.into(),
2051            checked: false,
2052            appearance: ChoiceAppearance::Plain,
2053            text_style: None,
2054            padding: None,
2055            indicator_size: None,
2056            gap: None,
2057            hovered: false,
2058            pressed: false,
2059            hover_animation: AnimatedScalar::new(0.0),
2060            press_animation: AnimatedScalar::new(0.0),
2061            toggle_animation: AnimatedScalar::new(0.0),
2062            focus_animation: AnimatedScalar::new(0.0),
2063            label_measurement: None,
2064            on_toggle: None,
2065        }
2066    }
2067
2068    pub fn checked(mut self, checked: bool) -> Self {
2069        self.checked = checked;
2070        self.toggle_animation = AnimatedScalar::new(checked as u8 as f32);
2071        self
2072    }
2073
2074    pub fn is_checked(&self) -> bool {
2075        self.checked
2076    }
2077
2078    /// Selects whether the complete checkbox row is plain or framed.
2079    pub fn appearance(mut self, appearance: ChoiceAppearance) -> Self {
2080        self.appearance = appearance;
2081        self
2082    }
2083
2084    /// Uses the quiet, transparent-at-rest row treatment.
2085    pub fn plain(self) -> Self {
2086        self.appearance(ChoiceAppearance::Plain)
2087    }
2088
2089    /// Uses the filled and bordered row treatment.
2090    pub fn framed(self) -> Self {
2091        self.appearance(ChoiceAppearance::Framed)
2092    }
2093
2094    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2095        self.theme = Box::new(theme);
2096        self.theme_reader = None;
2097        self
2098    }
2099
2100    pub fn theme_when<F>(mut self, theme: F) -> Self
2101    where
2102        F: Fn() -> DefaultTheme + 'static,
2103    {
2104        self.theme_reader = Some(Box::new(theme));
2105        self
2106    }
2107
2108    pub fn text_style(mut self, text_style: TextStyle) -> Self {
2109        self.text_style = Some(text_style);
2110        self
2111    }
2112
2113    pub fn padding(mut self, padding: Insets) -> Self {
2114        self.padding = Some(padding);
2115        self
2116    }
2117
2118    pub fn indicator_size(mut self, indicator_size: f32) -> Self {
2119        self.indicator_size = Some(indicator_size.max(0.0));
2120        self
2121    }
2122
2123    pub fn gap(mut self, gap: f32) -> Self {
2124        self.gap = Some(gap.max(0.0));
2125        self
2126    }
2127
2128    pub fn set_checked(&mut self, checked: bool) {
2129        self.checked = checked;
2130        self.toggle_animation = AnimatedScalar::new(checked as u8 as f32);
2131    }
2132
2133    pub fn on_toggle<F>(mut self, on_toggle: F) -> Self
2134    where
2135        F: FnMut(bool) + 'static,
2136    {
2137        self.on_toggle = Some(Box::new(on_toggle));
2138        self
2139    }
2140
2141    fn toggle(&mut self) {
2142        self.checked = !self.checked;
2143        if let Some(on_toggle) = &mut self.on_toggle {
2144            on_toggle(self.checked);
2145        }
2146    }
2147
2148    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
2149        if self.hovered != hovered {
2150            let theme = self.resolved_theme();
2151            self.hovered = hovered;
2152            set_hover_animation_target(
2153                &mut self.hover_animation,
2154                hovered as u8 as f32,
2155                &theme,
2156                ctx,
2157            );
2158            ctx.request_paint();
2159            ctx.request_semantics();
2160        }
2161    }
2162
2163    fn advance_animations(&mut self, time: f64) -> bool {
2164        self.hover_animation.advance(time)
2165            | self.press_animation.advance(time)
2166            | self.toggle_animation.advance(time)
2167            | self.focus_animation.advance(time)
2168    }
2169
2170    fn resolved_text_style(&self) -> TextStyle {
2171        self.text_style
2172            .clone()
2173            .unwrap_or_else(|| self.resolved_theme().body_text_style())
2174    }
2175
2176    fn resolved_padding(&self) -> Insets {
2177        self.padding
2178            .unwrap_or(self.resolved_theme().metrics.checkbox_padding)
2179    }
2180
2181    fn resolved_indicator_size(&self) -> f32 {
2182        self.indicator_size
2183            .unwrap_or(self.resolved_theme().metrics.checkbox_indicator_size)
2184    }
2185
2186    fn resolved_gap(&self) -> f32 {
2187        self.gap
2188            .unwrap_or(self.resolved_theme().metrics.checkbox_gap)
2189    }
2190
2191    fn resolved_theme(&self) -> DefaultTheme {
2192        self.theme_reader
2193            .as_ref()
2194            .map(|theme| theme())
2195            .unwrap_or(*self.theme)
2196    }
2197}
2198
2199impl Widget for Checkbox {
2200    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2201        match event {
2202            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2203                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2204            }
2205            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Enter) => {
2206                self.set_hovered(true, ctx);
2207            }
2208            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
2209                self.set_hovered(false, ctx);
2210            }
2211            Event::Pointer(pointer)
2212                if pointer.kind == PointerEventKind::Down
2213                    && pointer.button == Some(PointerButton::Primary) =>
2214            {
2215                let theme = self.resolved_theme();
2216                self.pressed = true;
2217                self.hovered = true;
2218                set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
2219                set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
2220                ctx.request_pointer_capture(pointer.pointer_id);
2221                ctx.request_focus();
2222                ctx.request_paint();
2223                ctx.request_semantics();
2224                ctx.set_handled();
2225            }
2226            Event::Pointer(pointer)
2227                if pointer.kind == PointerEventKind::Up
2228                    && pointer.button == Some(PointerButton::Primary) =>
2229            {
2230                let theme = self.resolved_theme();
2231                let hovered = ctx.bounds().contains(pointer.position);
2232                let toggle = self.pressed && hovered;
2233                self.pressed = false;
2234                self.hovered = hovered;
2235                set_hover_animation_target(
2236                    &mut self.hover_animation,
2237                    hovered as u8 as f32,
2238                    &theme,
2239                    ctx,
2240                );
2241                set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2242                ctx.release_pointer_capture(pointer.pointer_id);
2243                if toggle {
2244                    self.toggle();
2245                    set_toggle_animation_target(
2246                        &mut self.toggle_animation,
2247                        self.checked as u8 as f32,
2248                        &theme,
2249                        ctx,
2250                    );
2251                }
2252                ctx.request_paint();
2253                ctx.request_semantics();
2254                ctx.set_handled();
2255            }
2256            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2257                if self.pressed {
2258                    let theme = self.resolved_theme();
2259                    self.pressed = false;
2260                    self.hovered = false;
2261                    set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
2262                    set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2263                    ctx.release_pointer_capture(pointer.pointer_id);
2264                    ctx.request_paint();
2265                    ctx.request_semantics();
2266                    ctx.set_handled();
2267                }
2268            }
2269            Event::Keyboard(key)
2270                if key.state == KeyState::Pressed
2271                    && ctx.is_focused()
2272                    && matches!(key.key.as_str(), "Enter" | " ") =>
2273            {
2274                let theme = self.resolved_theme();
2275                self.toggle();
2276                set_toggle_animation_target(
2277                    &mut self.toggle_animation,
2278                    self.checked as u8 as f32,
2279                    &theme,
2280                    ctx,
2281                );
2282                ctx.request_paint();
2283                ctx.request_semantics();
2284                ctx.set_handled();
2285            }
2286            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
2287                if self.advance_animations(*time) {
2288                    ctx.request_animation_frame();
2289                }
2290                ctx.request_paint();
2291            }
2292            _ => {}
2293        }
2294    }
2295
2296    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2297        let theme = self.resolved_theme();
2298        let text_style = self.resolved_text_style();
2299        let padding = self.resolved_padding();
2300        let indicator_size = self.resolved_indicator_size();
2301        let gap = self.resolved_gap();
2302        let measurement = measure_text(ctx, &self.label, &text_style);
2303        self.label_measurement = Some(measurement);
2304
2305        let width = padding.left + indicator_size + gap + measurement.width + padding.right;
2306        let content_height = indicator_size.max(measurement.height.max(text_style.line_height));
2307        let height = choice_control_height(
2308            content_height,
2309            padding,
2310            default_form_control_height(&theme),
2311            self.padding.is_some(),
2312        );
2313
2314        constraints.clamp(Size::new(width, height))
2315    }
2316
2317    fn paint(&self, ctx: &mut PaintCtx) {
2318        let theme = self.resolved_theme();
2319        let palette = theme.palette;
2320        let metrics = theme.metrics;
2321        let interaction = theme.interaction;
2322        let text_style = self.resolved_text_style();
2323        let padding = self.resolved_padding();
2324        let indicator_size = self.resolved_indicator_size();
2325        let gap = self.resolved_gap();
2326        let hover_progress = self.hover_animation.value * interaction.hover_blend;
2327        let press_progress = self.press_animation.value * interaction.pressed_blend;
2328        let toggle_progress = self.toggle_animation.value;
2329        let focus_progress = self.focus_animation.value;
2330        let framed_background = mix_color(
2331            mix_color(palette.control, palette.control_hover, hover_progress),
2332            palette.control_active,
2333            press_progress,
2334        );
2335        let framed_border = mix_color(
2336            mix_color(
2337                palette.border,
2338                palette.border_hover,
2339                self.hover_animation.value,
2340            ),
2341            palette.border_focus,
2342            focus_progress,
2343        );
2344        let frame_visuals = choice_frame_visuals(
2345            &theme,
2346            self.appearance,
2347            framed_background,
2348            framed_border,
2349            hover_progress,
2350            press_progress,
2351            focus_progress,
2352        );
2353        let layout_padding = choice_control_layout_padding(padding, self.padding.is_some());
2354        let indicator = indicator_rect(ctx.bounds(), layout_padding, indicator_size);
2355        let label_rect = checkbox_label_rect(ctx.bounds(), layout_padding, indicator_size, gap);
2356
2357        draw_choice_control_frame(
2358            ctx,
2359            ctx.bounds(),
2360            metrics.corner_radius,
2361            metrics,
2362            self.appearance,
2363            frame_visuals,
2364            (focus_progress > 0.0).then_some(
2365                palette
2366                    .focus_ring
2367                    .with_alpha(palette.focus_ring.alpha * focus_progress),
2368            ),
2369        );
2370
2371        paint_checkbox_indicator_visual(
2372            ctx,
2373            &theme,
2374            indicator,
2375            CheckboxIndicatorVisual {
2376                hover_progress: self.hover_animation.value,
2377                press_progress: self.press_animation.value,
2378                toggle_progress,
2379                focus_progress,
2380            },
2381        );
2382        paint_aligned_text(
2383            ctx,
2384            label_rect,
2385            &self.label,
2386            &text_style,
2387            text_style.line_height,
2388            0.0,
2389        );
2390    }
2391
2392    fn semantics(&self, ctx: &mut SemanticsCtx) {
2393        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::CheckBox, ctx.bounds());
2394        node.name = Some(self.label.clone());
2395        node.state.focused = ctx.is_focused();
2396        node.state.hovered = self.hovered;
2397        node.state.checked = Some(if self.checked {
2398            ToggleState::Checked
2399        } else {
2400            ToggleState::Unchecked
2401        });
2402        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
2403        ctx.push(node);
2404    }
2405
2406    fn accepts_focus(&self) -> bool {
2407        true
2408    }
2409
2410    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2411        let theme = self.resolved_theme();
2412        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2413        ctx.request_paint();
2414        ctx.request_semantics();
2415    }
2416}
2417
2418pub struct Switch {
2419    theme: Box<DefaultTheme>,
2420    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2421    label: String,
2422    on: bool,
2423    appearance: ChoiceAppearance,
2424    text_style: Option<TextStyle>,
2425    padding: Option<Insets>,
2426    gap: Option<f32>,
2427    hovered: bool,
2428    pressed: bool,
2429    hover_animation: AnimatedScalar,
2430    press_animation: AnimatedScalar,
2431    toggle_animation: AnimatedScalar,
2432    focus_animation: AnimatedScalar,
2433    label_measurement: Option<TextMeasurement>,
2434    on_toggle: Option<Box<dyn FnMut(bool)>>,
2435}
2436
2437#[derive(Debug, Clone, Copy, PartialEq)]
2438struct SwitchVisuals {
2439    frame_background: Color,
2440    frame_border: Color,
2441    track_color: Color,
2442    track_border: Color,
2443    thumb_color: Color,
2444    label_color: Color,
2445    label_peak_lift: f32,
2446    indicator_style: Option<ResolvedHdrStyle>,
2447}
2448
2449impl Switch {
2450    pub fn new(label: impl Into<String>) -> Self {
2451        Self {
2452            theme: Box::new(DefaultTheme::default()),
2453            theme_reader: None,
2454            label: label.into(),
2455            on: false,
2456            appearance: ChoiceAppearance::Plain,
2457            text_style: None,
2458            padding: None,
2459            gap: None,
2460            hovered: false,
2461            pressed: false,
2462            hover_animation: AnimatedScalar::new(0.0),
2463            press_animation: AnimatedScalar::new(0.0),
2464            toggle_animation: AnimatedScalar::new(0.0),
2465            focus_animation: AnimatedScalar::new(0.0),
2466            label_measurement: None,
2467            on_toggle: None,
2468        }
2469    }
2470
2471    pub fn on(mut self, on: bool) -> Self {
2472        self.on = on;
2473        self.toggle_animation = AnimatedScalar::new(on as u8 as f32);
2474        self
2475    }
2476
2477    pub fn is_on(&self) -> bool {
2478        self.on
2479    }
2480
2481    /// Selects whether the complete switch row is plain or framed.
2482    pub fn appearance(mut self, appearance: ChoiceAppearance) -> Self {
2483        self.appearance = appearance;
2484        self
2485    }
2486
2487    /// Uses the quiet, transparent-at-rest row treatment.
2488    pub fn plain(self) -> Self {
2489        self.appearance(ChoiceAppearance::Plain)
2490    }
2491
2492    /// Uses the filled and bordered row treatment.
2493    pub fn framed(self) -> Self {
2494        self.appearance(ChoiceAppearance::Framed)
2495    }
2496
2497    pub fn set_on(&mut self, on: bool) {
2498        self.on = on;
2499        self.toggle_animation = AnimatedScalar::new(on as u8 as f32);
2500    }
2501
2502    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2503        self.theme = Box::new(theme);
2504        self.theme_reader = None;
2505        self
2506    }
2507
2508    pub fn theme_when<F>(mut self, theme: F) -> Self
2509    where
2510        F: Fn() -> DefaultTheme + 'static,
2511    {
2512        self.theme_reader = Some(Box::new(theme));
2513        self
2514    }
2515
2516    pub fn text_style(mut self, text_style: TextStyle) -> Self {
2517        self.text_style = Some(text_style);
2518        self
2519    }
2520
2521    pub fn padding(mut self, padding: Insets) -> Self {
2522        self.padding = Some(padding);
2523        self
2524    }
2525
2526    pub fn gap(mut self, gap: f32) -> Self {
2527        self.gap = Some(gap.max(0.0));
2528        self
2529    }
2530
2531    pub fn on_toggle<F>(mut self, on_toggle: F) -> Self
2532    where
2533        F: FnMut(bool) + 'static,
2534    {
2535        self.on_toggle = Some(Box::new(on_toggle));
2536        self
2537    }
2538
2539    fn resolved_text_style(&self) -> TextStyle {
2540        self.text_style
2541            .clone()
2542            .unwrap_or_else(|| self.resolved_theme().body_text_style())
2543    }
2544
2545    fn resolved_padding(&self) -> Insets {
2546        self.padding
2547            .unwrap_or(self.resolved_theme().metrics.checkbox_padding)
2548    }
2549
2550    fn resolved_gap(&self) -> f32 {
2551        self.gap
2552            .unwrap_or(self.resolved_theme().metrics.checkbox_gap)
2553    }
2554
2555    fn resolved_theme(&self) -> DefaultTheme {
2556        self.theme_reader
2557            .as_ref()
2558            .map(|theme| theme())
2559            .unwrap_or(*self.theme)
2560    }
2561
2562    fn toggle(&mut self) {
2563        self.on = !self.on;
2564        if let Some(on_toggle) = &mut self.on_toggle {
2565            on_toggle(self.on);
2566        }
2567    }
2568
2569    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
2570        if self.hovered != hovered {
2571            let theme = self.resolved_theme();
2572            self.hovered = hovered;
2573            set_hover_animation_target(
2574                &mut self.hover_animation,
2575                hovered as u8 as f32,
2576                &theme,
2577                ctx,
2578            );
2579            ctx.request_paint();
2580            ctx.request_semantics();
2581        }
2582    }
2583
2584    fn advance_animations(&mut self, time: f64) -> bool {
2585        self.hover_animation.advance(time)
2586            | self.press_animation.advance(time)
2587            | self.toggle_animation.advance(time)
2588            | self.focus_animation.advance(time)
2589    }
2590
2591    fn resolved_visuals_for_state(&self, on: bool, focused: bool) -> SwitchVisuals {
2592        let theme = self.resolved_theme();
2593        let palette = theme.palette;
2594        let interaction = theme.interaction;
2595        let hover_t = self.hover_animation.value * interaction.hover_blend;
2596        let press_t = self.press_animation.value * interaction.pressed_blend;
2597        let framed_background = mix_color(
2598            mix_color(
2599                palette.control,
2600                palette.control_hover,
2601                self.hover_animation.value,
2602            ),
2603            palette.control_active,
2604            press_t,
2605        );
2606        let framed_background = if focused {
2607            mix_color(framed_background, palette.surface_focus, 0.5)
2608        } else {
2609            framed_background
2610        };
2611        let framed_border = mix_color(
2612            mix_color(
2613                palette.border,
2614                palette.border_hover,
2615                self.hover_animation.value,
2616            ),
2617            palette.border_focus,
2618            focused as u8 as f32,
2619        );
2620        let frame_visuals = choice_frame_visuals(
2621            &theme,
2622            self.appearance,
2623            framed_background,
2624            framed_border,
2625            hover_t,
2626            press_t,
2627            focused as u8 as f32,
2628        );
2629        let baseline_track_color = if on {
2630            mix_color(
2631                mix_color(palette.accent, palette.accent_hover, hover_t),
2632                palette.accent_pressed,
2633                press_t,
2634            )
2635        } else {
2636            mix_color(palette.surface_focus, palette.control_active, hover_t)
2637        };
2638        let baseline_track_border = if on {
2639            palette.accent_border
2640        } else {
2641            mix_color(
2642                palette.border,
2643                palette.border_hover,
2644                self.hover_animation.value,
2645            )
2646        };
2647        let thumb_color = if matches!(
2648            theme.colors.scheme,
2649            ThemeColorScheme::Dark | ThemeColorScheme::HighContrast
2650        ) {
2651            palette.text
2652        } else {
2653            palette.accent_text
2654        };
2655        let label_peak_lift = resolve_luminance_role(&theme.hdr, WidgetLuminanceRole::Standard);
2656        let label_color = apply_hdr_policy_cap(self.resolved_text_style().color, label_peak_lift);
2657
2658        if matches!(theme.hdr.mode, HdrThemeMode::Disabled) || !on {
2659            return SwitchVisuals {
2660                frame_background: frame_visuals.background,
2661                frame_border: frame_visuals.border,
2662                track_color: baseline_track_color,
2663                track_border: baseline_track_border,
2664                thumb_color,
2665                label_color,
2666                label_peak_lift,
2667                indicator_style: None,
2668            };
2669        }
2670
2671        let indicator_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
2672            &theme.hdr,
2673            WidgetColorRole::Accent,
2674            WidgetLuminanceRole::EmissiveIndicator,
2675            WidgetMaterialRole::Flat,
2676            None,
2677        ));
2678
2679        SwitchVisuals {
2680            frame_background: frame_visuals.background,
2681            frame_border: frame_visuals.border,
2682            track_color: mix_color(
2683                mix_color(indicator_style.color, palette.accent_hover, hover_t),
2684                palette.accent_pressed,
2685                press_t,
2686            ),
2687            track_border: if focused {
2688                indicator_style.color
2689            } else {
2690                palette.accent_border
2691            },
2692            thumb_color,
2693            label_color,
2694            label_peak_lift,
2695            indicator_style: Some(indicator_style),
2696        }
2697    }
2698
2699    fn resolved_visuals(&self, focused: bool) -> SwitchVisuals {
2700        self.resolved_visuals_for_state(self.on, focused)
2701    }
2702}
2703
2704impl Widget for Switch {
2705    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2706        match event {
2707            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2708                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2709            }
2710            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Enter) => {
2711                self.set_hovered(true, ctx);
2712            }
2713            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
2714                self.set_hovered(false, ctx);
2715            }
2716            Event::Pointer(pointer)
2717                if pointer.kind == PointerEventKind::Down
2718                    && pointer.button == Some(PointerButton::Primary) =>
2719            {
2720                let theme = self.resolved_theme();
2721                self.pressed = true;
2722                self.hovered = true;
2723                set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
2724                set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
2725                ctx.request_pointer_capture(pointer.pointer_id);
2726                ctx.request_focus();
2727                ctx.request_paint();
2728                ctx.request_semantics();
2729                ctx.set_handled();
2730            }
2731            Event::Pointer(pointer)
2732                if pointer.kind == PointerEventKind::Up
2733                    && pointer.button == Some(PointerButton::Primary) =>
2734            {
2735                let theme = self.resolved_theme();
2736                let hovered = ctx.bounds().contains(pointer.position);
2737                let toggle = self.pressed && hovered;
2738                self.pressed = false;
2739                self.hovered = hovered;
2740                set_hover_animation_target(
2741                    &mut self.hover_animation,
2742                    hovered as u8 as f32,
2743                    &theme,
2744                    ctx,
2745                );
2746                set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2747                ctx.release_pointer_capture(pointer.pointer_id);
2748                if toggle {
2749                    self.toggle();
2750                    set_toggle_animation_target(
2751                        &mut self.toggle_animation,
2752                        self.on as u8 as f32,
2753                        &theme,
2754                        ctx,
2755                    );
2756                }
2757                ctx.request_paint();
2758                ctx.request_semantics();
2759                ctx.set_handled();
2760            }
2761            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2762                if self.pressed {
2763                    let theme = self.resolved_theme();
2764                    self.pressed = false;
2765                    self.hovered = false;
2766                    set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
2767                    set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2768                    ctx.release_pointer_capture(pointer.pointer_id);
2769                    ctx.request_paint();
2770                    ctx.request_semantics();
2771                    ctx.set_handled();
2772                }
2773            }
2774            Event::Keyboard(key)
2775                if key.state == KeyState::Pressed
2776                    && ctx.is_focused()
2777                    && matches!(key.key.as_str(), "Enter" | " ") =>
2778            {
2779                let theme = self.resolved_theme();
2780                self.toggle();
2781                set_toggle_animation_target(
2782                    &mut self.toggle_animation,
2783                    self.on as u8 as f32,
2784                    &theme,
2785                    ctx,
2786                );
2787                ctx.request_paint();
2788                ctx.request_semantics();
2789                ctx.set_handled();
2790            }
2791            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
2792                if self.advance_animations(*time) {
2793                    ctx.request_animation_frame();
2794                }
2795                ctx.request_paint();
2796            }
2797            _ => {}
2798        }
2799    }
2800
2801    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2802        let theme = self.resolved_theme();
2803        let text_style = self.resolved_text_style();
2804        let padding = self.resolved_padding();
2805        let gap = self.resolved_gap();
2806        let measurement = measure_text(ctx, &self.label, &text_style);
2807        self.label_measurement = Some(measurement);
2808        let track_width = theme.metrics.switch_track_width;
2809        let track_height = theme.metrics.switch_track_height;
2810
2811        let content_height = track_height.max(measurement.height.max(text_style.line_height));
2812
2813        constraints.clamp(Size::new(
2814            padding.left + track_width + gap + measurement.width + padding.right,
2815            choice_control_height(
2816                content_height,
2817                padding,
2818                default_form_control_height(&theme),
2819                self.padding.is_some(),
2820            ),
2821        ))
2822    }
2823
2824    fn paint(&self, ctx: &mut PaintCtx) {
2825        let theme = self.resolved_theme();
2826        let metrics = theme.metrics;
2827        let palette = theme.palette;
2828        let interaction = theme.interaction;
2829        let text_style = self.resolved_text_style();
2830        let padding = self.resolved_padding();
2831        let gap = self.resolved_gap();
2832        let track = switch_track_rect(ctx.bounds(), padding, metrics);
2833        let label_rect = switch_label_rect(ctx.bounds(), padding, metrics, gap);
2834        let visuals = self.resolved_visuals(ctx.is_focused());
2835        let off_visuals = self.resolved_visuals_for_state(false, ctx.is_focused());
2836        let on_visuals = self.resolved_visuals_for_state(true, ctx.is_focused());
2837        let hover_progress = self.hover_animation.value * interaction.hover_blend;
2838        let press_progress = self.press_animation.value * interaction.pressed_blend;
2839        let toggle_progress = self.toggle_animation.value;
2840        let focus_progress = self.focus_animation.value;
2841
2842        let framed_background = mix_color(
2843            mix_color(
2844                mix_color(palette.control, palette.control_hover, hover_progress),
2845                palette.surface_focus,
2846                focus_progress,
2847            ),
2848            palette.control_active,
2849            press_progress,
2850        );
2851        let framed_border = mix_color(
2852            mix_color(palette.border, palette.border_hover, hover_progress),
2853            palette.border_focus,
2854            focus_progress,
2855        );
2856        let frame_visuals = choice_frame_visuals(
2857            &theme,
2858            self.appearance,
2859            framed_background,
2860            framed_border,
2861            hover_progress,
2862            press_progress,
2863            focus_progress,
2864        );
2865
2866        draw_choice_control_frame(
2867            ctx,
2868            ctx.bounds(),
2869            metrics.corner_radius,
2870            metrics,
2871            self.appearance,
2872            frame_visuals,
2873            (focus_progress > 0.0).then_some(
2874                palette
2875                    .focus_ring
2876                    .with_alpha(palette.focus_ring.alpha * focus_progress),
2877            ),
2878        );
2879
2880        let thumb_inset = metrics.switch_thumb_inset;
2881        let thumb_size = (track.height() - (thumb_inset * 2.0)).max(0.0);
2882        let thumb_x_off = track.x() + thumb_inset;
2883        let thumb_x_on = track.max_x() - thumb_size - thumb_inset;
2884        let thumb = Rect::new(
2885            f32::interpolate(thumb_x_off, thumb_x_on, toggle_progress),
2886            track.y() + thumb_inset,
2887            thumb_size,
2888            thumb_size,
2889        );
2890
2891        let track_color = if toggle_progress <= f32::EPSILON {
2892            off_visuals.track_color
2893        } else if (1.0 - toggle_progress) <= f32::EPSILON {
2894            on_visuals.track_color
2895        } else {
2896            mix_color(
2897                off_visuals.track_color,
2898                on_visuals.track_color,
2899                toggle_progress,
2900            )
2901        };
2902        let track_border = if toggle_progress <= f32::EPSILON {
2903            off_visuals.track_border
2904        } else if (1.0 - toggle_progress) <= f32::EPSILON {
2905            on_visuals.track_border
2906        } else {
2907            mix_color(
2908                off_visuals.track_border,
2909                on_visuals.track_border,
2910                toggle_progress,
2911            )
2912        };
2913
2914        draw_control_shape(
2915            ctx,
2916            track,
2917            track.height() * 0.5,
2918            physical_pixels(ctx, metrics.border_width),
2919            track_color,
2920            track_border,
2921        );
2922        ctx.fill(
2923            Path::circle(rect_center(thumb), thumb.width() * 0.5),
2924            visuals.thumb_color,
2925        );
2926        let text_style = TextStyle {
2927            color: visuals.label_color,
2928            ..text_style
2929        };
2930        paint_aligned_text(
2931            ctx,
2932            label_rect,
2933            &self.label,
2934            &text_style,
2935            text_style.line_height,
2936            0.0,
2937        );
2938    }
2939
2940    fn semantics(&self, ctx: &mut SemanticsCtx) {
2941        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Switch, ctx.bounds());
2942        node.name = Some(self.label.clone());
2943        node.state.focused = ctx.is_focused();
2944        node.state.hovered = self.hovered;
2945        node.state.checked = Some(if self.on {
2946            ToggleState::Checked
2947        } else {
2948            ToggleState::Unchecked
2949        });
2950        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
2951        ctx.push(node);
2952    }
2953
2954    fn accepts_focus(&self) -> bool {
2955        true
2956    }
2957
2958    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2959        let theme = self.resolved_theme();
2960        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2961        ctx.request_paint();
2962        ctx.request_semantics();
2963    }
2964}
2965
2966pub struct RadioButton {
2967    theme: Box<DefaultTheme>,
2968    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2969    label: String,
2970    selected: bool,
2971    appearance: ChoiceAppearance,
2972    text_style: Option<TextStyle>,
2973    padding: Option<Insets>,
2974    indicator_size: Option<f32>,
2975    gap: Option<f32>,
2976    hovered: bool,
2977    pressed: bool,
2978    hover_animation: AnimatedScalar,
2979    press_animation: AnimatedScalar,
2980    toggle_animation: AnimatedScalar,
2981    focus_animation: AnimatedScalar,
2982    label_measurement: Option<TextMeasurement>,
2983    on_select: Option<Box<dyn FnMut()>>,
2984}
2985
2986impl RadioButton {
2987    pub fn new(label: impl Into<String>) -> Self {
2988        Self {
2989            theme: Box::new(DefaultTheme::default()),
2990            theme_reader: None,
2991            label: label.into(),
2992            selected: false,
2993            appearance: ChoiceAppearance::Plain,
2994            text_style: None,
2995            padding: None,
2996            indicator_size: None,
2997            gap: None,
2998            hovered: false,
2999            pressed: false,
3000            hover_animation: AnimatedScalar::new(0.0),
3001            press_animation: AnimatedScalar::new(0.0),
3002            toggle_animation: AnimatedScalar::new(0.0),
3003            focus_animation: AnimatedScalar::new(0.0),
3004            label_measurement: None,
3005            on_select: None,
3006        }
3007    }
3008
3009    pub fn selected(mut self, selected: bool) -> Self {
3010        self.selected = selected;
3011        self.toggle_animation = AnimatedScalar::new(selected as u8 as f32);
3012        self
3013    }
3014
3015    pub fn is_selected(&self) -> bool {
3016        self.selected
3017    }
3018
3019    /// Selects whether the complete radio row is plain or framed.
3020    pub fn appearance(mut self, appearance: ChoiceAppearance) -> Self {
3021        self.appearance = appearance;
3022        self
3023    }
3024
3025    /// Uses the quiet, transparent-at-rest row treatment.
3026    pub fn plain(self) -> Self {
3027        self.appearance(ChoiceAppearance::Plain)
3028    }
3029
3030    /// Uses the filled and bordered row treatment.
3031    pub fn framed(self) -> Self {
3032        self.appearance(ChoiceAppearance::Framed)
3033    }
3034
3035    pub fn set_selected(&mut self, selected: bool) {
3036        self.selected = selected;
3037        self.toggle_animation = AnimatedScalar::new(selected as u8 as f32);
3038    }
3039
3040    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3041        self.theme = Box::new(theme);
3042        self.theme_reader = None;
3043        self
3044    }
3045
3046    pub fn theme_when<F>(mut self, theme: F) -> Self
3047    where
3048        F: Fn() -> DefaultTheme + 'static,
3049    {
3050        self.theme_reader = Some(Box::new(theme));
3051        self
3052    }
3053
3054    pub fn text_style(mut self, text_style: TextStyle) -> Self {
3055        self.text_style = Some(text_style);
3056        self
3057    }
3058
3059    pub fn padding(mut self, padding: Insets) -> Self {
3060        self.padding = Some(padding);
3061        self
3062    }
3063
3064    pub fn indicator_size(mut self, indicator_size: f32) -> Self {
3065        self.indicator_size = Some(indicator_size.max(0.0));
3066        self
3067    }
3068
3069    pub fn gap(mut self, gap: f32) -> Self {
3070        self.gap = Some(gap.max(0.0));
3071        self
3072    }
3073
3074    pub fn on_select<F>(mut self, on_select: F) -> Self
3075    where
3076        F: FnMut() + 'static,
3077    {
3078        self.on_select = Some(Box::new(on_select));
3079        self
3080    }
3081
3082    fn resolved_text_style(&self) -> TextStyle {
3083        self.text_style
3084            .clone()
3085            .unwrap_or_else(|| self.resolved_theme().body_text_style())
3086    }
3087
3088    fn resolved_padding(&self) -> Insets {
3089        self.padding
3090            .unwrap_or(self.resolved_theme().metrics.checkbox_padding)
3091    }
3092
3093    fn resolved_indicator_size(&self) -> f32 {
3094        self.indicator_size
3095            .unwrap_or(self.resolved_theme().metrics.checkbox_indicator_size)
3096    }
3097
3098    fn resolved_gap(&self) -> f32 {
3099        self.gap
3100            .unwrap_or(self.resolved_theme().metrics.checkbox_gap)
3101    }
3102
3103    fn resolved_theme(&self) -> DefaultTheme {
3104        self.theme_reader
3105            .as_ref()
3106            .map(|theme| theme())
3107            .unwrap_or(*self.theme)
3108    }
3109
3110    fn activate(&mut self, ctx: &mut EventCtx) {
3111        let theme = self.resolved_theme();
3112        let changed = !self.selected;
3113        self.selected = true;
3114        if changed {
3115            set_toggle_animation_target(&mut self.toggle_animation, 1.0, &theme, ctx);
3116        }
3117        if let Some(on_select) = &mut self.on_select {
3118            on_select();
3119        }
3120    }
3121
3122    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
3123        if self.hovered != hovered {
3124            let theme = self.resolved_theme();
3125            self.hovered = hovered;
3126            set_hover_animation_target(
3127                &mut self.hover_animation,
3128                hovered as u8 as f32,
3129                &theme,
3130                ctx,
3131            );
3132            ctx.request_paint();
3133            ctx.request_semantics();
3134        }
3135    }
3136
3137    fn advance_animations(&mut self, time: f64) -> bool {
3138        self.hover_animation.advance(time)
3139            | self.press_animation.advance(time)
3140            | self.toggle_animation.advance(time)
3141            | self.focus_animation.advance(time)
3142    }
3143}
3144
3145impl Widget for RadioButton {
3146    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
3147        match event {
3148            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
3149                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
3150            }
3151            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Enter) => {
3152                self.set_hovered(true, ctx);
3153            }
3154            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
3155                self.set_hovered(false, ctx);
3156            }
3157            Event::Pointer(pointer)
3158                if pointer.kind == PointerEventKind::Down
3159                    && pointer.button == Some(PointerButton::Primary) =>
3160            {
3161                let theme = self.resolved_theme();
3162                self.pressed = true;
3163                self.hovered = true;
3164                set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
3165                set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
3166                ctx.request_pointer_capture(pointer.pointer_id);
3167                ctx.request_focus();
3168                ctx.request_paint();
3169                ctx.request_semantics();
3170                ctx.set_handled();
3171            }
3172            Event::Pointer(pointer)
3173                if pointer.kind == PointerEventKind::Up
3174                    && pointer.button == Some(PointerButton::Primary) =>
3175            {
3176                let theme = self.resolved_theme();
3177                let hovered = ctx.bounds().contains(pointer.position);
3178                let activate = self.pressed && hovered;
3179                self.pressed = false;
3180                self.hovered = hovered;
3181                set_hover_animation_target(
3182                    &mut self.hover_animation,
3183                    hovered as u8 as f32,
3184                    &theme,
3185                    ctx,
3186                );
3187                set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
3188                ctx.release_pointer_capture(pointer.pointer_id);
3189                if activate {
3190                    self.activate(ctx);
3191                }
3192                ctx.request_paint();
3193                ctx.request_semantics();
3194                ctx.set_handled();
3195            }
3196            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
3197                if self.pressed {
3198                    let theme = self.resolved_theme();
3199                    self.pressed = false;
3200                    self.hovered = false;
3201                    set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
3202                    set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
3203                    ctx.release_pointer_capture(pointer.pointer_id);
3204                    ctx.request_paint();
3205                    ctx.request_semantics();
3206                    ctx.set_handled();
3207                }
3208            }
3209            Event::Keyboard(key)
3210                if key.state == KeyState::Pressed
3211                    && ctx.is_focused()
3212                    && matches!(key.key.as_str(), "Enter" | " ") =>
3213            {
3214                self.activate(ctx);
3215                ctx.request_paint();
3216                ctx.request_semantics();
3217                ctx.set_handled();
3218            }
3219            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
3220                if self.advance_animations(*time) {
3221                    ctx.request_animation_frame();
3222                }
3223                ctx.request_paint();
3224            }
3225            _ => {}
3226        }
3227    }
3228
3229    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3230        let text_style = self.resolved_text_style();
3231        let padding = self.resolved_padding();
3232        let indicator_size = self.resolved_indicator_size();
3233        let gap = self.resolved_gap();
3234        let measurement = measure_text(ctx, &self.label, &text_style);
3235        self.label_measurement = Some(measurement);
3236
3237        let theme = self.resolved_theme();
3238        let content_height = indicator_size.max(measurement.height.max(text_style.line_height));
3239
3240        constraints.clamp(Size::new(
3241            padding.left + indicator_size + gap + measurement.width + padding.right,
3242            choice_control_height(
3243                content_height,
3244                padding,
3245                default_form_control_height(&theme),
3246                self.padding.is_some(),
3247            ),
3248        ))
3249    }
3250
3251    fn paint(&self, ctx: &mut PaintCtx) {
3252        let theme = self.resolved_theme();
3253        let palette = theme.palette;
3254        let metrics = theme.metrics;
3255        let interaction = theme.interaction;
3256        let text_style = self.resolved_text_style();
3257        let padding = self.resolved_padding();
3258        let indicator_size = self.resolved_indicator_size();
3259        let gap = self.resolved_gap();
3260        let hover_progress = self.hover_animation.value * interaction.hover_blend;
3261        let press_progress = self.press_animation.value * interaction.pressed_blend;
3262        let toggle_progress = self.toggle_animation.value;
3263        let focus_progress = self.focus_animation.value;
3264        let layout_padding = choice_control_layout_padding(padding, self.padding.is_some());
3265        let indicator = indicator_rect(ctx.bounds(), layout_padding, indicator_size);
3266        let label_rect = checkbox_label_rect(ctx.bounds(), layout_padding, indicator_size, gap);
3267        let framed_background = mix_color(
3268            mix_color(
3269                mix_color(palette.control, palette.control_hover, hover_progress),
3270                palette.surface_focus,
3271                focus_progress,
3272            ),
3273            palette.control_active,
3274            press_progress,
3275        );
3276        let framed_border = mix_color(
3277            mix_color(palette.border, palette.border_hover, hover_progress),
3278            palette.border_focus,
3279            focus_progress,
3280        );
3281        let frame_visuals = choice_frame_visuals(
3282            &theme,
3283            self.appearance,
3284            framed_background,
3285            framed_border,
3286            hover_progress,
3287            press_progress,
3288            focus_progress,
3289        );
3290
3291        draw_choice_control_frame(
3292            ctx,
3293            ctx.bounds(),
3294            metrics.corner_radius,
3295            metrics,
3296            self.appearance,
3297            frame_visuals,
3298            (focus_progress > 0.0).then_some(
3299                palette
3300                    .focus_ring
3301                    .with_alpha(palette.focus_ring.alpha * focus_progress),
3302            ),
3303        );
3304
3305        ctx.fill(
3306            Path::circle(rect_center(indicator), indicator.width() * 0.5),
3307            mix_color(
3308                mix_color(
3309                    palette.control_active,
3310                    palette.surface_focus,
3311                    hover_progress,
3312                ),
3313                mix_color(
3314                    mix_color(palette.accent, palette.accent_hover, hover_progress),
3315                    palette.accent_pressed,
3316                    press_progress,
3317                ),
3318                toggle_progress,
3319            ),
3320        );
3321        ctx.stroke(
3322            Path::circle(rect_center(indicator), (indicator.width() * 0.5) - 0.5),
3323            mix_color(framed_border, palette.accent_border_focus, toggle_progress),
3324            StrokeStyle::new(physical_pixels(ctx, metrics.border_width)),
3325        );
3326        if toggle_progress > 0.0 {
3327            ctx.fill(
3328                Path::circle(
3329                    rect_center(indicator),
3330                    indicator.width() * 0.22 * toggle_progress,
3331                ),
3332                palette.accent_text.with_alpha(toggle_progress),
3333            );
3334        }
3335        paint_aligned_text(
3336            ctx,
3337            label_rect,
3338            &self.label,
3339            &text_style,
3340            text_style.line_height,
3341            0.0,
3342        );
3343    }
3344
3345    fn semantics(&self, ctx: &mut SemanticsCtx) {
3346        let mut node =
3347            SemanticsNode::new(ctx.widget_id(), SemanticsRole::RadioButton, ctx.bounds());
3348        node.name = Some(self.label.clone());
3349        node.state.focused = ctx.is_focused();
3350        node.state.hovered = self.hovered;
3351        node.state.selected = self.selected;
3352        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
3353        ctx.push(node);
3354    }
3355
3356    fn accepts_focus(&self) -> bool {
3357        true
3358    }
3359
3360    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3361        let theme = self.resolved_theme();
3362        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
3363        ctx.request_paint();
3364        ctx.request_semantics();
3365    }
3366}
3367
3368pub struct RadioGroup {
3369    theme: Box<DefaultTheme>,
3370    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3371    name: String,
3372    options: Vec<String>,
3373    selected: Option<usize>,
3374    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
3375    hovered: Option<usize>,
3376    pressed: Option<usize>,
3377    hover_visual: Option<usize>,
3378    press_visual: Option<usize>,
3379    selected_visual: Option<usize>,
3380    hover_animation: AnimatedScalar,
3381    press_animation: AnimatedScalar,
3382    selection_animation: AnimatedScalar,
3383    focus_animation: AnimatedScalar,
3384    label_measurements: Vec<TextMeasurement>,
3385    spacing: f32,
3386    on_change: Option<Box<dyn FnMut(usize, String)>>,
3387}
3388
3389impl RadioGroup {
3390    pub fn new(name: impl Into<String>) -> Self {
3391        Self {
3392            theme: Box::new(DefaultTheme::default()),
3393            theme_reader: None,
3394            name: name.into(),
3395            options: Vec::new(),
3396            selected: None,
3397            selected_reader: None,
3398            hovered: None,
3399            pressed: None,
3400            hover_visual: None,
3401            press_visual: None,
3402            selected_visual: None,
3403            hover_animation: AnimatedScalar::new(0.0),
3404            press_animation: AnimatedScalar::new(0.0),
3405            selection_animation: AnimatedScalar::new(0.0),
3406            focus_animation: AnimatedScalar::new(0.0),
3407            label_measurements: Vec::new(),
3408            spacing: 6.0,
3409            on_change: None,
3410        }
3411    }
3412
3413    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3414        self.theme = Box::new(theme);
3415        self.theme_reader = None;
3416        self
3417    }
3418
3419    pub fn theme_when<F>(mut self, theme: F) -> Self
3420    where
3421        F: Fn() -> DefaultTheme + 'static,
3422    {
3423        self.theme_reader = Some(Box::new(theme));
3424        self
3425    }
3426
3427    pub fn option(mut self, option: impl Into<String>) -> Self {
3428        self.options.push(option.into());
3429        self
3430    }
3431
3432    pub fn options<I, S>(mut self, options: I) -> Self
3433    where
3434        I: IntoIterator<Item = S>,
3435        S: Into<String>,
3436    {
3437        self.options.extend(options.into_iter().map(Into::into));
3438        self
3439    }
3440
3441    pub fn selected(mut self, selected: usize) -> Self {
3442        self.selected = Some(selected);
3443        self.selected_reader = None;
3444        self.selected_visual = Some(selected);
3445        self.selection_animation = AnimatedScalar::new(1.0);
3446        self
3447    }
3448
3449    pub const fn selected_index(&self) -> Option<usize> {
3450        self.selected
3451    }
3452
3453    pub fn selected_when<F>(mut self, selected: F) -> Self
3454    where
3455        F: Fn() -> Option<usize> + 'static,
3456    {
3457        self.selected_reader = Some(Box::new(selected));
3458        self
3459    }
3460
3461    pub fn on_change<F>(mut self, on_change: F) -> Self
3462    where
3463        F: FnMut(usize, String) + 'static,
3464    {
3465        self.on_change = Some(Box::new(on_change));
3466        self
3467    }
3468
3469    fn row_height(&self) -> f32 {
3470        default_form_control_height(&self.resolved_theme())
3471    }
3472
3473    fn row_rect(&self, bounds: Rect, index: usize) -> Rect {
3474        let y = bounds.y() + (index as f32 * (self.row_height() + self.spacing));
3475        Rect::new(bounds.x(), y, bounds.width(), self.row_height())
3476    }
3477
3478    fn option_at(&self, bounds: Rect, position: Point) -> Option<usize> {
3479        self.options.iter().enumerate().find_map(|(index, _)| {
3480            self.row_rect(bounds, index)
3481                .contains(position)
3482                .then_some(index)
3483        })
3484    }
3485
3486    fn current_selected_index(&self) -> Option<usize> {
3487        self.selected_reader
3488            .as_ref()
3489            .map(|reader| reader())
3490            .unwrap_or(self.selected)
3491            .filter(|index| *index < self.options.len())
3492    }
3493
3494    fn select(&mut self, index: usize, ctx: &mut EventCtx) {
3495        if self.options.is_empty() {
3496            return;
3497        }
3498
3499        let selected = index.min(self.options.len().saturating_sub(1));
3500        let changed = self.current_selected_index() != Some(selected);
3501        self.selected = Some(selected);
3502        if changed || self.selected_visual != Some(selected) {
3503            let theme = self.resolved_theme();
3504            self.selected_visual = Some(selected);
3505            self.selection_animation = AnimatedScalar::new(0.0);
3506            set_toggle_animation_target(&mut self.selection_animation, 1.0, &theme, ctx);
3507        }
3508        if let Some(on_change) = &mut self.on_change {
3509            on_change(selected, self.options[selected].clone());
3510        }
3511    }
3512
3513    fn resolved_theme(&self) -> DefaultTheme {
3514        self.theme_reader
3515            .as_ref()
3516            .map(|theme| theme())
3517            .unwrap_or(*self.theme)
3518    }
3519
3520    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
3521        if self.hovered == hovered && self.hover_visual == hovered {
3522            return;
3523        }
3524
3525        let theme = self.resolved_theme();
3526        self.hovered = hovered;
3527        match hovered {
3528            Some(index) => {
3529                if self.hover_visual != Some(index) {
3530                    self.hover_visual = Some(index);
3531                    self.hover_animation = AnimatedScalar::new(0.0);
3532                }
3533                set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
3534            }
3535            None => {
3536                set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
3537            }
3538        }
3539        ctx.request_paint();
3540        ctx.request_semantics();
3541    }
3542
3543    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
3544        if self.pressed == pressed && self.press_visual == pressed {
3545            return;
3546        }
3547
3548        let theme = self.resolved_theme();
3549        self.pressed = pressed;
3550        match pressed {
3551            Some(index) => {
3552                if self.press_visual != Some(index) {
3553                    self.press_visual = Some(index);
3554                    self.press_animation = AnimatedScalar::new(0.0);
3555                }
3556                set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
3557            }
3558            None => {
3559                set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
3560            }
3561        }
3562        ctx.request_paint();
3563        ctx.request_semantics();
3564    }
3565
3566    fn hover_progress_for(&self, index: usize) -> f32 {
3567        if self.hover_visual == Some(index) {
3568            self.hover_animation.value
3569        } else {
3570            0.0
3571        }
3572    }
3573
3574    fn press_progress_for(&self, index: usize) -> f32 {
3575        if self.press_visual == Some(index) {
3576            self.press_animation.value
3577        } else {
3578            0.0
3579        }
3580    }
3581
3582    fn selection_progress_for(&self, index: usize) -> f32 {
3583        let selected = self.current_selected_index();
3584        if selected == Some(index) && self.selected_visual == Some(index) {
3585            self.selection_animation.value
3586        } else if selected == Some(index) {
3587            1.0
3588        } else {
3589            0.0
3590        }
3591    }
3592
3593    fn advance_animations(&mut self, time: f64) -> (bool, bool) {
3594        let previous_hover = self.hover_animation.value;
3595        let previous_press = self.press_animation.value;
3596        let previous_selection = self.selection_animation.value;
3597        let previous_focus = self.focus_animation.value;
3598        let active = self.hover_animation.advance(time)
3599            | self.press_animation.advance(time)
3600            | self.selection_animation.advance(time)
3601            | self.focus_animation.advance(time);
3602        let changed = self.hover_animation.changed_since(previous_hover)
3603            || self.press_animation.changed_since(previous_press)
3604            || self.selection_animation.changed_since(previous_selection)
3605            || self.focus_animation.changed_since(previous_focus);
3606
3607        if self.hovered.is_none() && !self.hover_animation.is_presented() {
3608            self.hover_visual = None;
3609        }
3610        if self.pressed.is_none() && !self.press_animation.is_presented() {
3611            self.press_visual = None;
3612        }
3613
3614        (changed, active)
3615    }
3616}
3617
3618impl Widget for RadioGroup {
3619    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
3620        match event {
3621            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
3622                self.set_hovered(self.option_at(ctx.bounds(), pointer.position), ctx);
3623            }
3624            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Enter) => {
3625                self.set_hovered(self.option_at(ctx.bounds(), pointer.position), ctx);
3626            }
3627            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
3628                self.set_hovered(None, ctx);
3629            }
3630            Event::Pointer(pointer)
3631                if pointer.kind == PointerEventKind::Down
3632                    && pointer.button == Some(PointerButton::Primary) =>
3633            {
3634                let hovered = self.option_at(ctx.bounds(), pointer.position);
3635                self.set_hovered(hovered, ctx);
3636                self.set_pressed(hovered, ctx);
3637                ctx.request_focus();
3638                ctx.request_pointer_capture(pointer.pointer_id);
3639                ctx.request_paint();
3640                ctx.request_semantics();
3641                ctx.set_handled();
3642            }
3643            Event::Pointer(pointer)
3644                if pointer.kind == PointerEventKind::Up
3645                    && pointer.button == Some(PointerButton::Primary) =>
3646            {
3647                let hovered = self.option_at(ctx.bounds(), pointer.position);
3648                let activate = self
3649                    .pressed
3650                    .zip(hovered)
3651                    .filter(|(pressed, hovered)| pressed == hovered);
3652                self.set_hovered(hovered, ctx);
3653                self.set_pressed(None, ctx);
3654                ctx.release_pointer_capture(pointer.pointer_id);
3655                if let Some((index, _)) = activate {
3656                    self.select(index, ctx);
3657                }
3658                ctx.request_paint();
3659                ctx.request_semantics();
3660                ctx.set_handled();
3661            }
3662            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
3663                if self.pressed.is_some() {
3664                    self.set_pressed(None, ctx);
3665                    ctx.release_pointer_capture(pointer.pointer_id);
3666                    ctx.request_paint();
3667                    ctx.request_semantics();
3668                    ctx.set_handled();
3669                }
3670            }
3671            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
3672                let SemanticsActionRequest::SetValue(SemanticsValue::Text(value)) =
3673                    &semantics.action
3674                else {
3675                    return;
3676                };
3677                let Some(index) = self.options.iter().position(|option| option == value) else {
3678                    return;
3679                };
3680                self.set_hovered(Some(index), ctx);
3681                self.select(index, ctx);
3682                ctx.request_paint();
3683                ctx.request_semantics();
3684                ctx.set_handled();
3685            }
3686            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
3687                if self.options.is_empty() {
3688                    return;
3689                }
3690
3691                let current = self
3692                    .current_selected_index()
3693                    .unwrap_or(0)
3694                    .min(self.options.len() - 1);
3695                let next = match key.key.as_str() {
3696                    "ArrowUp" | "ArrowLeft" => Some(current.saturating_sub(1)),
3697                    "ArrowDown" | "ArrowRight" => Some((current + 1).min(self.options.len() - 1)),
3698                    "Home" => Some(0),
3699                    "End" => Some(self.options.len() - 1),
3700                    "Enter" | " " => Some(current),
3701                    _ => None,
3702                };
3703
3704                if let Some(next) = next {
3705                    self.set_hovered(Some(next), ctx);
3706                    self.select(next, ctx);
3707                    ctx.request_paint();
3708                    ctx.request_semantics();
3709                    ctx.set_handled();
3710                }
3711            }
3712            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
3713                let (changed, active) = self.advance_animations(*time);
3714                if changed {
3715                    ctx.request_paint();
3716                }
3717                if active {
3718                    ctx.request_animation_frame();
3719                }
3720                ctx.set_handled();
3721            }
3722            _ => {}
3723        }
3724    }
3725
3726    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3727        let theme = self.resolved_theme();
3728        let text_style = theme.body_text_style();
3729        let padding = theme.metrics.checkbox_padding;
3730        let indicator = theme.metrics.checkbox_indicator_size;
3731        let gap = theme.metrics.checkbox_gap;
3732        let mut width: f32 = 0.0;
3733        self.label_measurements.clear();
3734
3735        for option in &self.options {
3736            let measurement = measure_text(ctx, option, &text_style);
3737            self.label_measurements.push(measurement);
3738            width = width.max(padding.left + indicator + gap + measurement.width + padding.right);
3739        }
3740
3741        let count = self.options.len() as f32;
3742        let height = if self.options.is_empty() {
3743            self.row_height()
3744        } else {
3745            (count * self.row_height()) + ((count - 1.0) * self.spacing.max(0.0))
3746        };
3747
3748        constraints.clamp(Size::new(width.max(theme.metrics.button_min_width), height))
3749    }
3750
3751    fn paint(&self, ctx: &mut PaintCtx) {
3752        let theme = self.resolved_theme();
3753        let palette = theme.palette;
3754        let metrics = theme.metrics;
3755        let interaction = theme.interaction;
3756        let focus_progress = self.focus_animation.value;
3757        let row_padding = Insets {
3758            top: 0.0,
3759            bottom: 0.0,
3760            ..metrics.checkbox_padding
3761        };
3762
3763        if focus_progress > AnimatedScalar::EPSILON {
3764            let outset = physical_pixels(ctx, metrics.focus_ring_outset);
3765            ctx.stroke(
3766                rounded_rect_path(
3767                    ctx.bounds().inflate(outset, outset),
3768                    metrics.corner_radius + outset,
3769                ),
3770                palette
3771                    .focus_ring
3772                    .with_alpha(palette.focus_ring.alpha * focus_progress),
3773                StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
3774            );
3775        }
3776
3777        for (index, option) in self.options.iter().enumerate() {
3778            let row = self.row_rect(ctx.bounds(), index);
3779            let indicator = indicator_rect(row, row_padding, metrics.checkbox_indicator_size);
3780            let label_rect = checkbox_label_rect(
3781                row,
3782                row_padding,
3783                metrics.checkbox_indicator_size,
3784                metrics.checkbox_gap,
3785            );
3786            let hover_progress = self.hover_progress_for(index);
3787            let press_progress = self.press_progress_for(index);
3788            let selection_progress = self.selection_progress_for(index);
3789            let hover_amount = hover_progress * interaction.hover_blend;
3790            let press_amount = press_progress * interaction.pressed_blend;
3791            let background = mix_color(
3792                mix_color(palette.control, palette.control_hover, hover_amount),
3793                palette.control_active,
3794                press_amount,
3795            );
3796            let border = mix_color(
3797                mix_color(palette.border, palette.border_hover, hover_progress),
3798                palette.accent_border,
3799                selection_progress,
3800            );
3801            let indicator_fill = mix_color(
3802                mix_color(palette.control_active, palette.surface_focus, hover_amount),
3803                mix_color(
3804                    mix_color(palette.accent, palette.accent_hover, hover_amount),
3805                    palette.accent_pressed,
3806                    press_amount,
3807                ),
3808                selection_progress,
3809            );
3810
3811            draw_control_shape(
3812                ctx,
3813                row,
3814                metrics.corner_radius,
3815                physical_pixels(ctx, metrics.border_width),
3816                background,
3817                border,
3818            );
3819            ctx.fill(
3820                Path::circle(rect_center(indicator), indicator.width() * 0.5),
3821                indicator_fill,
3822            );
3823            ctx.stroke(
3824                Path::circle(rect_center(indicator), (indicator.width() * 0.5) - 0.5),
3825                border,
3826                StrokeStyle::new(physical_pixels(ctx, metrics.border_width)),
3827            );
3828            if selection_progress > AnimatedScalar::EPSILON {
3829                ctx.fill(
3830                    Path::circle(
3831                        rect_center(indicator),
3832                        indicator.width() * 0.22 * selection_progress,
3833                    ),
3834                    palette.accent_text.with_alpha(selection_progress),
3835                );
3836            }
3837            let text_style = theme.body_text_style();
3838            paint_aligned_text(
3839                ctx,
3840                label_rect,
3841                option,
3842                &text_style,
3843                text_style.line_height,
3844                0.0,
3845            );
3846        }
3847    }
3848
3849    fn semantics(&self, ctx: &mut SemanticsCtx) {
3850        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::RadioGroup, ctx.bounds());
3851        node.name = Some(self.name.clone());
3852        node.value = self
3853            .current_selected_index()
3854            .and_then(|index| self.options.get(index).cloned())
3855            .map(SemanticsValue::Text);
3856        node.state.focused = ctx.is_focused();
3857        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
3858        ctx.push(node);
3859    }
3860
3861    fn accepts_focus(&self) -> bool {
3862        true
3863    }
3864
3865    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3866        let theme = self.resolved_theme();
3867        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
3868        ctx.request_paint();
3869        ctx.request_semantics();
3870    }
3871}
3872
3873pub struct Slider {
3874    theme: Box<DefaultTheme>,
3875    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3876    name: String,
3877    min: f64,
3878    max: f64,
3879    step: f64,
3880    value: f64,
3881    value_reader: Option<Box<dyn Fn() -> f64>>,
3882    hovered: bool,
3883    dragging: bool,
3884    hover_animation: AnimatedScalar,
3885    drag_animation: AnimatedScalar,
3886    focus_animation: AnimatedScalar,
3887    on_change: Option<Box<dyn FnMut(f64)>>,
3888    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, f64)>>,
3889}
3890
3891impl Slider {
3892    pub fn new(name: impl Into<String>) -> Self {
3893        Self {
3894            theme: Box::new(DefaultTheme::default()),
3895            theme_reader: None,
3896            name: name.into(),
3897            min: 0.0,
3898            max: 1.0,
3899            step: 0.01,
3900            value: 0.0,
3901            value_reader: None,
3902            hovered: false,
3903            dragging: false,
3904            hover_animation: AnimatedScalar::new(0.0),
3905            drag_animation: AnimatedScalar::new(0.0),
3906            focus_animation: AnimatedScalar::new(0.0),
3907            on_change: None,
3908            on_change_with_ctx: None,
3909        }
3910    }
3911
3912    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3913        self.theme = Box::new(theme);
3914        self.theme_reader = None;
3915        self
3916    }
3917
3918    pub fn theme_when<F>(mut self, theme: F) -> Self
3919    where
3920        F: Fn() -> DefaultTheme + 'static,
3921    {
3922        self.theme_reader = Some(Box::new(theme));
3923        self
3924    }
3925
3926    pub fn range(mut self, min: f64, max: f64) -> Self {
3927        self.min = min.min(max);
3928        self.max = max.max(min);
3929        self.value = clamp_and_snap_value(self.value, self.min, self.max, self.step);
3930        self
3931    }
3932
3933    pub fn step(mut self, step: f64) -> Self {
3934        self.step = step.abs();
3935        self.value = clamp_and_snap_value(self.value, self.min, self.max, self.step);
3936        self
3937    }
3938
3939    pub fn value(mut self, value: f64) -> Self {
3940        self.value = clamp_and_snap_value(value, self.min, self.max, self.step);
3941        self.value_reader = None;
3942        self
3943    }
3944
3945    pub fn value_when<F>(mut self, value: F) -> Self
3946    where
3947        F: Fn() -> f64 + 'static,
3948    {
3949        self.value_reader = Some(Box::new(value));
3950        self
3951    }
3952
3953    pub const fn current_value(&self) -> f64 {
3954        self.value
3955    }
3956
3957    pub fn on_change<F>(mut self, on_change: F) -> Self
3958    where
3959        F: FnMut(f64) + 'static,
3960    {
3961        self.on_change = Some(Box::new(on_change));
3962        self
3963    }
3964
3965    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
3966    where
3967        F: FnMut(&mut EventCtx, f64) + 'static,
3968    {
3969        self.on_change_with_ctx = Some(Box::new(on_change));
3970        self
3971    }
3972
3973    fn resolved_value(&self) -> f64 {
3974        if self.dragging {
3975            return self.value;
3976        }
3977
3978        self.value_reader
3979            .as_ref()
3980            .map(|reader| clamp_and_snap_value(reader(), self.min, self.max, self.step))
3981            .unwrap_or(self.value)
3982    }
3983
3984    fn fraction_for(&self, value: f64) -> f32 {
3985        if (self.max - self.min).abs() <= f64::EPSILON {
3986            return 0.0;
3987        }
3988
3989        ((value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) as f32
3990    }
3991
3992    fn sync_external_value(&mut self) {
3993        if self.dragging {
3994            return;
3995        }
3996        let Some(reader) = &self.value_reader else {
3997            return;
3998        };
3999        self.value = clamp_and_snap_value(reader(), self.min, self.max, self.step);
4000    }
4001
4002    fn resolved_theme(&self) -> DefaultTheme {
4003        self.theme_reader
4004            .as_ref()
4005            .map(|theme| theme())
4006            .unwrap_or(*self.theme)
4007    }
4008
4009    fn track_rect(&self, bounds: Rect) -> Rect {
4010        let theme = self.resolved_theme();
4011        let padding = theme.metrics.slider_padding;
4012        let height = theme.metrics.slider_track_height.max(1.0);
4013        Rect::new(
4014            bounds.x() + padding.left,
4015            bounds.y() + ((bounds.height() - height) * 0.5),
4016            (bounds.width() - padding.left - padding.right).max(0.0),
4017            height,
4018        )
4019    }
4020
4021    fn thumb_rect_for(&self, bounds: Rect, value: f64) -> Rect {
4022        let track = self.track_rect(bounds);
4023        let theme = self.resolved_theme();
4024        let thumb = theme.metrics.slider_thumb_size;
4025        Rect::new(
4026            track.x() + (track.width() * self.fraction_for(value)) - (thumb * 0.5),
4027            bounds.y() + ((bounds.height() - thumb) * 0.5),
4028            thumb,
4029            thumb,
4030        )
4031    }
4032
4033    fn emit_change(&mut self, ctx: &mut EventCtx) {
4034        if let Some(on_change) = &mut self.on_change {
4035            on_change(self.value);
4036        }
4037        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
4038            on_change_with_ctx(ctx, self.value);
4039        }
4040    }
4041
4042    fn set_from_position(&mut self, ctx: &mut EventCtx, bounds: Rect, position: Point) {
4043        let track = self.track_rect(bounds);
4044        if track.width() <= 0.0 {
4045            return;
4046        }
4047
4048        let fraction = ((position.x - track.x()) / track.width()).clamp(0.0, 1.0);
4049        let raw = self.min + ((self.max - self.min) * f64::from(fraction));
4050        let next = clamp_and_snap_value(raw, self.min, self.max, self.step);
4051        if (next - self.value).abs() > f64::EPSILON {
4052            self.value = next;
4053            self.emit_change(ctx);
4054        }
4055    }
4056
4057    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
4058        if self.hovered != hovered {
4059            let theme = self.resolved_theme();
4060            self.hovered = hovered;
4061            set_hover_animation_target(
4062                &mut self.hover_animation,
4063                hovered as u8 as f32,
4064                &theme,
4065                ctx,
4066            );
4067            ctx.request_paint();
4068            ctx.request_semantics();
4069        }
4070    }
4071
4072    fn advance_animations(&mut self, time: f64) -> bool {
4073        self.hover_animation.advance(time)
4074            | self.drag_animation.advance(time)
4075            | self.focus_animation.advance(time)
4076    }
4077}
4078
4079impl Widget for Slider {
4080    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4081        self.sync_external_value();
4082
4083        match event {
4084            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
4085                let hovered = ctx.bounds().contains(pointer.position);
4086                self.set_hovered(hovered, ctx);
4087                if self.dragging {
4088                    let previous = self.value;
4089                    self.set_from_position(ctx, ctx.bounds(), pointer.position);
4090                    if (self.value - previous).abs() > f64::EPSILON {
4091                        ctx.request_paint();
4092                        ctx.request_semantics();
4093                    }
4094                }
4095            }
4096            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Enter) => {
4097                self.set_hovered(true, ctx);
4098            }
4099            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
4100                self.set_hovered(false, ctx);
4101            }
4102            Event::Pointer(pointer)
4103                if pointer.kind == PointerEventKind::Down
4104                    && pointer.button == Some(PointerButton::Primary) =>
4105            {
4106                let theme = self.resolved_theme();
4107                self.dragging = true;
4108                self.hovered = true;
4109                set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
4110                set_press_animation_target(&mut self.drag_animation, 1.0, &theme, ctx);
4111                self.set_from_position(ctx, ctx.bounds(), pointer.position);
4112                ctx.request_pointer_capture(pointer.pointer_id);
4113                ctx.request_focus();
4114                ctx.request_paint();
4115                ctx.request_semantics();
4116                ctx.set_handled();
4117            }
4118            Event::Pointer(pointer)
4119                if pointer.kind == PointerEventKind::Up
4120                    && pointer.button == Some(PointerButton::Primary) =>
4121            {
4122                let theme = self.resolved_theme();
4123                self.dragging = false;
4124                self.hovered = ctx.bounds().contains(pointer.position);
4125                set_hover_animation_target(
4126                    &mut self.hover_animation,
4127                    self.hovered as u8 as f32,
4128                    &theme,
4129                    ctx,
4130                );
4131                set_press_animation_target(&mut self.drag_animation, 0.0, &theme, ctx);
4132                self.set_from_position(ctx, ctx.bounds(), pointer.position);
4133                ctx.release_pointer_capture(pointer.pointer_id);
4134                ctx.request_paint();
4135                ctx.request_semantics();
4136                ctx.set_handled();
4137            }
4138            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
4139                if self.dragging {
4140                    let theme = self.resolved_theme();
4141                    self.dragging = false;
4142                    self.hovered = false;
4143                    set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
4144                    set_press_animation_target(&mut self.drag_animation, 0.0, &theme, ctx);
4145                    ctx.release_pointer_capture(pointer.pointer_id);
4146                    ctx.request_paint();
4147                    ctx.request_semantics();
4148                    ctx.set_handled();
4149                }
4150            }
4151            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
4152                let next = match &semantics.action {
4153                    SemanticsActionRequest::Increment => Some(self.value + self.step.max(0.01)),
4154                    SemanticsActionRequest::Decrement => Some(self.value - self.step.max(0.01)),
4155                    SemanticsActionRequest::SetValue(SemanticsValue::Number(value)) => Some(*value),
4156                    SemanticsActionRequest::SetValue(SemanticsValue::Range { value, .. }) => {
4157                        Some(*value)
4158                    }
4159                    _ => None,
4160                };
4161                let Some(next) = next.filter(|value| value.is_finite()) else {
4162                    return;
4163                };
4164                let clamped = clamp_and_snap_value(next, self.min, self.max, self.step);
4165                if (clamped - self.value).abs() > f64::EPSILON {
4166                    self.value = clamped;
4167                    self.emit_change(ctx);
4168                }
4169                ctx.request_paint();
4170                ctx.request_semantics();
4171                ctx.set_handled();
4172            }
4173            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
4174                let next = match key.key.as_str() {
4175                    "ArrowLeft" | "ArrowDown" => Some(self.value - self.step.max(0.01)),
4176                    "ArrowRight" | "ArrowUp" => Some(self.value + self.step.max(0.01)),
4177                    "Home" => Some(self.min),
4178                    "End" => Some(self.max),
4179                    _ => None,
4180                };
4181
4182                if let Some(next) = next {
4183                    let clamped = clamp_and_snap_value(next, self.min, self.max, self.step);
4184                    if (clamped - self.value).abs() > f64::EPSILON {
4185                        self.value = clamped;
4186                        self.emit_change(ctx);
4187                    }
4188                    ctx.request_paint();
4189                    ctx.request_semantics();
4190                    ctx.set_handled();
4191                }
4192            }
4193            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
4194                if self.advance_animations(*time) {
4195                    ctx.request_animation_frame();
4196                }
4197                ctx.request_paint();
4198            }
4199            _ => {}
4200        }
4201    }
4202
4203    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4204        self.sync_external_value();
4205        let theme = self.resolved_theme();
4206
4207        constraints.clamp(Size::new(
4208            theme.metrics.slider_min_width,
4209            default_form_control_height(&theme),
4210        ))
4211    }
4212
4213    fn paint(&self, ctx: &mut PaintCtx) {
4214        let theme = self.resolved_theme();
4215        let palette = theme.palette;
4216        let metrics = theme.metrics;
4217        let hover_progress = self.hover_animation.value;
4218        let drag_progress = self.drag_animation.value;
4219        let focus_progress = self.focus_animation.value;
4220        let value = self.resolved_value();
4221        let track = self.track_rect(ctx.bounds());
4222        let active = Rect::new(
4223            track.x(),
4224            track.y(),
4225            track.width() * self.fraction_for(value),
4226            track.height(),
4227        );
4228        let thumb = self.thumb_rect_for(ctx.bounds(), value);
4229
4230        draw_control_frame(
4231            ctx,
4232            ctx.bounds(),
4233            metrics.corner_radius,
4234            metrics,
4235            mix_color(
4236                mix_color(
4237                    palette.control,
4238                    palette.control_hover,
4239                    hover_progress.max(drag_progress),
4240                ),
4241                palette.surface_focus,
4242                focus_progress,
4243            ),
4244            mix_color(
4245                mix_color(palette.border, palette.border_hover, hover_progress),
4246                palette.border_focus,
4247                focus_progress,
4248            ),
4249            (focus_progress > 0.0).then_some(
4250                palette
4251                    .focus_ring
4252                    .with_alpha(palette.focus_ring.alpha * focus_progress),
4253            ),
4254        );
4255        ctx.fill(
4256            rounded_rect_path(track, track.height() * 0.5),
4257            palette.control_active,
4258        );
4259        ctx.fill(
4260            rounded_rect_path(active, track.height() * 0.5),
4261            palette.accent,
4262        );
4263        ctx.fill(
4264            Path::circle(rect_center(thumb), thumb.width() * 0.5),
4265            mix_color(
4266                mix_color(palette.accent, palette.accent_hover, hover_progress),
4267                palette.accent_pressed,
4268                drag_progress,
4269            ),
4270        );
4271        ctx.stroke(
4272            Path::circle(rect_center(thumb), (thumb.width() * 0.5) - 0.5),
4273            palette.accent_border,
4274            StrokeStyle::new(physical_pixels(ctx, metrics.border_width)),
4275        );
4276    }
4277
4278    fn semantics(&self, ctx: &mut SemanticsCtx) {
4279        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Slider, ctx.bounds());
4280        node.name = Some(self.name.clone());
4281        node.value = Some(SemanticsValue::Range {
4282            value: self.resolved_value(),
4283            min: self.min,
4284            max: self.max,
4285        });
4286        node.numeric_step = Some(self.step.max(0.01));
4287        node.state.focused = ctx.is_focused();
4288        node.state.hovered = self.hovered;
4289        node.actions = vec![
4290            SemanticsAction::Focus,
4291            SemanticsAction::Increment,
4292            SemanticsAction::Decrement,
4293            SemanticsAction::SetValue,
4294        ];
4295        ctx.push(node);
4296    }
4297
4298    fn accepts_focus(&self) -> bool {
4299        true
4300    }
4301
4302    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
4303        let theme = self.resolved_theme();
4304        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
4305        ctx.request_paint();
4306        ctx.request_semantics();
4307    }
4308}
4309
4310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4311enum NumberInputStepperPart {
4312    Increment,
4313    Decrement,
4314}
4315
4316pub struct NumberInput {
4317    theme: Box<DefaultTheme>,
4318    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
4319    name: String,
4320    value: f64,
4321    min: f64,
4322    max: f64,
4323    step: f64,
4324    precision: usize,
4325    buffer: String,
4326    hovered: bool,
4327    hovered_stepper: Option<NumberInputStepperPart>,
4328    pressed_stepper: Option<NumberInputStepperPart>,
4329    hover_animation: AnimatedScalar,
4330    stepper_hover_animation: AnimatedScalar,
4331    press_animation: AnimatedScalar,
4332    focus_animation: AnimatedScalar,
4333    editing: bool,
4334    value_reader: Option<Box<dyn Fn() -> f64>>,
4335    on_change: Option<Box<dyn FnMut(f64)>>,
4336}
4337
4338impl NumberInput {
4339    pub fn new(name: impl Into<String>) -> Self {
4340        let value = 0.0;
4341        Self {
4342            theme: Box::new(DefaultTheme::default()),
4343            theme_reader: None,
4344            name: name.into(),
4345            value,
4346            min: f64::NEG_INFINITY,
4347            max: f64::INFINITY,
4348            step: 1.0,
4349            precision: 2,
4350            buffer: format_number(value, 2),
4351            hovered: false,
4352            hovered_stepper: None,
4353            pressed_stepper: None,
4354            hover_animation: AnimatedScalar::new(0.0),
4355            stepper_hover_animation: AnimatedScalar::new(0.0),
4356            press_animation: AnimatedScalar::new(0.0),
4357            focus_animation: AnimatedScalar::new(0.0),
4358            editing: false,
4359            value_reader: None,
4360            on_change: None,
4361        }
4362    }
4363
4364    pub fn theme(mut self, theme: DefaultTheme) -> Self {
4365        self.theme = Box::new(theme);
4366        self.theme_reader = None;
4367        self
4368    }
4369
4370    pub fn theme_when<F>(mut self, theme: F) -> Self
4371    where
4372        F: Fn() -> DefaultTheme + 'static,
4373    {
4374        self.theme_reader = Some(Box::new(theme));
4375        self
4376    }
4377
4378    pub fn range(mut self, min: f64, max: f64) -> Self {
4379        self.min = min.min(max);
4380        self.max = max.max(min);
4381        self.value = clamp_and_snap_value(self.value, self.min, self.max, self.step);
4382        self.buffer = format_number(self.value, self.precision);
4383        self
4384    }
4385
4386    pub fn step(mut self, step: f64) -> Self {
4387        self.step = step.abs().max(f64::EPSILON);
4388        self.value = clamp_and_snap_value(self.value, self.min, self.max, self.step);
4389        self.buffer = format_number(self.value, self.precision);
4390        self
4391    }
4392
4393    pub fn precision(mut self, precision: usize) -> Self {
4394        self.precision = precision;
4395        self.buffer = format_number(self.value, self.precision);
4396        self
4397    }
4398
4399    pub fn value(mut self, value: f64) -> Self {
4400        self.value = clamp_and_snap_value(value, self.min, self.max, self.step);
4401        self.buffer = format_number(self.value, self.precision);
4402        self.value_reader = None;
4403        self
4404    }
4405
4406    pub fn value_when<F>(mut self, value: F) -> Self
4407    where
4408        F: Fn() -> f64 + 'static,
4409    {
4410        self.value_reader = Some(Box::new(value));
4411        self
4412    }
4413
4414    pub const fn current_value(&self) -> f64 {
4415        self.value
4416    }
4417
4418    pub fn on_change<F>(mut self, on_change: F) -> Self
4419    where
4420        F: FnMut(f64) + 'static,
4421    {
4422        self.on_change = Some(Box::new(on_change));
4423        self
4424    }
4425
4426    fn resolved_theme(&self) -> DefaultTheme {
4427        self.theme_reader
4428            .as_ref()
4429            .map(|theme| theme())
4430            .unwrap_or(*self.theme)
4431    }
4432
4433    fn text_style(&self) -> TextStyle {
4434        numeric_text_style(self.resolved_theme().body_text_style())
4435    }
4436
4437    fn sync_external_value(&mut self) {
4438        if self.editing {
4439            return;
4440        }
4441        let Some(reader) = &self.value_reader else {
4442            return;
4443        };
4444        let next = clamp_and_snap_value(reader(), self.min, self.max, self.step);
4445        if (next - self.value).abs() > f64::EPSILON {
4446            self.value = next;
4447            self.buffer = format_number(self.value, self.precision);
4448        }
4449    }
4450
4451    fn resolved_value(&self) -> f64 {
4452        if !self.editing
4453            && let Some(reader) = &self.value_reader
4454        {
4455            return clamp_and_snap_value(reader(), self.min, self.max, self.step);
4456        }
4457
4458        self.value
4459    }
4460
4461    fn display_buffer(&self) -> String {
4462        if !self.editing && self.value_reader.is_some() {
4463            format_number(self.resolved_value(), self.precision)
4464        } else {
4465            self.buffer.clone()
4466        }
4467    }
4468
4469    fn commit_buffer(&mut self) {
4470        if let Ok(parsed) = self.buffer.trim().parse::<f64>() {
4471            let next = clamp_and_snap_value(parsed, self.min, self.max, self.step);
4472            if (next - self.value).abs() > f64::EPSILON {
4473                self.value = next;
4474                if let Some(on_change) = &mut self.on_change {
4475                    on_change(self.value);
4476                }
4477            }
4478            self.buffer = format_number(self.value, self.precision);
4479        }
4480    }
4481
4482    fn apply_edit_buffer(&mut self) {
4483        let Ok(parsed) = self.buffer.trim().parse::<f64>() else {
4484            return;
4485        };
4486        if !parsed.is_finite() || parsed < self.min || parsed > self.max {
4487            return;
4488        }
4489        if (parsed - self.value).abs() > f64::EPSILON {
4490            self.value = parsed;
4491            if let Some(on_change) = &mut self.on_change {
4492                on_change(self.value);
4493            }
4494        }
4495    }
4496
4497    fn nudge(&mut self, delta: f64) {
4498        let next = clamp_and_snap_value(self.value + delta, self.min, self.max, self.step);
4499        if (next - self.value).abs() > f64::EPSILON {
4500            self.value = next;
4501            self.buffer = format_number(self.value, self.precision);
4502            if let Some(on_change) = &mut self.on_change {
4503                on_change(self.value);
4504            }
4505        }
4506    }
4507
4508    fn set_hover_state(
4509        &mut self,
4510        hovered: bool,
4511        hovered_stepper: Option<NumberInputStepperPart>,
4512        ctx: &mut EventCtx,
4513    ) {
4514        if self.hovered != hovered || self.hovered_stepper != hovered_stepper {
4515            let theme = self.resolved_theme();
4516            self.hovered = hovered;
4517            self.hovered_stepper = hovered_stepper;
4518            set_hover_animation_target(
4519                &mut self.hover_animation,
4520                hovered as u8 as f32,
4521                &theme,
4522                ctx,
4523            );
4524            set_hover_animation_target(
4525                &mut self.stepper_hover_animation,
4526                hovered_stepper.is_some() as u8 as f32,
4527                &theme,
4528                ctx,
4529            );
4530            ctx.request_paint();
4531            ctx.request_semantics();
4532        }
4533    }
4534
4535    fn set_pressed_stepper(
4536        &mut self,
4537        pressed_stepper: Option<NumberInputStepperPart>,
4538        ctx: &mut EventCtx,
4539    ) {
4540        if self.pressed_stepper != pressed_stepper {
4541            let theme = self.resolved_theme();
4542            self.pressed_stepper = pressed_stepper;
4543            set_press_animation_target(
4544                &mut self.press_animation,
4545                pressed_stepper.is_some() as u8 as f32,
4546                &theme,
4547                ctx,
4548            );
4549            ctx.request_paint();
4550            ctx.request_semantics();
4551        }
4552    }
4553
4554    fn advance_animations(&mut self, time: f64) -> bool {
4555        self.hover_animation.advance(time)
4556            | self.stepper_hover_animation.advance(time)
4557            | self.press_animation.advance(time)
4558            | self.focus_animation.advance(time)
4559    }
4560}
4561
4562impl Widget for NumberInput {
4563    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4564        self.sync_external_value();
4565        match event {
4566            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
4567                let theme = self.resolved_theme();
4568                self.set_hover_state(
4569                    ctx.bounds().contains(pointer.position),
4570                    number_input_stepper_part(ctx.bounds(), theme.metrics, pointer.position),
4571                    ctx,
4572                );
4573            }
4574            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Enter) => {
4575                let theme = self.resolved_theme();
4576                self.set_hover_state(
4577                    ctx.bounds().contains(pointer.position),
4578                    number_input_stepper_part(ctx.bounds(), theme.metrics, pointer.position),
4579                    ctx,
4580                );
4581            }
4582            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
4583                self.set_hover_state(false, None, ctx);
4584            }
4585            Event::Pointer(pointer)
4586                if pointer.kind == PointerEventKind::Down
4587                    && pointer.button == Some(PointerButton::Primary) =>
4588            {
4589                let theme = self.resolved_theme();
4590                let stepper_part =
4591                    number_input_stepper_part(ctx.bounds(), theme.metrics, pointer.position);
4592                self.set_hover_state(ctx.bounds().contains(pointer.position), stepper_part, ctx);
4593                self.set_pressed_stepper(stepper_part, ctx);
4594                ctx.request_focus();
4595                ctx.request_pointer_capture(pointer.pointer_id);
4596                match stepper_part {
4597                    Some(NumberInputStepperPart::Increment) => self.nudge(self.step),
4598                    Some(NumberInputStepperPart::Decrement) => self.nudge(-self.step),
4599                    None => {}
4600                }
4601                ctx.request_paint();
4602                ctx.request_semantics();
4603                ctx.set_handled();
4604            }
4605            Event::Pointer(pointer)
4606                if pointer.kind == PointerEventKind::Up
4607                    && pointer.button == Some(PointerButton::Primary) =>
4608            {
4609                let theme = self.resolved_theme();
4610                self.set_hover_state(
4611                    ctx.bounds().contains(pointer.position),
4612                    number_input_stepper_part(ctx.bounds(), theme.metrics, pointer.position),
4613                    ctx,
4614                );
4615                self.set_pressed_stepper(None, ctx);
4616                ctx.release_pointer_capture(pointer.pointer_id);
4617                ctx.request_paint();
4618                ctx.request_semantics();
4619                ctx.set_handled();
4620            }
4621            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
4622                if self.pressed_stepper.is_some() {
4623                    self.set_pressed_stepper(None, ctx);
4624                    ctx.release_pointer_capture(pointer.pointer_id);
4625                    ctx.request_paint();
4626                    ctx.request_semantics();
4627                    ctx.set_handled();
4628                }
4629            }
4630            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
4631                let next = match &semantics.action {
4632                    SemanticsActionRequest::Increment => Some(self.value + self.step),
4633                    SemanticsActionRequest::Decrement => Some(self.value - self.step),
4634                    SemanticsActionRequest::SetValue(SemanticsValue::Number(value)) => Some(*value),
4635                    SemanticsActionRequest::SetValue(SemanticsValue::Range { value, .. }) => {
4636                        Some(*value)
4637                    }
4638                    _ => None,
4639                };
4640                let Some(next) = next.filter(|value| value.is_finite()) else {
4641                    return;
4642                };
4643                let next = clamp_and_snap_value(next, self.min, self.max, self.step);
4644                if (next - self.value).abs() > f64::EPSILON {
4645                    self.value = next;
4646                    self.buffer = format_number(self.value, self.precision);
4647                    if let Some(on_change) = &mut self.on_change {
4648                        on_change(self.value);
4649                    }
4650                }
4651                ctx.request_measure();
4652                ctx.request_paint();
4653                ctx.request_semantics();
4654                ctx.set_handled();
4655            }
4656            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
4657                match key.key.as_str() {
4658                    "ArrowUp" => self.nudge(self.step),
4659                    "ArrowDown" => self.nudge(-self.step),
4660                    "Enter" => self.commit_buffer(),
4661                    "Escape" => self.buffer = format_number(self.value, self.precision),
4662                    "Backspace" => {
4663                        self.buffer.pop();
4664                        self.apply_edit_buffer();
4665                    }
4666                    _ => {
4667                        if let Some(text) = keyboard_text(key)
4668                            && text.chars().all(is_numeric_input_char)
4669                        {
4670                            self.buffer.push_str(text);
4671                            self.apply_edit_buffer();
4672                        }
4673                    }
4674                }
4675                ctx.request_measure();
4676                ctx.request_paint();
4677                ctx.request_semantics();
4678                ctx.set_handled();
4679            }
4680            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
4681                let previous_hover = self.hover_animation.value;
4682                let previous_stepper_hover = self.stepper_hover_animation.value;
4683                let previous_press = self.press_animation.value;
4684                let previous_focus = self.focus_animation.value;
4685                let animating = self.advance_animations(*time);
4686                let changed = self.hover_animation.changed_since(previous_hover)
4687                    || self
4688                        .stepper_hover_animation
4689                        .changed_since(previous_stepper_hover)
4690                    || self.press_animation.changed_since(previous_press)
4691                    || self.focus_animation.changed_since(previous_focus);
4692                if changed {
4693                    ctx.request_paint();
4694                }
4695                if animating {
4696                    ctx.request_animation_frame();
4697                }
4698                ctx.set_handled();
4699            }
4700            _ => {}
4701        }
4702    }
4703
4704    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4705        self.sync_external_value();
4706        let buffer = self.display_buffer();
4707        let text_style = self.text_style();
4708        let measurement = measure_text(ctx, &buffer, &text_style);
4709        let theme = self.resolved_theme();
4710        let padding = theme.metrics.text_input_padding;
4711        let height =
4712            (measurement.height.max(text_style.line_height) + padding.top + padding.bottom)
4713                .max(theme.metrics.min_height);
4714        constraints.clamp(Size::new(
4715            (measurement.width
4716                + padding.left
4717                + padding.right
4718                + theme.metrics.number_input_stepper_width)
4719                .max(theme.metrics.button_min_width + 60.0),
4720            height,
4721        ))
4722    }
4723
4724    fn paint(&self, ctx: &mut PaintCtx) {
4725        let theme = self.resolved_theme();
4726        let palette = theme.palette;
4727        let metrics = theme.metrics;
4728        let interaction = theme.interaction;
4729        let content = number_input_text_rect(ctx.bounds(), metrics);
4730        let stepper = number_input_stepper_rect(ctx.bounds(), metrics);
4731        let text_style = self.text_style();
4732        let buffer = self.display_buffer();
4733        let hover_progress = self.hover_animation.value * interaction.hover_blend;
4734        let stepper_hover_progress = self.stepper_hover_animation.value * interaction.hover_blend;
4735        let press_progress = self.press_animation.value * interaction.pressed_blend;
4736        let focus_progress = self.focus_animation.value;
4737        let base_background = mix_color(palette.control, palette.control_hover, hover_progress);
4738
4739        draw_control_frame(
4740            ctx,
4741            ctx.bounds(),
4742            metrics.corner_radius,
4743            metrics,
4744            mix_color(base_background, palette.surface_focus, focus_progress),
4745            mix_color(
4746                mix_color(
4747                    palette.border,
4748                    palette.border_hover,
4749                    self.hover_animation.value,
4750                ),
4751                palette.border_focus,
4752                focus_progress,
4753            ),
4754            (focus_progress > 0.0).then_some(
4755                palette
4756                    .focus_ring
4757                    .with_alpha(palette.focus_ring.alpha * focus_progress),
4758            ),
4759        );
4760
4761        paint_aligned_text(
4762            ctx,
4763            content,
4764            &buffer,
4765            &text_style,
4766            text_style.line_height,
4767            1.0,
4768        );
4769        ctx.stroke(
4770            line_path(
4771                Point::new(stepper.x(), ctx.bounds().y() + 6.0),
4772                Point::new(stepper.x(), ctx.bounds().max_y() - 6.0),
4773            ),
4774            palette.border,
4775            StrokeStyle::new(physical_pixels(ctx, metrics.border_width)),
4776        );
4777        for (part, rect) in [
4778            (
4779                NumberInputStepperPart::Increment,
4780                Rect::new(
4781                    stepper.x(),
4782                    stepper.y(),
4783                    stepper.width(),
4784                    stepper.height() * 0.5,
4785                ),
4786            ),
4787            (
4788                NumberInputStepperPart::Decrement,
4789                Rect::new(
4790                    stepper.x(),
4791                    stepper.y() + (stepper.height() * 0.5),
4792                    stepper.width(),
4793                    stepper.height() * 0.5,
4794                ),
4795            ),
4796        ] {
4797            let hover_amount = if self.hovered_stepper == Some(part) {
4798                stepper_hover_progress
4799            } else {
4800                0.0
4801            };
4802            let press_amount = if self.pressed_stepper == Some(part) {
4803                press_progress
4804            } else {
4805                0.0
4806            };
4807            if hover_amount > 0.0 || press_amount > 0.0 {
4808                let fill = mix_color(
4809                    mix_color(palette.control, palette.control_hover, hover_amount),
4810                    palette.control_active,
4811                    press_amount,
4812                );
4813                ctx.fill(
4814                    rounded_rect_path(rect.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
4815                    fill,
4816                );
4817            }
4818        }
4819        let increment_offset = if self.pressed_stepper == Some(NumberInputStepperPart::Increment) {
4820            Vector::new(0.0, self.press_animation.value * interaction.pressed_offset)
4821        } else {
4822            Vector::ZERO
4823        };
4824        let decrement_offset = if self.pressed_stepper == Some(NumberInputStepperPart::Decrement) {
4825            Vector::new(0.0, self.press_animation.value * interaction.pressed_offset)
4826        } else {
4827            Vector::ZERO
4828        };
4829        draw_icon_glyph(
4830            ctx,
4831            IconGlyph::ChevronUp,
4832            Rect::new(
4833                stepper.x(),
4834                stepper.y(),
4835                stepper.width(),
4836                stepper.height() * 0.5,
4837            )
4838            .translate(increment_offset),
4839            palette.text,
4840        );
4841        draw_icon_glyph(
4842            ctx,
4843            IconGlyph::ChevronDown,
4844            Rect::new(
4845                stepper.x(),
4846                stepper.y() + (stepper.height() * 0.5),
4847                stepper.width(),
4848                stepper.height() * 0.5,
4849            )
4850            .translate(decrement_offset),
4851            palette.text,
4852        );
4853
4854        if ctx.is_focused() {
4855            let caret_x = content.max_x();
4856            let caret_width = physical_pixels(ctx, metrics.caret_width);
4857            let caret = Rect::new(
4858                caret_x.min((content.max_x() - caret_width).max(content.x())),
4859                content.y(),
4860                caret_width,
4861                content.height(),
4862            );
4863            ctx.set_ime_composition_rect(caret);
4864            ctx.fill(rounded_rect_path(caret, caret_width * 0.5), palette.caret);
4865        }
4866    }
4867
4868    fn semantics(&self, ctx: &mut SemanticsCtx) {
4869        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::SpinBox, ctx.bounds());
4870        node.name = Some(self.name.clone());
4871        node.value = Some(SemanticsValue::Range {
4872            value: self.resolved_value(),
4873            min: self.min,
4874            max: self.max,
4875        });
4876        node.numeric_step = Some(self.step);
4877        node.state.focused = ctx.is_focused();
4878        node.state.hovered = self.hovered;
4879        node.actions = vec![
4880            SemanticsAction::Focus,
4881            SemanticsAction::Increment,
4882            SemanticsAction::Decrement,
4883            SemanticsAction::SetValue,
4884        ];
4885        ctx.push(node);
4886    }
4887
4888    fn accepts_focus(&self) -> bool {
4889        true
4890    }
4891
4892    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
4893        if focused {
4894            self.sync_external_value();
4895        }
4896        self.editing = focused;
4897        if !focused {
4898            self.commit_buffer();
4899            self.sync_external_value();
4900        }
4901        let theme = self.resolved_theme();
4902        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
4903        ctx.request_paint();
4904        ctx.request_semantics();
4905    }
4906}
4907
4908pub struct TextArea {
4909    theme: Box<DefaultTheme>,
4910    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
4911    name: String,
4912    editor: EditableTextController,
4913    placeholder: String,
4914    read_only: bool,
4915    appearance: FieldAppearance,
4916    text_style: Option<TextStyle>,
4917    padding: Option<Insets>,
4918    min_width: Option<f32>,
4919    min_height: Option<f32>,
4920    hovered: bool,
4921    focused: bool,
4922    dragging_selection: bool,
4923    hover_animation: AnimatedScalar,
4924    focus_animation: AnimatedScalar,
4925    caret: CaretBlink,
4926    display_layout: Option<PersistentTextLayout>,
4927    input_layout: Option<PersistentTextLayout>,
4928    changes: TextChangeCallbacks,
4929    on_submit: Option<Box<dyn FnMut(&str)>>,
4930    on_focus_change: Option<Box<dyn FnMut(bool)>>,
4931}
4932
4933impl TextArea {
4934    pub fn new(name: impl Into<String>) -> Self {
4935        Self {
4936            theme: Box::new(DefaultTheme::default()),
4937            theme_reader: None,
4938            name: name.into(),
4939            editor: EditableTextController::new(),
4940            placeholder: String::new(),
4941            read_only: false,
4942            appearance: FieldAppearance::Framed,
4943            text_style: None,
4944            padding: None,
4945            min_width: None,
4946            min_height: None,
4947            hovered: false,
4948            focused: false,
4949            dragging_selection: false,
4950            hover_animation: AnimatedScalar::new(0.0),
4951            focus_animation: AnimatedScalar::new(0.0),
4952            caret: CaretBlink::new(CARET_BLINK_PERIOD_SECONDS),
4953            display_layout: None,
4954            input_layout: None,
4955            changes: TextChangeCallbacks::default(),
4956            on_submit: None,
4957            on_focus_change: None,
4958        }
4959    }
4960
4961    pub fn theme(mut self, theme: DefaultTheme) -> Self {
4962        self.theme = Box::new(theme);
4963        self.theme_reader = None;
4964        self
4965    }
4966
4967    pub fn theme_when<F>(mut self, theme: F) -> Self
4968    where
4969        F: Fn() -> DefaultTheme + 'static,
4970    {
4971        self.theme_reader = Some(Box::new(theme));
4972        self
4973    }
4974
4975    pub fn text_style(mut self, text_style: TextStyle) -> Self {
4976        self.text_style = Some(text_style);
4977        self
4978    }
4979
4980    pub fn appearance(mut self, appearance: FieldAppearance) -> Self {
4981        self.appearance = appearance;
4982        self
4983    }
4984
4985    pub fn bare(mut self) -> Self {
4986        self.appearance = FieldAppearance::Bare;
4987        self
4988    }
4989
4990    pub fn padding(mut self, padding: Insets) -> Self {
4991        self.padding = Some(padding);
4992        self
4993    }
4994
4995    pub fn min_width(mut self, width: f32) -> Self {
4996        self.min_width = Some(width.max(0.0));
4997        self
4998    }
4999
5000    pub fn min_height(mut self, height: f32) -> Self {
5001        self.min_height = Some(height.max(0.0));
5002        self
5003    }
5004
5005    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
5006        self.placeholder = placeholder.into();
5007        self
5008    }
5009
5010    pub fn read_only(mut self) -> Self {
5011        self.read_only = true;
5012        self
5013    }
5014
5015    pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
5016        self.editor.selectable(selection_scope);
5017        self
5018    }
5019
5020    pub fn selection_scope(mut self, selection_scope: SelectionScope) -> Self {
5021        self.editor.selection_scope(selection_scope);
5022        self
5023    }
5024
5025    pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
5026        self.editor.clipboard_behavior(behavior);
5027        self
5028    }
5029
5030    pub fn copy_to_clipboard(self, enabled: bool) -> Self {
5031        self.clipboard_behavior(if enabled {
5032            SelectionClipboardBehavior::WidgetManaged
5033        } else {
5034            SelectionClipboardBehavior::AppManaged
5035        })
5036    }
5037
5038    pub fn value(mut self, value: impl Into<String>) -> Self {
5039        self.editor.set_text(value);
5040        self
5041    }
5042
5043    pub fn current_value(&self) -> &str {
5044        self.editor.document().text()
5045    }
5046
5047    pub fn set_value(&mut self, value: impl Into<String>) {
5048        self.editor.set_text(value);
5049    }
5050
5051    pub fn on_change<F>(mut self, on_change: F) -> Self
5052    where
5053        F: FnMut(String) + 'static,
5054    {
5055        self.changes.value = Some(Box::new(on_change));
5056        self
5057    }
5058
5059    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
5060    where
5061        F: FnMut(&mut EventCtx, String) + 'static,
5062    {
5063        self.changes.with_ctx = Some(Box::new(on_change));
5064        self
5065    }
5066
5067    /// Fire `on_submit(current_text)` when the user presses a plain `Enter` (no Shift/Ctrl/Meta
5068    /// modifier) while focused, *instead* of inserting a newline. `Shift+Enter` (and any modified
5069    /// Enter) still inserts a newline. When no `on_submit` is set, `Enter` inserts a newline as
5070    /// before, so this is fully backward-compatible.
5071    ///
5072    /// This turns the multi-line `TextArea` into a chat-style composer: Enter to send, Shift+Enter
5073    /// for a soft line break.
5074    pub fn on_submit<F>(mut self, on_submit: F) -> Self
5075    where
5076        F: FnMut(&str) + 'static,
5077    {
5078        self.on_submit = Some(Box::new(on_submit));
5079        self
5080    }
5081
5082    pub fn on_focus_change<F>(mut self, on_focus_change: F) -> Self
5083    where
5084        F: FnMut(bool) + 'static,
5085    {
5086        self.on_focus_change = Some(Box::new(on_focus_change));
5087        self
5088    }
5089
5090    fn input_text(&self) -> String {
5091        self.editor.display_text()
5092    }
5093
5094    fn display_text(&self) -> String {
5095        let input = self.input_text();
5096        if input.is_empty() {
5097            self.placeholder.clone()
5098        } else {
5099            input
5100        }
5101    }
5102
5103    fn resolved_text_style(&self) -> TextStyle {
5104        self.text_style
5105            .clone()
5106            .unwrap_or_else(|| self.resolved_theme().body_text_style())
5107    }
5108
5109    fn display_text_style(&self) -> TextStyle {
5110        let theme = self.resolved_theme();
5111        if self.input_text().is_empty() {
5112            theme.placeholder_text_style()
5113        } else if self.read_only {
5114            theme.text_style(theme.palette.text_muted)
5115        } else {
5116            self.resolved_text_style()
5117        }
5118    }
5119
5120    fn resolved_padding(&self) -> Insets {
5121        self.padding
5122            .unwrap_or(self.resolved_theme().metrics.text_input_padding)
5123    }
5124
5125    fn resolved_min_size(&self) -> Size {
5126        let theme = self.resolved_theme();
5127        Size::new(
5128            self.min_width.unwrap_or(theme.metrics.text_input_min_width),
5129            self.min_height
5130                .unwrap_or(theme.metrics.text_area_min_height),
5131        )
5132    }
5133
5134    fn resolved_theme(&self) -> DefaultTheme {
5135        self.theme_reader
5136            .as_ref()
5137            .map(|theme| theme())
5138            .unwrap_or(*self.theme)
5139    }
5140
5141    fn apply_editor_result(&mut self, ctx: &mut EventCtx, result: EditorCommandResult) {
5142        self.editor.apply_field_result(
5143            ctx,
5144            result,
5145            &mut self.changes,
5146            &mut self.caret,
5147            self.focused,
5148            self.read_only,
5149        );
5150    }
5151
5152    fn execute_editor_command(&mut self, ctx: &mut EventCtx, command: EditorCommand) {
5153        let result = self.editor.execute(command);
5154        self.apply_editor_result(ctx, result);
5155    }
5156
5157    /// Select the entire document.
5158    pub fn select_all(&mut self, ctx: &mut EventCtx) {
5159        self.apply_text_command(ctx, TextCommand::SelectAll);
5160    }
5161
5162    /// Copy the current selection to the clipboard. No-op when the selection
5163    /// is collapsed.
5164    pub fn copy(&mut self, ctx: &mut EventCtx) {
5165        self.apply_text_command(ctx, TextCommand::Copy);
5166    }
5167
5168    /// Copy the current selection to the clipboard and delete it. No-op when
5169    /// read-only or the selection is collapsed.
5170    pub fn cut(&mut self, ctx: &mut EventCtx) {
5171        self.apply_text_command(ctx, TextCommand::Cut);
5172    }
5173
5174    /// Replace the current selection with the clipboard text. No-op when
5175    /// read-only or the clipboard has no text.
5176    pub fn paste(&mut self, ctx: &mut EventCtx) {
5177        self.apply_text_command(ctx, TextCommand::Paste);
5178    }
5179
5180    /// Currently selected document text (empty when the selection is
5181    /// collapsed).
5182    pub fn selected_text(&self) -> &str {
5183        self.editor.selected_text()
5184    }
5185
5186    fn apply_text_command(&mut self, ctx: &mut EventCtx, command: TextCommand) {
5187        if let Some(command) = self.editor.text_command(
5188            ctx,
5189            command,
5190            self.read_only,
5191            EditableTextLineMode::MultiLine,
5192        ) {
5193            self.execute_editor_command(ctx, command);
5194        }
5195    }
5196
5197    fn text_offset_at_position(&self, bounds: Rect, position: Point) -> usize {
5198        let content = inset_rect(bounds, self.resolved_padding());
5199        self.input_layout
5200            .as_ref()
5201            .map(|layout| {
5202                layout
5203                    .hit_test_point(Point::new(
5204                        position.x - content.x(),
5205                        position.y - content.y(),
5206                    ))
5207                    .utf8_offset
5208            })
5209            .unwrap_or(self.editor.document().len())
5210    }
5211
5212    fn set_caret_from_position(
5213        &mut self,
5214        bounds: Rect,
5215        position: Point,
5216        extend: bool,
5217        ctx: &mut EventCtx,
5218    ) {
5219        let offset = self.text_offset_at_position(bounds, position);
5220        let command = if extend {
5221            EditorCommand::SetSelection {
5222                anchor: self.editor.selection().anchor.utf8_offset,
5223                focus: offset,
5224            }
5225        } else {
5226            EditorCommand::MoveTo {
5227                offset,
5228                extend: false,
5229            }
5230        };
5231        let result = self.editor.execute(command);
5232        self.apply_editor_result(ctx, result);
5233    }
5234
5235    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
5236        if self.hovered != hovered {
5237            let theme = self.resolved_theme();
5238            self.hovered = hovered;
5239            set_hover_animation_target(
5240                &mut self.hover_animation,
5241                hovered as u8 as f32,
5242                &theme,
5243                ctx,
5244            );
5245            ctx.request_paint();
5246            ctx.request_semantics();
5247        }
5248    }
5249}
5250
5251impl Widget for TextArea {
5252    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5253        match event {
5254            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
5255                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
5256                if self.dragging_selection
5257                    && ctx.phase() != EventPhase::Capture
5258                    && pointer.buttons.contains(PointerButton::Primary)
5259                {
5260                    let offset = self.text_offset_at_position(ctx.bounds(), pointer.position);
5261                    let anchor = self.editor.selection().anchor.utf8_offset;
5262                    let result = self.editor.execute(EditorCommand::SetSelection {
5263                        anchor,
5264                        focus: offset,
5265                    });
5266                    self.apply_editor_result(ctx, result);
5267                }
5268            }
5269            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
5270                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
5271            }
5272            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
5273                self.set_hovered(false, ctx);
5274            }
5275            Event::Pointer(pointer)
5276                if pointer.kind == PointerEventKind::Down
5277                    && pointer.button == Some(PointerButton::Primary) =>
5278            {
5279                self.set_hovered(true, ctx);
5280                if self.focused {
5281                    self.caret.reset(ctx, self.focused, self.read_only);
5282                }
5283                self.set_caret_from_position(
5284                    ctx.bounds(),
5285                    pointer.position,
5286                    pointer.modifiers.shift,
5287                    ctx,
5288                );
5289                self.dragging_selection = true;
5290                ctx.request_pointer_capture(pointer.pointer_id);
5291                ctx.request_focus();
5292                ctx.request_paint();
5293                ctx.request_semantics();
5294                ctx.set_handled();
5295            }
5296            Event::Pointer(pointer)
5297                if pointer.kind == PointerEventKind::Up
5298                    && pointer.button == Some(PointerButton::Primary)
5299                    && self.dragging_selection =>
5300            {
5301                self.dragging_selection = false;
5302                ctx.release_pointer_capture(pointer.pointer_id);
5303                ctx.set_handled();
5304            }
5305            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
5306                if self.dragging_selection {
5307                    self.dragging_selection = false;
5308                    ctx.release_pointer_capture(pointer.pointer_id);
5309                }
5310            }
5311            Event::Pointer(pointer)
5312                if pointer.kind == PointerEventKind::Down
5313                    && pointer.button == Some(PointerButton::Secondary)
5314                    && ctx.phase() != EventPhase::Capture
5315                    && ctx.bounds().contains(pointer.position) =>
5316            {
5317                // Focus on right-click (keeping the selection intact) so
5318                // follow-up clipboard commands land here. Deliberately not
5319                // handled: wrapping context menus react to the same press.
5320                self.set_hovered(true, ctx);
5321                if !ctx.is_focused() {
5322                    ctx.request_focus();
5323                    ctx.request_paint();
5324                    ctx.request_semantics();
5325                }
5326            }
5327            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
5328                if let Some(commands) = self.editor.semantics_commands(
5329                    ctx,
5330                    &semantics.action,
5331                    self.read_only,
5332                    EditableTextLineMode::MultiLine,
5333                ) {
5334                    for command in commands {
5335                        self.execute_editor_command(ctx, command);
5336                    }
5337                }
5338            }
5339            Event::Ime(ImeEvent::CompositionStart) if ctx.is_focused() => {
5340                if !self.read_only {
5341                    self.execute_editor_command(ctx, EditorCommand::StartComposition);
5342                }
5343            }
5344            Event::Ime(ImeEvent::CompositionUpdate { text, cursor_range }) if ctx.is_focused() => {
5345                if !self.read_only {
5346                    self.execute_editor_command(
5347                        ctx,
5348                        EditorCommand::UpdateComposition {
5349                            text: text.clone(),
5350                            cursor_range: cursor_range.clone(),
5351                        },
5352                    );
5353                }
5354            }
5355            Event::Ime(ImeEvent::CompositionCommit { text }) if ctx.is_focused() => {
5356                if !self.read_only {
5357                    self.execute_editor_command(
5358                        ctx,
5359                        EditorCommand::CommitComposition(text.clone()),
5360                    );
5361                }
5362            }
5363            Event::Ime(ImeEvent::CompositionEnd) if ctx.is_focused() => {
5364                if !self.read_only {
5365                    self.execute_editor_command(ctx, EditorCommand::EndComposition);
5366                }
5367            }
5368            Event::Keyboard(key)
5369                if key.state == KeyState::Pressed && ctx.is_focused() && key.key == "Enter" =>
5370            {
5371                // Chat-composer behavior (only when an `on_submit` is wired): a plain Enter (no
5372                // Shift/Ctrl/Meta) submits the current text and is consumed, while Shift+Enter (or
5373                // any modified Enter) inserts a newline as usual. With no `on_submit`, Enter always
5374                // inserts a newline (backward-compatible).
5375                let plain_enter =
5376                    !key.modifiers.shift && !key.modifiers.control && !key.modifiers.meta;
5377                if self.on_submit.is_some() && plain_enter {
5378                    let text = self.current_value().to_string();
5379                    if let Some(on_submit) = &mut self.on_submit {
5380                        on_submit(&text);
5381                    }
5382                    ctx.set_handled();
5383                } else if let Some(command) = self.editor.keyboard_command(
5384                    ctx,
5385                    key,
5386                    self.read_only,
5387                    EditableTextLineMode::MultiLine,
5388                ) {
5389                    self.execute_editor_command(ctx, command);
5390                }
5391            }
5392            Event::Keyboard(key) if key.state == KeyState::Pressed && ctx.is_focused() => {
5393                if let Some(command) = self.editor.keyboard_command(
5394                    ctx,
5395                    key,
5396                    self.read_only,
5397                    EditableTextLineMode::MultiLine,
5398                ) {
5399                    self.execute_editor_command(ctx, command);
5400                }
5401            }
5402            Event::Wake(sui_core::WakeEvent::Timer { token, .. }) if self.caret.matches(*token) => {
5403                self.caret.tick(ctx, self.focused);
5404            }
5405            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
5406                let previous_hover = self.hover_animation.value;
5407                let previous_focus = self.focus_animation.value;
5408                let animating =
5409                    self.hover_animation.advance(*time) | self.focus_animation.advance(*time);
5410                let changed = self.hover_animation.changed_since(previous_hover)
5411                    || self.focus_animation.changed_since(previous_focus);
5412                if animating {
5413                    ctx.request_animation_frame();
5414                }
5415                if changed {
5416                    ctx.request_paint();
5417                }
5418            }
5419            _ => {}
5420        }
5421    }
5422
5423    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
5424        let Some(command) = TextCommand::from_command(command) else {
5425            return;
5426        };
5427        if !ctx.is_focused() {
5428            ctx.request_focus();
5429        }
5430        self.apply_text_command(ctx, command);
5431    }
5432
5433    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5434        let text_style = self.resolved_text_style();
5435        let padding = self.resolved_padding();
5436        let min_size = self.resolved_min_size();
5437        let content_width = if constraints.max.width.is_finite() {
5438            (constraints.max.width - padding.left - padding.right).max(0.0)
5439        } else {
5440            (min_size.width - padding.left - padding.right).max(0.0)
5441        };
5442        let display_text = self.display_text();
5443        let input_text = self.input_text();
5444        let display_style = self.display_text_style();
5445        let display_min_height = display_style.line_height.max(1.0);
5446        let input_min_height = text_style.line_height.max(1.0);
5447        let display_box = Size::new(content_width.max(1.0), display_min_height);
5448        let input_box = Size::new(content_width.max(1.0), input_min_height);
5449
5450        let mut display_layout = ctx
5451            .layout()
5452            .shape_text_persistent(
5453                self.display_layout.as_ref().map(|layout| layout.handle()),
5454                display_text.clone(),
5455                display_box,
5456                display_style.clone(),
5457            )
5458            .ok();
5459        if let Some(required_height) = display_layout
5460            .as_ref()
5461            .map(|layout| layout.measurement().height.max(display_min_height).max(1.0))
5462            .filter(|height| *height > display_box.height + 0.01)
5463            && let Ok(layout) = ctx.layout().shape_text_persistent(
5464                self.display_layout.as_ref().map(|layout| layout.handle()),
5465                display_text,
5466                Size::new(content_width.max(1.0), required_height),
5467                display_style.clone(),
5468            )
5469        {
5470            display_layout = Some(layout);
5471        }
5472
5473        let mut input_layout = ctx
5474            .layout()
5475            .shape_text_persistent(
5476                self.input_layout.as_ref().map(|layout| layout.handle()),
5477                input_text.clone(),
5478                input_box,
5479                text_style.clone(),
5480            )
5481            .ok();
5482        if let Some(required_height) = input_layout
5483            .as_ref()
5484            .map(|layout| layout.measurement().height.max(input_min_height).max(1.0))
5485            .filter(|height| *height > input_box.height + 0.01)
5486            && let Ok(layout) = ctx.layout().shape_text_persistent(
5487                self.input_layout.as_ref().map(|layout| layout.handle()),
5488                input_text,
5489                Size::new(content_width.max(1.0), required_height),
5490                text_style.clone(),
5491            )
5492        {
5493            input_layout = Some(layout);
5494        }
5495
5496        let measured_height = display_layout
5497            .as_ref()
5498            .map(|layout| layout.measurement().height.max(display_style.line_height))
5499            .unwrap_or(display_style.line_height);
5500        self.display_layout = display_layout;
5501        self.input_layout = input_layout;
5502
5503        constraints.clamp(Size::new(
5504            min_size
5505                .width
5506                .max(content_width + padding.left + padding.right),
5507            min_size
5508                .height
5509                .max(measured_height + padding.top + padding.bottom),
5510        ))
5511    }
5512
5513    fn paint(&self, ctx: &mut PaintCtx) {
5514        let theme = self.resolved_theme();
5515        let palette = theme.palette;
5516        let metrics = theme.metrics;
5517        let padding = self.resolved_padding();
5518        let content = inset_rect(ctx.bounds(), padding);
5519        let focus_progress = self.focus_animation.value;
5520
5521        // Light fields lift from their slightly recessed rest fill to the
5522        // surface on hover. Focus then moves every scheme toward its soft
5523        // accent well; dark and Void keep their established resting depth.
5524        let background = field_background(
5525            &theme,
5526            self.read_only,
5527            self.hover_animation.value,
5528            focus_progress,
5529        );
5530        if self.appearance == FieldAppearance::Framed {
5531            draw_control_frame(
5532                ctx,
5533                ctx.bounds(),
5534                metrics.corner_radius,
5535                metrics,
5536                background,
5537                mix_color(
5538                    mix_color(
5539                        palette.border,
5540                        palette.border_hover,
5541                        self.hover_animation.value,
5542                    ),
5543                    palette.border_focus,
5544                    focus_progress,
5545                ),
5546                (focus_progress > 0.0).then_some(
5547                    palette
5548                        .focus_ring
5549                        .with_alpha(palette.focus_ring.alpha * focus_progress),
5550                ),
5551            );
5552        }
5553
5554        if let Some(layout) = &self.display_layout {
5555            ctx.push_clip_rect(content);
5556            let input_text = self.input_text();
5557            let selection = selection_range(&self.editor.display_selection(), input_text.len());
5558            if !selection.is_empty() {
5559                for rect in layout.selection_rects(selection) {
5560                    ctx.fill_rect(
5561                        rect.translate(content.origin.to_vector()),
5562                        palette.selection,
5563                    );
5564                }
5565            }
5566            ctx.draw_persistent_text_layout(content.origin, layout);
5567            ctx.pop_clip();
5568        }
5569
5570        if self.focused && !self.read_only {
5571            let text_style = self.resolved_text_style();
5572            let caret_width = physical_pixels(ctx, metrics.caret_width);
5573            let fallback_caret = Rect::new(
5574                content.x(),
5575                content.y(),
5576                caret_width,
5577                text_style.line_height.max(1.0),
5578            );
5579            let caret = self
5580                .input_layout
5581                .as_ref()
5582                .and_then(|layout| {
5583                    let caret = layout
5584                        .caret_rect(self.editor.display_selection().focus.utf8_offset)
5585                        .translate(content.origin.to_vector());
5586                    rect_is_finite(caret).then_some(caret)
5587                })
5588                .unwrap_or(fallback_caret);
5589            let caret = Rect::new(
5590                caret
5591                    .x()
5592                    .min((content.max_x() - caret_width).max(content.x()))
5593                    .max(content.x()),
5594                caret.y(),
5595                caret_width,
5596                caret.height().max(text_style.line_height).max(1.0),
5597            );
5598            ctx.set_ime_composition_rect(caret);
5599            if self.caret.visible {
5600                ctx.fill(rounded_rect_path(caret, caret_width * 0.5), palette.caret);
5601            }
5602        }
5603    }
5604
5605    fn semantics(&self, ctx: &mut SemanticsCtx) {
5606        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
5607        let display_text = self.input_text();
5608        let display_selection = self.editor.display_selection();
5609        let selection = selection_range(&display_selection, display_text.len());
5610        node.name = Some(self.name.clone());
5611        node.value = Some(SemanticsValue::Text(display_text));
5612        node.state.focused = ctx.is_focused();
5613        node.state.hovered = self.hovered;
5614        node.editable_text = Some(EditableTextSemantics {
5615            caret_offset: display_selection.focus.utf8_offset,
5616            selection: SemanticsTextRange::new(selection.start, selection.end),
5617            multiline: true,
5618            password: false,
5619            readonly: self.read_only,
5620            scroll_x: 0.0,
5621            scroll_y: 0.0,
5622        });
5623        node.actions = self.editor.semantic_actions(self.read_only);
5624        ctx.push(node);
5625    }
5626
5627    fn accepts_focus(&self) -> bool {
5628        true
5629    }
5630
5631    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
5632        self.focused = focused;
5633        if !focused {
5634            let result = self.editor.execute(EditorCommand::ClearComposition);
5635            if result.layout_changed() {
5636                ctx.request_measure();
5637            }
5638        }
5639        if focused {
5640            self.caret.reset(ctx, self.focused, self.read_only);
5641        } else {
5642            self.caret.stop(ctx);
5643        }
5644        let theme = self.resolved_theme();
5645        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
5646        if let Some(on_focus_change) = &mut self.on_focus_change {
5647            on_focus_change(focused);
5648        }
5649        ctx.request_paint();
5650        ctx.request_semantics();
5651    }
5652}
5653
5654#[derive(Debug, Clone)]
5655struct SelectMenuPresentationState {
5656    theme: DefaultTheme,
5657    options: Vec<String>,
5658    selected: Option<usize>,
5659    hovered: Option<usize>,
5660    hover_visual: Option<usize>,
5661    hover_animation: AnimatedScalar,
5662    placement: SelectMenuPlacement,
5663    menu_bounds: Rect,
5664    reveal: AnimatedScalar,
5665}
5666
5667impl SelectMenuPresentationState {
5668    fn new() -> Self {
5669        Self {
5670            theme: DefaultTheme::default(),
5671            options: Vec::new(),
5672            selected: None,
5673            hovered: None,
5674            hover_visual: None,
5675            hover_animation: AnimatedScalar::new(0.0),
5676            placement: SelectMenuPlacement::Below,
5677            menu_bounds: Rect::ZERO,
5678            reveal: AnimatedScalar::new(0.0),
5679        }
5680    }
5681
5682    fn is_presented(&self) -> bool {
5683        self.reveal.is_presented()
5684    }
5685
5686    fn row_height(&self) -> f32 {
5687        default_form_control_height(&self.theme)
5688    }
5689
5690    fn row_rect(&self, index: usize, bounds: Rect) -> Rect {
5691        Rect::new(
5692            bounds.x(),
5693            bounds.y() + (index as f32 * self.row_height()),
5694            bounds.width(),
5695            self.row_height(),
5696        )
5697    }
5698
5699    fn set_hovered(&mut self, hovered: Option<usize>, animate: bool, ctx: &mut EventCtx) -> bool {
5700        if self.hovered == hovered && self.hover_visual == hovered {
5701            return false;
5702        }
5703
5704        self.hovered = hovered;
5705        match hovered {
5706            Some(index) => {
5707                if self.hover_visual != Some(index) {
5708                    self.hover_visual = Some(index);
5709                    self.hover_animation = AnimatedScalar::new(0.0);
5710                }
5711                if animate {
5712                    set_hover_animation_target(&mut self.hover_animation, 1.0, &self.theme, ctx);
5713                } else {
5714                    self.hover_animation = AnimatedScalar::new(1.0);
5715                }
5716            }
5717            None => {
5718                if animate {
5719                    set_hover_animation_target(&mut self.hover_animation, 0.0, &self.theme, ctx);
5720                } else {
5721                    self.hover_animation = AnimatedScalar::new(0.0);
5722                    self.hover_visual = None;
5723                }
5724            }
5725        }
5726        true
5727    }
5728
5729    fn sync_hovered_without_animation(&mut self, hovered: Option<usize>) -> bool {
5730        if self.hovered == hovered && self.hover_visual == hovered {
5731            return false;
5732        }
5733        self.hovered = hovered;
5734        self.hover_visual = hovered;
5735        self.hover_animation = AnimatedScalar::new(hovered.is_some() as u8 as f32);
5736        true
5737    }
5738
5739    fn advance_hover(&mut self, time: f64) -> (bool, bool) {
5740        let previous = self.hover_animation.value;
5741        let active = self.hover_animation.advance(time);
5742        let changed = self.hover_animation.changed_since(previous);
5743        if self.hovered.is_none() && !self.hover_animation.is_presented() {
5744            self.hover_visual = None;
5745        }
5746        (changed, active)
5747    }
5748
5749    fn hover_progress_for(&self, index: usize) -> f32 {
5750        if self.hover_visual == Some(index) {
5751            self.hover_animation.value
5752        } else {
5753            0.0
5754        }
5755    }
5756
5757    fn layer_properties(&self) -> LayerProperties {
5758        let direction = match self.placement {
5759            SelectMenuPlacement::Below => -1.0,
5760            SelectMenuPlacement::Above => 1.0,
5761        };
5762        LayerProperties {
5763            opacity: self.reveal.value,
5764            translation: Vector::new(
5765                0.0,
5766                self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value) * direction,
5767            ),
5768        }
5769    }
5770}
5771
5772struct SelectMenuSurface {
5773    state: Rc<RefCell<SelectMenuPresentationState>>,
5774}
5775
5776impl SelectMenuSurface {
5777    fn new(state: Rc<RefCell<SelectMenuPresentationState>>) -> Self {
5778        Self { state }
5779    }
5780}
5781
5782impl Widget for SelectMenuSurface {
5783    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5784        match event {
5785            Event::Pointer(pointer)
5786                if matches!(
5787                    pointer.kind,
5788                    PointerEventKind::Move | PointerEventKind::Enter
5789                ) =>
5790            {
5791                let mut state = self.state.borrow_mut();
5792                let bounds = state.menu_bounds;
5793                let hovered = bounds.contains(pointer.position).then(|| {
5794                    state.options.iter().enumerate().find_map(|(index, _)| {
5795                        state
5796                            .row_rect(index, bounds)
5797                            .contains(pointer.position)
5798                            .then_some(index)
5799                    })
5800                });
5801                let changed = state.set_hovered(hovered.flatten(), true, ctx);
5802                drop(state);
5803                if changed {
5804                    ctx.request_paint();
5805                }
5806            }
5807            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
5808                let mut state = self.state.borrow_mut();
5809                let changed = state.set_hovered(None, true, ctx);
5810                drop(state);
5811                if changed {
5812                    ctx.request_paint();
5813                }
5814            }
5815            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
5816                let mut state = self.state.borrow_mut();
5817                let (changed, active) = state.advance_hover(*time);
5818                drop(state);
5819                if changed {
5820                    ctx.request_paint();
5821                }
5822                if active {
5823                    ctx.request_animation_frame();
5824                }
5825                ctx.set_handled();
5826            }
5827            _ => {}
5828        }
5829    }
5830
5831    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
5832        let state = self.state.borrow();
5833        if state.is_presented() {
5834            state.menu_bounds.size
5835        } else {
5836            Size::ZERO
5837        }
5838    }
5839
5840    fn paint(&self, ctx: &mut PaintCtx) {
5841        let state = self.state.borrow();
5842        if !state.is_presented() {
5843            return;
5844        }
5845
5846        let menu = ctx.bounds();
5847        let theme = state.theme;
5848        let metrics = theme.metrics;
5849        let palette = theme.palette;
5850        let menu_radius = metrics.corner_radius + 2.0;
5851        paint_theme_shadow(ctx, menu, [menu_radius; 4], &theme.shadows.box_shadow.md);
5852        draw_control_shape(
5853            ctx,
5854            menu,
5855            menu_radius,
5856            physical_pixels(ctx, metrics.border_width),
5857            palette.surface_raised,
5858            palette.border,
5859        );
5860        ctx.push_clip_rect(menu);
5861        for (index, option) in state.options.iter().enumerate() {
5862            let row = state.row_rect(index, menu);
5863            let selected = state.selected == Some(index);
5864            let hover_progress = state.hover_progress_for(index);
5865            let text_style = theme.body_text_style();
5866            if hover_progress > AnimatedScalar::EPSILON || selected {
5867                let background = if selected {
5868                    mix_color(
5869                        palette.selection,
5870                        palette.control_hover,
5871                        hover_progress * theme.interaction.hover_blend,
5872                    )
5873                } else {
5874                    mix_color(
5875                        palette.surface_raised,
5876                        palette.control_hover,
5877                        hover_progress,
5878                    )
5879                };
5880                ctx.fill(
5881                    rounded_rect_path(row.inflate(-4.0, -4.0), metrics.corner_radius - 2.0),
5882                    background,
5883                );
5884            }
5885            let text_slot = horizontal_text_inset_rect(row, metrics.text_input_padding);
5886            ctx.push_clip_rect(text_slot);
5887            paint_aligned_text(
5888                ctx,
5889                text_slot,
5890                option,
5891                &text_style,
5892                text_style.line_height,
5893                0.0,
5894            );
5895            ctx.pop_clip();
5896        }
5897        ctx.pop_clip();
5898    }
5899
5900    fn layer_options(&self) -> LayerOptions {
5901        let presented = self.state.borrow().is_presented();
5902        LayerOptions {
5903            paint_boundary: PaintBoundaryMode::Explicit,
5904            composition_mode: if presented {
5905                LayerCompositionMode::Overlay
5906            } else {
5907                LayerCompositionMode::Normal
5908            },
5909        }
5910    }
5911
5912    fn layer_properties(&self) -> LayerProperties {
5913        self.state.borrow().layer_properties()
5914    }
5915
5916    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
5917        self.state
5918            .borrow()
5919            .is_presented()
5920            .then_some(StackSurfaceOptions {
5921                transient: true,
5922                ..StackSurfaceOptions::default()
5923            })
5924    }
5925}
5926
5927pub struct Select {
5928    theme: Box<DefaultTheme>,
5929    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5930    name: String,
5931    options: Vec<String>,
5932    selected: Option<usize>,
5933    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
5934    placeholder: String,
5935    expanded: bool,
5936    hovered_option: Option<usize>,
5937    hovered_header: bool,
5938    pressed_header: bool,
5939    hover_animation: AnimatedScalar,
5940    press_animation: AnimatedScalar,
5941    focus_animation: AnimatedScalar,
5942    menu_surface: SingleChild,
5943    menu_state: Rc<RefCell<SelectMenuPresentationState>>,
5944    on_change: Option<Box<dyn FnMut(usize, String)>>,
5945    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String)>>,
5946}
5947
5948impl Select {
5949    pub fn new(name: impl Into<String>) -> Self {
5950        let menu_state = Rc::new(RefCell::new(SelectMenuPresentationState::new()));
5951        Self {
5952            theme: Box::new(DefaultTheme::default()),
5953            theme_reader: None,
5954            name: name.into(),
5955            options: Vec::new(),
5956            selected: None,
5957            selected_reader: None,
5958            placeholder: String::new(),
5959            expanded: false,
5960            hovered_option: None,
5961            hovered_header: false,
5962            pressed_header: false,
5963            hover_animation: AnimatedScalar::new(0.0),
5964            press_animation: AnimatedScalar::new(0.0),
5965            focus_animation: AnimatedScalar::new(0.0),
5966            menu_surface: SingleChild::new(SelectMenuSurface::new(Rc::clone(&menu_state))),
5967            menu_state,
5968            on_change: None,
5969            on_change_with_ctx: None,
5970        }
5971    }
5972
5973    pub fn theme(mut self, theme: DefaultTheme) -> Self {
5974        self.theme = Box::new(theme);
5975        self.theme_reader = None;
5976        self
5977    }
5978
5979    pub fn theme_when<F>(mut self, theme: F) -> Self
5980    where
5981        F: Fn() -> DefaultTheme + 'static,
5982    {
5983        self.theme_reader = Some(Box::new(theme));
5984        self
5985    }
5986
5987    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
5988        self.placeholder = placeholder.into();
5989        self
5990    }
5991
5992    pub fn option(mut self, option: impl Into<String>) -> Self {
5993        self.options.push(option.into());
5994        self
5995    }
5996
5997    pub fn options<I, S>(mut self, options: I) -> Self
5998    where
5999        I: IntoIterator<Item = S>,
6000        S: Into<String>,
6001    {
6002        self.options.extend(options.into_iter().map(Into::into));
6003        self
6004    }
6005
6006    pub fn selected(mut self, index: usize) -> Self {
6007        self.selected = Some(index);
6008        self.selected_reader = None;
6009        self
6010    }
6011
6012    pub fn expanded(mut self, expanded: bool) -> Self {
6013        self.expanded = expanded;
6014        if expanded {
6015            self.hovered_option = self.current_selected_index().or(Some(0));
6016        } else {
6017            self.hovered_option = None;
6018        }
6019        self.menu_state.borrow_mut().reveal = AnimatedScalar::new(expanded as u8 as f32);
6020        self
6021    }
6022
6023    pub fn selected_when<F>(mut self, selected: F) -> Self
6024    where
6025        F: Fn() -> Option<usize> + 'static,
6026    {
6027        self.selected_reader = Some(Box::new(selected));
6028        self
6029    }
6030
6031    pub const fn selected_index(&self) -> Option<usize> {
6032        self.selected
6033    }
6034
6035    pub fn current_value(&self) -> Option<&str> {
6036        self.current_selected_index()
6037            .and_then(|index| self.options.get(index).map(String::as_str))
6038    }
6039
6040    pub fn on_change<F>(mut self, on_change: F) -> Self
6041    where
6042        F: FnMut(usize, String) + 'static,
6043    {
6044        self.on_change = Some(Box::new(on_change));
6045        self
6046    }
6047
6048    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
6049    where
6050        F: FnMut(&mut EventCtx, usize, String) + 'static,
6051    {
6052        self.on_change_with_ctx = Some(Box::new(on_change));
6053        self
6054    }
6055
6056    fn resolved_theme(&self) -> DefaultTheme {
6057        self.theme_reader
6058            .as_ref()
6059            .map(|theme| theme())
6060            .unwrap_or(*self.theme)
6061    }
6062
6063    fn header_height(&self) -> f32 {
6064        default_form_control_height(&self.resolved_theme())
6065    }
6066
6067    fn current_label(&self) -> String {
6068        self.current_value()
6069            .map(str::to_string)
6070            .unwrap_or_else(|| self.placeholder.clone())
6071    }
6072
6073    fn current_selected_index(&self) -> Option<usize> {
6074        self.selected_reader
6075            .as_ref()
6076            .map(|reader| reader())
6077            .unwrap_or(self.selected)
6078            .filter(|index| *index < self.options.len())
6079    }
6080
6081    fn header_rect(&self, bounds: Rect) -> Rect {
6082        let height = self.header_height().min(bounds.height()).max(0.0);
6083        Rect::new(
6084            bounds.x(),
6085            bounds.y() + ((bounds.height() - height) * 0.5).max(0.0),
6086            bounds.width(),
6087            height,
6088        )
6089    }
6090
6091    fn menu_height(&self) -> f32 {
6092        (self.options.len() as f32 * self.header_height())
6093            .min(self.resolved_theme().metrics.select_menu_max_height)
6094    }
6095
6096    fn menu_layout(&self, bounds: Rect, viewport: Size) -> (SelectMenuPlacement, Rect) {
6097        let theme = self.resolved_theme();
6098        let viewport = if viewport.width.is_finite()
6099            && viewport.height.is_finite()
6100            && viewport.width > 0.0
6101            && viewport.height > 0.0
6102        {
6103            Rect::from_origin_size(Point::ZERO, viewport)
6104        } else {
6105            Rect::new(0.0, 0.0, f32::MAX / 4.0, f32::MAX / 4.0)
6106        };
6107        let result = place_overlay(
6108            &OverlayPlacementRequest::new(
6109                self.header_rect(bounds),
6110                Size::new(bounds.width(), self.menu_height()),
6111                viewport,
6112                OverlayPlacement::BOTTOM_START,
6113            )
6114            .fallbacks([OverlayPlacement::TOP_START])
6115            .gap(theme.metrics.select_menu_gap)
6116            .margin(theme.metrics.select_menu_edge_padding),
6117        );
6118        let placement = if result.placement == OverlayPlacement::TOP_START {
6119            SelectMenuPlacement::Above
6120        } else {
6121            SelectMenuPlacement::Below
6122        };
6123        (placement, result.bounds)
6124    }
6125
6126    fn menu_placement(&self, bounds: Rect, viewport: Size) -> SelectMenuPlacement {
6127        self.menu_layout(bounds, viewport).0
6128    }
6129
6130    fn menu_rect(&self, bounds: Rect, viewport: Size) -> Rect {
6131        self.menu_layout(bounds, viewport).1
6132    }
6133
6134    fn option_rect(&self, bounds: Rect, viewport: Size, index: usize) -> Rect {
6135        let menu = self.menu_rect(bounds, viewport);
6136        Rect::new(
6137            menu.x(),
6138            menu.y() + (index as f32 * self.header_height()),
6139            menu.width(),
6140            self.header_height(),
6141        )
6142    }
6143
6144    fn option_at(&self, bounds: Rect, viewport: Size, position: Point) -> Option<usize> {
6145        if !self.expanded {
6146            return None;
6147        }
6148
6149        let menu = self.menu_rect(bounds, viewport);
6150        if !menu.contains(position) {
6151            return None;
6152        }
6153
6154        self.options.iter().enumerate().find_map(|(index, _)| {
6155            self.option_rect(bounds, viewport, index)
6156                .contains(position)
6157                .then_some(index)
6158        })
6159    }
6160
6161    fn select_index(&mut self, ctx: &mut EventCtx, index: usize) {
6162        if self.options.is_empty() {
6163            return;
6164        }
6165        let index = index.min(self.options.len().saturating_sub(1));
6166        self.selected = Some(index);
6167        let value = self.options[index].clone();
6168        if let Some(on_change) = &mut self.on_change {
6169            on_change(index, value.clone());
6170        }
6171        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
6172            on_change_with_ctx(ctx, index, value);
6173        }
6174        self.refresh_menu_interaction_state(ctx);
6175    }
6176
6177    fn sync_menu_state(&self, bounds: Rect, viewport: Size) {
6178        let mut state = self.menu_state.borrow_mut();
6179        state.theme = self.resolved_theme();
6180        state.options = self.options.clone();
6181        state.selected = self.current_selected_index();
6182        if state.hovered != self.hovered_option {
6183            state.sync_hovered_without_animation(self.hovered_option);
6184        }
6185        state.placement = self.menu_placement(bounds, viewport);
6186        state.menu_bounds = self.menu_rect(bounds, viewport);
6187    }
6188
6189    fn refresh_menu_interaction_state(&self, ctx: &mut EventCtx) {
6190        let selected = self.current_selected_index();
6191        let hovered = self.hovered_option;
6192        let surface_id = self.menu_surface.child().id();
6193        let mut state = self.menu_state.borrow_mut();
6194        let selected_changed = state.selected != selected;
6195        state.selected = selected;
6196        let hover_changed = state.set_hovered(hovered, true, ctx);
6197        let changed = selected_changed || hover_changed;
6198        let presented = state.is_presented();
6199        drop(state);
6200
6201        if changed && presented {
6202            request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
6203        }
6204    }
6205
6206    fn set_expanded(&mut self, ctx: &mut EventCtx, expanded: bool) {
6207        if self.expanded == expanded {
6208            return;
6209        }
6210
6211        self.expanded = expanded;
6212        self.hovered_option = if expanded {
6213            self.current_selected_index().or(Some(0))
6214        } else {
6215            None
6216        };
6217
6218        let surface_id = self.menu_surface.child().id();
6219        let theme = self.resolved_theme();
6220        let mut state = self.menu_state.borrow_mut();
6221        state.theme = theme;
6222        let was_presented = state.is_presented();
6223        state.sync_hovered_without_animation(self.hovered_option);
6224        let should_animate = if expanded {
6225            let motion = theme.motion;
6226            state.reveal.set_target(
6227                1.0,
6228                ctx.current_time(),
6229                motion.entrance_duration(),
6230                motion.entrance_easing(),
6231            )
6232        } else {
6233            state.reveal = AnimatedScalar::new(0.0);
6234            false
6235        };
6236        let is_presented = state.is_presented();
6237        drop(state);
6238
6239        if expanded || was_presented != is_presented {
6240            ctx.request_measure();
6241            request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
6242        }
6243        if should_animate {
6244            ctx.request_animation_frame();
6245        }
6246        ctx.request_paint();
6247        ctx.request_semantics();
6248    }
6249
6250    fn set_hover_state(
6251        &mut self,
6252        hovered_header: bool,
6253        hovered_option: Option<usize>,
6254        ctx: &mut EventCtx,
6255    ) {
6256        if self.hovered_header != hovered_header || self.hovered_option != hovered_option {
6257            let theme = self.resolved_theme();
6258            self.hovered_header = hovered_header;
6259            self.hovered_option = hovered_option;
6260            set_hover_animation_target(
6261                &mut self.hover_animation,
6262                hovered_header as u8 as f32,
6263                &theme,
6264                ctx,
6265            );
6266            let surface_id = self.menu_surface.child().id();
6267            let mut state = self.menu_state.borrow_mut();
6268            state.theme = theme;
6269            state.set_hovered(hovered_option, true, ctx);
6270            let presented = state.is_presented();
6271            drop(state);
6272            if presented {
6273                request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
6274            }
6275            ctx.request_paint();
6276            ctx.request_semantics();
6277        }
6278    }
6279
6280    fn set_pressed_header(&mut self, pressed: bool, ctx: &mut EventCtx) {
6281        if self.pressed_header != pressed {
6282            let theme = self.resolved_theme();
6283            self.pressed_header = pressed;
6284            set_press_animation_target(
6285                &mut self.press_animation,
6286                pressed as u8 as f32,
6287                &theme,
6288                ctx,
6289            );
6290            ctx.request_paint();
6291            ctx.request_semantics();
6292        }
6293    }
6294
6295    fn advance_header_animations(&mut self, time: f64) -> (bool, bool) {
6296        let previous_hover = self.hover_animation.value;
6297        let previous_press = self.press_animation.value;
6298        let previous_focus = self.focus_animation.value;
6299        let animating = self.hover_animation.advance(time)
6300            | self.press_animation.advance(time)
6301            | self.focus_animation.advance(time);
6302        let changed = self.hover_animation.changed_since(previous_hover)
6303            || self.press_animation.changed_since(previous_press)
6304            || self.focus_animation.changed_since(previous_focus);
6305        (changed, animating)
6306    }
6307}
6308
6309impl Widget for Select {
6310    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
6311        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.expanded {
6312            self.set_expanded(ctx, false);
6313            ctx.set_handled();
6314        }
6315    }
6316
6317    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6318        match event {
6319            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
6320                self.set_hover_state(
6321                    self.header_rect(ctx.bounds()).contains(pointer.position),
6322                    self.option_at(ctx.bounds(), ctx.dpi().viewport, pointer.position),
6323                    ctx,
6324                );
6325            }
6326            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Enter) => {
6327                self.set_hover_state(
6328                    self.header_rect(ctx.bounds()).contains(pointer.position),
6329                    self.option_at(ctx.bounds(), ctx.dpi().viewport, pointer.position),
6330                    ctx,
6331                );
6332            }
6333            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Leave) => {
6334                self.set_hover_state(
6335                    false,
6336                    self.option_at(ctx.bounds(), ctx.dpi().viewport, pointer.position),
6337                    ctx,
6338                );
6339            }
6340            Event::Pointer(pointer)
6341                if pointer.kind == PointerEventKind::Down
6342                    && pointer.button == Some(PointerButton::Primary) =>
6343            {
6344                let hovered_header = self.header_rect(ctx.bounds()).contains(pointer.position);
6345                let hovered_option =
6346                    self.option_at(ctx.bounds(), ctx.dpi().viewport, pointer.position);
6347                self.set_hover_state(hovered_header, hovered_option, ctx);
6348                self.set_pressed_header(hovered_header, ctx);
6349                ctx.request_focus();
6350                ctx.request_pointer_capture(pointer.pointer_id);
6351                ctx.request_paint();
6352                ctx.request_semantics();
6353                ctx.set_handled();
6354            }
6355            Event::Pointer(pointer)
6356                if pointer.kind == PointerEventKind::Up
6357                    && pointer.button == Some(PointerButton::Primary) =>
6358            {
6359                let hovered_header = self.header_rect(ctx.bounds()).contains(pointer.position);
6360                let hovered_option =
6361                    self.option_at(ctx.bounds(), ctx.dpi().viewport, pointer.position);
6362                let was_pressed_header = self.pressed_header;
6363
6364                if was_pressed_header && hovered_header {
6365                    self.set_expanded(ctx, !self.expanded);
6366                } else if let Some(index) = hovered_option {
6367                    self.select_index(ctx, index);
6368                    self.set_expanded(ctx, false);
6369                } else {
6370                    self.set_expanded(ctx, false);
6371                }
6372
6373                self.set_pressed_header(false, ctx);
6374                self.set_hover_state(
6375                    hovered_header,
6376                    if self.expanded {
6377                        self.hovered_option
6378                    } else {
6379                        None
6380                    },
6381                    ctx,
6382                );
6383                ctx.release_pointer_capture(pointer.pointer_id);
6384                ctx.request_paint();
6385                ctx.request_semantics();
6386                ctx.set_handled();
6387            }
6388            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
6389                if self.pressed_header {
6390                    self.set_pressed_header(false, ctx);
6391                    self.set_hover_state(false, None, ctx);
6392                    ctx.release_pointer_capture(pointer.pointer_id);
6393                    ctx.request_paint();
6394                    ctx.request_semantics();
6395                    ctx.set_handled();
6396                }
6397            }
6398            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
6399                if self.options.is_empty() {
6400                    return;
6401                }
6402
6403                match key.key.as_str() {
6404                    "Enter" | " " => {
6405                        if self.expanded {
6406                            if let Some(index) = self
6407                                .hovered_option
6408                                .or_else(|| self.current_selected_index())
6409                            {
6410                                self.select_index(ctx, index);
6411                            }
6412                            self.set_expanded(ctx, false);
6413                        } else {
6414                            self.set_expanded(ctx, true);
6415                        }
6416                    }
6417                    "Escape" => self.set_expanded(ctx, false),
6418                    "ArrowDown" => {
6419                        if self.expanded {
6420                            let next = self
6421                                .hovered_option
6422                                .unwrap_or_else(|| self.current_selected_index().unwrap_or(0))
6423                                .saturating_add(1)
6424                                .min(self.options.len() - 1);
6425                            self.set_hover_state(self.hovered_header, Some(next), ctx);
6426                        } else {
6427                            let next = self
6428                                .current_selected_index()
6429                                .unwrap_or(0)
6430                                .saturating_add(1)
6431                                .min(self.options.len() - 1);
6432                            self.select_index(ctx, next);
6433                        }
6434                    }
6435                    "ArrowUp" => {
6436                        if self.expanded {
6437                            let next = self
6438                                .hovered_option
6439                                .unwrap_or_else(|| self.current_selected_index().unwrap_or(0))
6440                                .saturating_sub(1);
6441                            self.set_hover_state(self.hovered_header, Some(next), ctx);
6442                        } else {
6443                            let next = self.current_selected_index().unwrap_or(0).saturating_sub(1);
6444                            self.select_index(ctx, next);
6445                        }
6446                    }
6447                    "Home" => self.select_index(ctx, 0),
6448                    "End" => self.select_index(ctx, self.options.len() - 1),
6449                    _ => {}
6450                }
6451
6452                self.refresh_menu_interaction_state(ctx);
6453                ctx.request_paint();
6454                ctx.request_semantics();
6455                ctx.set_handled();
6456            }
6457            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
6458                let (header_changed, header_animating) = self.advance_header_animations(*time);
6459                let surface_id = self.menu_surface.child().id();
6460                let mut state = self.menu_state.borrow_mut();
6461                let was_presented = state.is_presented();
6462                let previous = state.reveal.value;
6463                let (hover_changed, hover_animating) = state.advance_hover(*time);
6464                let animating = state.reveal.advance(*time);
6465                let changed = state.reveal.changed_since(previous);
6466                let is_presented = state.is_presented();
6467                drop(state);
6468
6469                if changed {
6470                    request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
6471                    request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
6472                }
6473                if was_presented != is_presented {
6474                    ctx.request_measure();
6475                    request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
6476                }
6477                if hover_changed {
6478                    request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
6479                }
6480                if header_changed {
6481                    ctx.request_paint();
6482                }
6483                if animating || header_animating || hover_animating {
6484                    ctx.request_animation_frame();
6485                }
6486                ctx.set_handled();
6487            }
6488            _ => {}
6489        }
6490    }
6491
6492    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6493        let theme = self.resolved_theme();
6494        let padding = theme.metrics.text_input_padding;
6495        let text_style = theme.body_text_style();
6496        let widest_option = self
6497            .options
6498            .iter()
6499            .map(|label| measure_text(ctx, label, &text_style).width)
6500            .fold(0.0, f32::max);
6501        let placeholder_width =
6502            measure_text(ctx, &self.placeholder, &theme.placeholder_text_style()).width;
6503        let widest = widest_option.max(placeholder_width);
6504        let width = (widest + padding.left + padding.right + SELECT_CHEVRON_SLOT_WIDTH)
6505            .max(theme.metrics.button_min_width + SELECT_CHEVRON_SLOT_WIDTH + padding.right);
6506        let height = self.header_height();
6507        let presented = self.menu_state.borrow().is_presented();
6508        if presented {
6509            let menu_size = Size::new(width, self.menu_height());
6510            {
6511                let mut state = self.menu_state.borrow_mut();
6512                state.theme = theme;
6513                state.options = self.options.clone();
6514                state.selected = self.current_selected_index();
6515                if state.hovered != self.hovered_option {
6516                    state.sync_hovered_without_animation(self.hovered_option);
6517                }
6518                state.menu_bounds = Rect::from_origin_size(Point::ZERO, menu_size);
6519            }
6520            self.menu_surface
6521                .measure(ctx, Constraints::tight(menu_size));
6522        }
6523
6524        constraints.clamp(Size::new(width, height))
6525    }
6526
6527    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
6528        self.sync_menu_state(bounds, ctx.dpi().viewport);
6529        let state = self.menu_state.borrow();
6530        let surface_bounds = if state.is_presented() {
6531            state.menu_bounds
6532        } else {
6533            Rect::from_origin_size(bounds.origin, Size::ZERO)
6534        };
6535        drop(state);
6536        self.menu_surface.arrange(ctx, surface_bounds);
6537    }
6538
6539    fn paint(&self, ctx: &mut PaintCtx) {
6540        let theme = self.resolved_theme();
6541        let palette = theme.palette;
6542        let metrics = theme.metrics;
6543        let interaction = theme.interaction;
6544        let header = self.header_rect(ctx.bounds());
6545        let label = self.current_label();
6546        let placeholder = self.current_value().is_none();
6547        let hover_progress = self.hover_animation.value * interaction.hover_blend;
6548        let press_progress = self.press_animation.value * interaction.pressed_blend;
6549        let focus_progress = self.focus_animation.value;
6550        let content_offset =
6551            Vector::new(0.0, self.press_animation.value * interaction.pressed_offset);
6552        let text_style = if placeholder {
6553            theme.placeholder_text_style()
6554        } else {
6555            theme.body_text_style()
6556        };
6557        let text_slot = Rect::new(
6558            header.x() + metrics.text_input_padding.left,
6559            header.y(),
6560            (header.width()
6561                - metrics.text_input_padding.left
6562                - metrics.text_input_padding.right
6563                - SELECT_CHEVRON_SLOT_WIDTH)
6564                .max(0.0),
6565            header.height(),
6566        );
6567        // Mesh selects are dressed fields: the closed control sits on the
6568        // field token; hover/press keep the well and animate the border.
6569        draw_control_frame(
6570            ctx,
6571            header,
6572            metrics.corner_radius,
6573            metrics,
6574            mix_color(
6575                mix_color(palette.field, palette.control_active, press_progress * 0.5),
6576                palette.surface_focus,
6577                focus_progress,
6578            ),
6579            mix_color(
6580                mix_color(
6581                    palette.border,
6582                    palette.border_hover,
6583                    self.hover_animation.value.max(hover_progress),
6584                ),
6585                palette.border_focus,
6586                focus_progress,
6587            ),
6588            (focus_progress > 0.0).then_some(
6589                palette
6590                    .focus_ring
6591                    .with_alpha(palette.focus_ring.alpha * focus_progress),
6592            ),
6593        );
6594        ctx.push_clip_rect(text_slot);
6595        paint_single_line_aligned_text(
6596            ctx,
6597            text_slot.translate(content_offset),
6598            &label,
6599            &text_style,
6600            text_style.line_height,
6601            0.0,
6602        );
6603        ctx.pop_clip();
6604        draw_icon_glyph(
6605            ctx,
6606            if self.expanded {
6607                IconGlyph::ChevronUp
6608            } else {
6609                IconGlyph::ChevronDown
6610            },
6611            select_chevron_icon_rect(header).translate(content_offset),
6612            palette.text,
6613        );
6614
6615        if self.menu_state.borrow().is_presented() {
6616            self.menu_surface.paint(ctx);
6617        }
6618    }
6619
6620    fn semantics(&self, ctx: &mut SemanticsCtx) {
6621        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::ComboBox, ctx.bounds());
6622        node.name = Some(self.name.clone());
6623        node.value = Some(SemanticsValue::Text(self.current_label()));
6624        node.state.focused = ctx.is_focused();
6625        node.state.hovered = self.hovered_header || self.menu_state.borrow().hovered.is_some();
6626        node.state.expanded = Some(self.expanded);
6627        node.popup = Some(SemanticsPopupKind::ListBox);
6628        node.actions = vec![
6629            SemanticsAction::Focus,
6630            SemanticsAction::Expand,
6631            SemanticsAction::Collapse,
6632            SemanticsAction::SetValue,
6633        ];
6634        ctx.push(node);
6635    }
6636
6637    fn accepts_focus(&self) -> bool {
6638        true
6639    }
6640
6641    fn overlay_options(&self) -> Option<OverlayOptions> {
6642        (self.expanded || self.menu_state.borrow().is_presented()).then_some(
6643            OverlayOptions::new(OverlayKind::Menu)
6644                .dismiss(if self.expanded {
6645                    OverlayDismissPolicy::TRANSIENT
6646                } else {
6647                    OverlayDismissPolicy::NONE
6648                })
6649                .focus(OverlayFocusBehavior::NONE),
6650        )
6651    }
6652
6653    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
6654        if !focused && self.expanded {
6655            self.set_expanded(ctx, false);
6656        }
6657        let theme = self.resolved_theme();
6658        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
6659        ctx.request_paint();
6660        ctx.request_semantics();
6661    }
6662
6663    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
6664        if self.menu_state.borrow().is_presented() {
6665            self.menu_surface.visit_children(visitor);
6666        }
6667    }
6668
6669    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
6670        if self.menu_state.borrow().is_presented() {
6671            self.menu_surface.visit_children_mut(visitor);
6672        }
6673    }
6674}
6675
6676pub type Divider = Separator;
6677pub type SpinBox = NumberInput;
6678pub type MultilineTextInput = TextArea;
6679pub type ComboBox = Select;
6680
6681const PASSWORD_MASK: &str = "•";
6682
6683pub struct TextInput {
6684    theme: Box<DefaultTheme>,
6685    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
6686    name: String,
6687    editor: EditableTextController,
6688    password: bool,
6689    placeholder: String,
6690    leading_icon: Option<IconGlyph>,
6691    read_only: bool,
6692    appearance: FieldAppearance,
6693    text_style: Option<TextStyle>,
6694    padding: Option<Insets>,
6695    min_width: Option<f32>,
6696    min_height: Option<f32>,
6697    hovered: bool,
6698    focused: bool,
6699    dragging_selection: bool,
6700    hover_animation: AnimatedScalar,
6701    focus_animation: AnimatedScalar,
6702    caret: CaretBlink,
6703    visible_measurement: Option<TextMeasurement>,
6704    input_measurement: Option<TextMeasurement>,
6705    display_layout: Option<PersistentTextLayout>,
6706    input_layout: Option<PersistentTextLayout>,
6707    changes: TextChangeCallbacks,
6708    on_focus_change: Option<Box<dyn FnMut(bool)>>,
6709}
6710
6711impl TextInput {
6712    pub fn new(name: impl Into<String>) -> Self {
6713        Self {
6714            theme: Box::new(DefaultTheme::default()),
6715            theme_reader: None,
6716            name: name.into(),
6717            editor: EditableTextController::new(),
6718            password: false,
6719            placeholder: String::new(),
6720            leading_icon: None,
6721            read_only: false,
6722            appearance: FieldAppearance::Framed,
6723            text_style: None,
6724            padding: None,
6725            min_width: None,
6726            min_height: None,
6727            hovered: false,
6728            focused: false,
6729            dragging_selection: false,
6730            hover_animation: AnimatedScalar::new(0.0),
6731            focus_animation: AnimatedScalar::new(0.0),
6732            caret: CaretBlink::new(CARET_BLINK_PERIOD_SECONDS),
6733            visible_measurement: None,
6734            input_measurement: None,
6735            display_layout: None,
6736            input_layout: None,
6737            changes: TextChangeCallbacks::default(),
6738            on_focus_change: None,
6739        }
6740    }
6741
6742    pub fn name(&self) -> &str {
6743        &self.name
6744    }
6745
6746    pub fn theme(mut self, theme: DefaultTheme) -> Self {
6747        self.theme = Box::new(theme);
6748        self.theme_reader = None;
6749        self
6750    }
6751
6752    pub fn theme_when<F>(mut self, theme: F) -> Self
6753    where
6754        F: Fn() -> DefaultTheme + 'static,
6755    {
6756        self.theme_reader = Some(Box::new(theme));
6757        self
6758    }
6759
6760    pub fn text_style(mut self, text_style: TextStyle) -> Self {
6761        self.text_style = Some(text_style);
6762        self
6763    }
6764
6765    pub fn appearance(mut self, appearance: FieldAppearance) -> Self {
6766        self.appearance = appearance;
6767        self
6768    }
6769
6770    pub fn bare(mut self) -> Self {
6771        self.appearance = FieldAppearance::Bare;
6772        self
6773    }
6774
6775    pub fn padding(mut self, padding: Insets) -> Self {
6776        self.padding = Some(padding);
6777        self
6778    }
6779
6780    pub fn min_width(mut self, width: f32) -> Self {
6781        self.min_width = Some(width.max(0.0));
6782        self
6783    }
6784
6785    pub fn min_height(mut self, height: f32) -> Self {
6786        self.min_height = Some(height.max(0.0));
6787        self
6788    }
6789
6790    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
6791        self.placeholder = placeholder.into();
6792        self
6793    }
6794
6795    pub fn leading_icon(mut self, icon: IconGlyph) -> Self {
6796        self.leading_icon = Some(icon);
6797        self
6798    }
6799
6800    pub fn read_only(mut self) -> Self {
6801        self.read_only = true;
6802        self
6803    }
6804
6805    pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
6806        self.editor.selectable(selection_scope);
6807        self
6808    }
6809
6810    pub fn selection_scope(mut self, selection_scope: SelectionScope) -> Self {
6811        self.editor.selection_scope(selection_scope);
6812        self
6813    }
6814
6815    pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
6816        self.editor.clipboard_behavior(behavior);
6817        self
6818    }
6819
6820    pub fn copy_to_clipboard(self, enabled: bool) -> Self {
6821        self.clipboard_behavior(if enabled {
6822            SelectionClipboardBehavior::WidgetManaged
6823        } else {
6824            SelectionClipboardBehavior::AppManaged
6825        })
6826    }
6827
6828    pub fn value(mut self, value: impl Into<String>) -> Self {
6829        self.editor.set_text(single_line_text(value.into()));
6830        self
6831    }
6832
6833    fn password(mut self) -> Self {
6834        self.password = true;
6835        self
6836    }
6837
6838    pub fn current_value(&self) -> &str {
6839        self.editor.document().text()
6840    }
6841
6842    pub fn set_value(&mut self, value: impl Into<String>) {
6843        self.editor.set_text(single_line_text(value.into()));
6844    }
6845
6846    pub fn on_change<F>(mut self, on_change: F) -> Self
6847    where
6848        F: FnMut(String) + 'static,
6849    {
6850        self.changes.value = Some(Box::new(on_change));
6851        self
6852    }
6853
6854    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
6855    where
6856        F: FnMut(&mut EventCtx, String) + 'static,
6857    {
6858        self.changes.with_ctx = Some(Box::new(on_change));
6859        self
6860    }
6861
6862    pub fn on_focus_change<F>(mut self, on_focus_change: F) -> Self
6863    where
6864        F: FnMut(bool) + 'static,
6865    {
6866        self.on_focus_change = Some(Box::new(on_focus_change));
6867        self
6868    }
6869
6870    fn input_text(&self) -> String {
6871        self.editor.display_text()
6872    }
6873
6874    fn rendered_input_text(&self) -> String {
6875        let input = self.input_text();
6876        if self.password {
6877            PASSWORD_MASK.repeat(input.graphemes(true).count())
6878        } else {
6879            input
6880        }
6881    }
6882
6883    fn rendered_offset(&self, input: &str, editor_offset: usize) -> usize {
6884        if !self.password {
6885            return editor_offset.min(input.len());
6886        }
6887
6888        input
6889            .grapheme_indices(true)
6890            .take_while(|(offset, _)| *offset < editor_offset.min(input.len()))
6891            .count()
6892            * PASSWORD_MASK.len()
6893    }
6894
6895    fn editor_offset(&self, input: &str, rendered_offset: usize) -> usize {
6896        if !self.password {
6897            return rendered_offset.min(input.len());
6898        }
6899
6900        let grapheme_index = rendered_offset / PASSWORD_MASK.len();
6901        input
6902            .grapheme_indices(true)
6903            .nth(grapheme_index)
6904            .map(|(offset, _)| offset)
6905            .unwrap_or(input.len())
6906    }
6907
6908    fn rendered_selection_range(&self, input: &str) -> Range<usize> {
6909        let selection = selection_range(&self.editor.display_selection(), input.len());
6910        self.rendered_offset(input, selection.start)..self.rendered_offset(input, selection.end)
6911    }
6912
6913    fn display_caret_offset(&self) -> usize {
6914        let input = self.input_text();
6915        self.rendered_offset(&input, self.editor.display_selection().focus.utf8_offset)
6916    }
6917
6918    fn visible_text(&self) -> String {
6919        let input = self.rendered_input_text();
6920        if input.is_empty() {
6921            self.placeholder.clone()
6922        } else {
6923            input
6924        }
6925    }
6926
6927    fn display_text_style(&self) -> TextStyle {
6928        let theme = self.resolved_theme();
6929        if self.input_text().is_empty() {
6930            theme.placeholder_text_style()
6931        } else if self.read_only {
6932            theme.text_style(theme.palette.text_muted)
6933        } else {
6934            self.resolved_text_style()
6935        }
6936    }
6937
6938    fn apply_editor_result(&mut self, ctx: &mut EventCtx, result: EditorCommandResult) {
6939        self.editor.apply_field_result(
6940            ctx,
6941            result,
6942            &mut self.changes,
6943            &mut self.caret,
6944            self.focused,
6945            self.read_only,
6946        );
6947    }
6948
6949    fn execute_editor_command(&mut self, ctx: &mut EventCtx, command: EditorCommand) {
6950        let result = self.editor.execute(command);
6951        self.apply_editor_result(ctx, result);
6952    }
6953
6954    /// Select the entire document.
6955    pub fn select_all(&mut self, ctx: &mut EventCtx) {
6956        self.apply_text_command(ctx, TextCommand::SelectAll);
6957    }
6958
6959    /// Copy the current selection to the clipboard. No-op when the selection
6960    /// is collapsed.
6961    pub fn copy(&mut self, ctx: &mut EventCtx) {
6962        self.apply_text_command(ctx, TextCommand::Copy);
6963    }
6964
6965    /// Copy the current selection to the clipboard and delete it. No-op when
6966    /// read-only or the selection is collapsed.
6967    pub fn cut(&mut self, ctx: &mut EventCtx) {
6968        self.apply_text_command(ctx, TextCommand::Cut);
6969    }
6970
6971    /// Replace the current selection with the clipboard text (coerced to a
6972    /// single line). No-op when read-only or the clipboard has no text.
6973    pub fn paste(&mut self, ctx: &mut EventCtx) {
6974        self.apply_text_command(ctx, TextCommand::Paste);
6975    }
6976
6977    /// Currently selected document text (empty when the selection is
6978    /// collapsed).
6979    pub fn selected_text(&self) -> &str {
6980        self.editor.selected_text()
6981    }
6982
6983    fn apply_text_command(&mut self, ctx: &mut EventCtx, command: TextCommand) {
6984        if let Some(command) = self.editor.text_command(
6985            ctx,
6986            command,
6987            self.read_only,
6988            EditableTextLineMode::SingleLine,
6989        ) {
6990            self.execute_editor_command(ctx, command);
6991        }
6992    }
6993
6994    fn text_offset_at_position(&self, bounds: Rect, position: Point) -> usize {
6995        let content = self.text_content_rect(bounds);
6996        let rendered_offset = self
6997            .input_layout
6998            .as_ref()
6999            .map(|layout| {
7000                layout
7001                    .hit_test_point(Point::new(
7002                        position.x - content.x(),
7003                        position.y - content.y(),
7004                    ))
7005                    .utf8_offset
7006            })
7007            .unwrap_or(self.rendered_input_text().len());
7008        self.editor_offset(&self.input_text(), rendered_offset)
7009    }
7010
7011    fn set_caret_from_position(
7012        &mut self,
7013        bounds: Rect,
7014        position: Point,
7015        extend: bool,
7016        ctx: &mut EventCtx,
7017    ) {
7018        let offset = self.text_offset_at_position(bounds, position);
7019        let command = if extend {
7020            EditorCommand::SetSelection {
7021                anchor: self.editor.selection().anchor.utf8_offset,
7022                focus: offset,
7023            }
7024        } else {
7025            EditorCommand::MoveTo {
7026                offset,
7027                extend: false,
7028            }
7029        };
7030        let result = self.editor.execute(command);
7031        self.apply_editor_result(ctx, result);
7032        self.caret.reset(ctx, self.focused, self.read_only);
7033    }
7034
7035    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
7036        if self.hovered != hovered {
7037            let theme = self.resolved_theme();
7038            self.hovered = hovered;
7039            set_hover_animation_target(
7040                &mut self.hover_animation,
7041                hovered as u8 as f32,
7042                &theme,
7043                ctx,
7044            );
7045            ctx.request_paint();
7046            ctx.request_semantics();
7047        }
7048    }
7049
7050    fn resolved_text_style(&self) -> TextStyle {
7051        self.text_style
7052            .clone()
7053            .unwrap_or_else(|| self.resolved_theme().body_text_style())
7054    }
7055
7056    fn resolved_padding(&self) -> Insets {
7057        self.padding
7058            .unwrap_or(self.resolved_theme().metrics.text_input_padding)
7059    }
7060
7061    fn leading_icon_advance(&self) -> f32 {
7062        if self.leading_icon.is_some() {
7063            24.0
7064        } else {
7065            0.0
7066        }
7067    }
7068
7069    fn text_content_rect(&self, bounds: Rect) -> Rect {
7070        let content = inset_rect(bounds, self.resolved_padding());
7071        let leading = self.leading_icon_advance();
7072        Rect::new(
7073            (content.x() + leading).min(content.max_x()),
7074            content.y(),
7075            (content.width() - leading).max(0.0),
7076            content.height(),
7077        )
7078    }
7079
7080    fn resolved_min_size(&self) -> Size {
7081        let theme = self.resolved_theme();
7082        Size::new(
7083            self.min_width.unwrap_or(theme.metrics.text_input_min_width),
7084            self.min_height.unwrap_or(theme.metrics.min_height),
7085        )
7086    }
7087
7088    fn resolved_theme(&self) -> DefaultTheme {
7089        self.theme_reader
7090            .as_ref()
7091            .map(|theme| theme())
7092            .unwrap_or(*self.theme)
7093    }
7094
7095    fn single_line_layout_rect(
7096        &self,
7097        ctx: &PaintCtx,
7098        content: Rect,
7099        layout: &PersistentTextLayout,
7100        line_height: f32,
7101    ) -> Rect {
7102        aligned_text_rect_for_layout(ctx, content, layout.layout(), line_height, 0.0)
7103    }
7104
7105    fn single_line_text_rect(
7106        &self,
7107        ctx: &PaintCtx,
7108        content: Rect,
7109        text: &str,
7110        style: &TextStyle,
7111        line_height: f32,
7112    ) -> Rect {
7113        aligned_text_rect_for_text(ctx, content, text, style, line_height, 0.0)
7114    }
7115}
7116
7117impl Widget for TextInput {
7118    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
7119        match event {
7120            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
7121                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
7122                if self.dragging_selection
7123                    && ctx.phase() != EventPhase::Capture
7124                    && pointer.buttons.contains(PointerButton::Primary)
7125                {
7126                    let offset = self.text_offset_at_position(ctx.bounds(), pointer.position);
7127                    let anchor = self.editor.selection().anchor.utf8_offset;
7128                    let result = self.editor.execute(EditorCommand::SetSelection {
7129                        anchor,
7130                        focus: offset,
7131                    });
7132                    self.apply_editor_result(ctx, result);
7133                }
7134            }
7135            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Enter) => {
7136                self.set_hovered(true, ctx);
7137            }
7138            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
7139                self.set_hovered(false, ctx);
7140            }
7141            Event::Pointer(pointer)
7142                if pointer.kind == PointerEventKind::Down
7143                    && pointer.button == Some(PointerButton::Primary) =>
7144            {
7145                self.set_hovered(true, ctx);
7146                self.set_caret_from_position(
7147                    ctx.bounds(),
7148                    pointer.position,
7149                    pointer.modifiers.shift,
7150                    ctx,
7151                );
7152                self.dragging_selection = true;
7153                ctx.request_pointer_capture(pointer.pointer_id);
7154                ctx.request_focus();
7155                ctx.request_paint();
7156                ctx.request_semantics();
7157                ctx.set_handled();
7158            }
7159            Event::Pointer(pointer)
7160                if pointer.kind == PointerEventKind::Up
7161                    && pointer.button == Some(PointerButton::Primary)
7162                    && self.dragging_selection =>
7163            {
7164                self.dragging_selection = false;
7165                ctx.release_pointer_capture(pointer.pointer_id);
7166                ctx.set_handled();
7167            }
7168            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
7169                if self.dragging_selection {
7170                    self.dragging_selection = false;
7171                    ctx.release_pointer_capture(pointer.pointer_id);
7172                }
7173            }
7174            Event::Pointer(pointer)
7175                if pointer.kind == PointerEventKind::Down
7176                    && pointer.button == Some(PointerButton::Secondary)
7177                    && ctx.phase() != EventPhase::Capture
7178                    && ctx.bounds().contains(pointer.position) =>
7179            {
7180                // Focus on right-click (keeping the selection intact) so
7181                // follow-up clipboard commands land here. Deliberately not
7182                // handled: wrapping context menus react to the same press.
7183                self.set_hovered(true, ctx);
7184                if !ctx.is_focused() {
7185                    ctx.request_focus();
7186                    ctx.request_paint();
7187                    ctx.request_semantics();
7188                }
7189            }
7190            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
7191                if let Some(commands) = self.editor.semantics_commands(
7192                    ctx,
7193                    &semantics.action,
7194                    self.read_only,
7195                    EditableTextLineMode::SingleLine,
7196                ) {
7197                    for command in commands {
7198                        self.execute_editor_command(ctx, command);
7199                    }
7200                }
7201            }
7202            Event::Ime(ImeEvent::CompositionStart) if ctx.is_focused() => {
7203                if !self.read_only {
7204                    self.execute_editor_command(ctx, EditorCommand::StartComposition);
7205                }
7206            }
7207            Event::Ime(ImeEvent::CompositionUpdate { text, cursor_range }) if ctx.is_focused() => {
7208                if !self.read_only {
7209                    self.execute_editor_command(
7210                        ctx,
7211                        EditorCommand::UpdateComposition {
7212                            text: single_line_text(text.clone()),
7213                            cursor_range: cursor_range.clone(),
7214                        },
7215                    );
7216                }
7217            }
7218            Event::Ime(ImeEvent::CompositionCommit { text }) if ctx.is_focused() => {
7219                if !self.read_only {
7220                    self.execute_editor_command(
7221                        ctx,
7222                        EditorCommand::CommitComposition(single_line_text(text.clone())),
7223                    );
7224                }
7225            }
7226            Event::Ime(ImeEvent::CompositionEnd) if ctx.is_focused() => {
7227                if !self.read_only {
7228                    self.execute_editor_command(ctx, EditorCommand::EndComposition);
7229                }
7230            }
7231            Event::Keyboard(key) if key.state == KeyState::Pressed && ctx.is_focused() => {
7232                if let Some(command) = self.editor.keyboard_command(
7233                    ctx,
7234                    key,
7235                    self.read_only,
7236                    EditableTextLineMode::SingleLine,
7237                ) {
7238                    self.execute_editor_command(ctx, command);
7239                }
7240            }
7241            Event::Wake(sui_core::WakeEvent::Timer { token, .. }) if self.caret.matches(*token) => {
7242                self.caret.tick(ctx, self.focused);
7243            }
7244            Event::Wake(sui_core::WakeEvent::AnimationFrame { time, .. }) => {
7245                let previous_hover = self.hover_animation.value;
7246                let previous_focus = self.focus_animation.value;
7247                let animating =
7248                    self.hover_animation.advance(*time) | self.focus_animation.advance(*time);
7249                let changed = self.hover_animation.changed_since(previous_hover)
7250                    || self.focus_animation.changed_since(previous_focus);
7251                if animating {
7252                    ctx.request_animation_frame();
7253                }
7254                if changed {
7255                    ctx.request_paint();
7256                }
7257            }
7258            _ => {}
7259        }
7260    }
7261
7262    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
7263        let Some(command) = TextCommand::from_command(command) else {
7264            return;
7265        };
7266        if !ctx.is_focused() {
7267            ctx.request_focus();
7268        }
7269        self.apply_text_command(ctx, command);
7270    }
7271
7272    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
7273        let text_style = self.resolved_text_style();
7274        let padding = self.resolved_padding();
7275        let min_size = self.resolved_min_size();
7276        let visible_text = self.visible_text();
7277        let input_text = self.rendered_input_text();
7278        let display_style = self.display_text_style();
7279        let measured_visible = measure_text(ctx, &visible_text, &display_style);
7280        let measured_input = if input_text.is_empty() {
7281            TextMeasurement {
7282                width: 0.0,
7283                height: measured_visible.height,
7284                bounds: Rect::new(0.0, 0.0, 0.0, measured_visible.height),
7285                ascent: measured_visible.ascent,
7286                descent: measured_visible.descent,
7287                cap_height: measured_visible.cap_height,
7288            }
7289        } else {
7290            measure_text(ctx, &input_text, &text_style)
7291        };
7292        let display_line_height = display_style
7293            .line_height
7294            .max(measured_visible.height)
7295            .max(1.0);
7296        let input_line_height = text_style.line_height.max(measured_input.height).max(1.0);
7297        let display_line_box = Size::new(f32::INFINITY, display_line_height);
7298        let input_line_box = Size::new(f32::INFINITY, input_line_height);
7299        let display_layout = ctx
7300            .layout()
7301            .shape_text_persistent(
7302                self.display_layout.as_ref().map(|layout| layout.handle()),
7303                visible_text.clone(),
7304                display_line_box,
7305                display_style.clone(),
7306            )
7307            .ok();
7308        let input_layout = ctx
7309            .layout()
7310            .shape_text_persistent(
7311                self.input_layout.as_ref().map(|layout| layout.handle()),
7312                input_text.clone(),
7313                input_line_box,
7314                text_style.clone(),
7315            )
7316            .ok();
7317
7318        let visible_measurement = display_layout
7319            .as_ref()
7320            .map(|layout| layout.measurement())
7321            .unwrap_or(measured_visible);
7322        let input_measurement = input_layout
7323            .as_ref()
7324            .map(|layout| layout.measurement())
7325            .unwrap_or(measured_input);
7326
7327        self.visible_measurement = Some(visible_measurement);
7328        self.input_measurement = Some(input_measurement);
7329        self.display_layout = display_layout;
7330        self.input_layout = input_layout;
7331
7332        let width = (visible_measurement.width
7333            + self.leading_icon_advance()
7334            + padding.left
7335            + padding.right)
7336            .max(min_size.width);
7337        let height = (visible_measurement.height.max(display_style.line_height)
7338            + padding.top
7339            + padding.bottom)
7340            .max(min_size.height);
7341
7342        constraints.clamp(Size::new(width, height))
7343    }
7344
7345    fn paint(&self, ctx: &mut PaintCtx) {
7346        let theme = self.resolved_theme();
7347        let palette = theme.palette;
7348        let metrics = theme.metrics;
7349        let text_style = self.resolved_text_style();
7350        let padding = self.resolved_padding();
7351        let focus_progress = self.focus_animation.value;
7352        // Light fields lift from their slightly recessed rest fill to the
7353        // surface on hover. Focus then moves every scheme toward its soft
7354        // accent well; dark and Void keep their established resting depth.
7355        let background = field_background(
7356            &theme,
7357            self.read_only,
7358            self.hover_animation.value,
7359            focus_progress,
7360        );
7361        let border = mix_color(
7362            mix_color(
7363                palette.border,
7364                palette.border_hover,
7365                self.hover_animation.value,
7366            ),
7367            palette.border_focus,
7368            focus_progress,
7369        );
7370        let full_content_rect = inset_rect(ctx.bounds(), padding);
7371        let content_rect = self.text_content_rect(ctx.bounds());
7372        let display_text = self.visible_text();
7373        let placeholder = self.input_text().is_empty();
7374
7375        if self.appearance == FieldAppearance::Framed {
7376            draw_control_frame(
7377                ctx,
7378                ctx.bounds(),
7379                metrics.corner_radius,
7380                metrics,
7381                background,
7382                border,
7383                (focus_progress > 0.0).then_some(
7384                    palette
7385                        .focus_ring
7386                        .with_alpha(palette.focus_ring.alpha * focus_progress),
7387                ),
7388            );
7389        }
7390        if let Some(icon) = self.leading_icon {
7391            let icon_color = if self.read_only || placeholder {
7392                palette.text_muted
7393            } else {
7394                palette.text
7395            };
7396            let icon_side = 15.0;
7397            let icon_rect = Rect::new(
7398                full_content_rect.x() + 1.0,
7399                full_content_rect.y() + (full_content_rect.height() - icon_side) * 0.5,
7400                icon_side,
7401                icon_side,
7402            );
7403            draw_icon_glyph(ctx, icon, icon_rect, icon_color);
7404        }
7405        ctx.push_clip_rect(content_rect);
7406        if let Some(layout) = &self.display_layout {
7407            let layout_bounds = layout.measurement().bounds;
7408            let layout_rect =
7409                self.single_line_layout_rect(ctx, content_rect, layout, layout.style().line_height);
7410            let layout_origin = Point::new(layout_rect.x() - layout_bounds.x(), layout_rect.y());
7411            if !placeholder {
7412                let input = self.input_text();
7413                let selection = self.rendered_selection_range(&input);
7414                if !selection.is_empty() {
7415                    for rect in layout.selection_rects(selection) {
7416                        ctx.fill_rect(rect.translate(layout_origin.to_vector()), palette.selection);
7417                    }
7418                }
7419            }
7420            ctx.draw_persistent_text_layout(layout_origin, layout);
7421        } else {
7422            let display_style = if placeholder {
7423                theme.placeholder_text_style()
7424            } else if self.read_only {
7425                theme.text_style(palette.text_muted)
7426            } else {
7427                text_style.clone()
7428            };
7429            paint_aligned_text(
7430                ctx,
7431                content_rect,
7432                &display_text,
7433                &display_style,
7434                display_style.line_height,
7435                0.0,
7436            );
7437        }
7438        ctx.pop_clip();
7439
7440        if self.focused && !self.read_only {
7441            let caret_width = physical_pixels(ctx, metrics.caret_width);
7442            let input_text = self.rendered_input_text();
7443            let input_text_rect = self
7444                .input_layout
7445                .as_ref()
7446                .map(|layout| {
7447                    self.single_line_layout_rect(ctx, content_rect, layout, text_style.line_height)
7448                })
7449                .unwrap_or_else(|| {
7450                    self.single_line_text_rect(
7451                        ctx,
7452                        content_rect,
7453                        &input_text,
7454                        &text_style,
7455                        text_style.line_height,
7456                    )
7457                });
7458            let caret_rect = self
7459                .input_layout
7460                .as_ref()
7461                .map(|layout| {
7462                    layout
7463                        .caret_rect(self.display_caret_offset())
7464                        .translate(input_text_rect.origin.to_vector())
7465                })
7466                .unwrap_or(Rect::new(
7467                    input_text_rect.x()
7468                        + self
7469                            .input_measurement
7470                            .map(|measurement| measurement.width)
7471                            .unwrap_or(0.0),
7472                    input_text_rect.y(),
7473                    caret_width,
7474                    input_text_rect.height().max(text_style.line_height),
7475                ));
7476            let caret_rect = Rect::new(
7477                caret_rect
7478                    .x()
7479                    .min((content_rect.max_x() - caret_width).max(content_rect.x()))
7480                    .max(content_rect.x()),
7481                caret_rect.y(),
7482                caret_width,
7483                caret_rect.height().max(text_style.line_height),
7484            );
7485            ctx.set_ime_composition_rect(caret_rect);
7486            if self.caret.visible {
7487                ctx.fill(
7488                    rounded_rect_path(caret_rect, caret_width * 0.5),
7489                    palette.caret,
7490                );
7491            }
7492        }
7493    }
7494
7495    fn semantics(&self, ctx: &mut SemanticsCtx) {
7496        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
7497        let display_text = self.input_text();
7498        let display_selection = self.editor.display_selection();
7499        let selection = selection_range(&display_selection, display_text.len());
7500        node.name = Some(self.name.clone());
7501        node.value = Some(SemanticsValue::Text(display_text));
7502        node.state.focused = ctx.is_focused();
7503        node.state.hovered = self.hovered;
7504        node.editable_text = Some(EditableTextSemantics {
7505            caret_offset: display_selection.focus.utf8_offset,
7506            selection: SemanticsTextRange::new(selection.start, selection.end),
7507            multiline: false,
7508            password: self.password,
7509            readonly: self.read_only,
7510            scroll_x: 0.0,
7511            scroll_y: 0.0,
7512        });
7513        node.actions = self.editor.semantic_actions(self.read_only);
7514        ctx.push(node);
7515    }
7516
7517    fn accepts_focus(&self) -> bool {
7518        true
7519    }
7520
7521    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
7522        self.focused = focused;
7523        if !focused {
7524            let result = self.editor.execute(EditorCommand::ClearComposition);
7525            if result.layout_changed() {
7526                ctx.request_measure();
7527            }
7528        }
7529        if focused {
7530            self.caret.reset(ctx, self.focused, self.read_only);
7531        } else {
7532            self.caret.stop(ctx);
7533        }
7534        let theme = self.resolved_theme();
7535        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
7536        if let Some(on_focus_change) = &mut self.on_focus_change {
7537            on_focus_change(focused);
7538        }
7539        ctx.request_paint();
7540        ctx.request_semantics();
7541    }
7542}
7543
7544/// A single-line text input that masks its visible value while retaining the
7545/// same selection, clipboard, IME, and change-callback behavior as
7546/// [`TextInput`].
7547pub struct PasswordInput {
7548    inner: TextInput,
7549}
7550
7551impl PasswordInput {
7552    pub fn new(name: impl Into<String>) -> Self {
7553        Self {
7554            inner: TextInput::new(name).password(),
7555        }
7556    }
7557
7558    pub fn theme(mut self, theme: DefaultTheme) -> Self {
7559        self.inner = self.inner.theme(theme);
7560        self
7561    }
7562
7563    pub fn theme_when<F>(mut self, theme: F) -> Self
7564    where
7565        F: Fn() -> DefaultTheme + 'static,
7566    {
7567        self.inner = self.inner.theme_when(theme);
7568        self
7569    }
7570
7571    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
7572        self.inner = self.inner.placeholder(placeholder);
7573        self
7574    }
7575
7576    pub fn value(mut self, value: impl Into<String>) -> Self {
7577        self.inner = self.inner.value(value);
7578        self
7579    }
7580
7581    pub fn min_width(mut self, width: f32) -> Self {
7582        self.inner = self.inner.min_width(width);
7583        self
7584    }
7585
7586    pub fn read_only(mut self) -> Self {
7587        self.inner = self.inner.read_only();
7588        self
7589    }
7590
7591    pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
7592        self.inner = self.inner.selectable(selection_scope);
7593        self
7594    }
7595
7596    pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
7597        self.inner = self.inner.clipboard_behavior(behavior);
7598        self
7599    }
7600
7601    pub fn copy_to_clipboard(mut self, enabled: bool) -> Self {
7602        self.inner = self.inner.copy_to_clipboard(enabled);
7603        self
7604    }
7605
7606    pub fn on_change<F>(mut self, on_change: F) -> Self
7607    where
7608        F: FnMut(String) + 'static,
7609    {
7610        self.inner = self.inner.on_change(on_change);
7611        self
7612    }
7613
7614    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
7615    where
7616        F: FnMut(&mut EventCtx, String) + 'static,
7617    {
7618        self.inner = self.inner.on_change_with_ctx(on_change);
7619        self
7620    }
7621
7622    pub fn current_value(&self) -> &str {
7623        self.inner.current_value()
7624    }
7625
7626    pub fn set_value(&mut self, value: impl Into<String>) {
7627        self.inner.set_value(value);
7628    }
7629
7630    pub fn selected_text(&self) -> &str {
7631        self.inner.selected_text()
7632    }
7633
7634    pub fn select_all(&mut self, ctx: &mut EventCtx) {
7635        self.inner.select_all(ctx);
7636    }
7637
7638    pub fn copy(&mut self, ctx: &mut EventCtx) {
7639        self.inner.copy(ctx);
7640    }
7641
7642    pub fn cut(&mut self, ctx: &mut EventCtx) {
7643        self.inner.cut(ctx);
7644    }
7645
7646    pub fn paste(&mut self, ctx: &mut EventCtx) {
7647        self.inner.paste(ctx);
7648    }
7649}
7650
7651impl Widget for PasswordInput {
7652    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
7653        self.inner.event(ctx, event);
7654    }
7655
7656    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
7657        self.inner.measure(ctx, constraints)
7658    }
7659
7660    fn paint(&self, ctx: &mut PaintCtx) {
7661        self.inner.paint(ctx);
7662    }
7663
7664    fn semantics(&self, ctx: &mut SemanticsCtx) {
7665        self.inner.semantics(ctx);
7666    }
7667
7668    fn accepts_focus(&self) -> bool {
7669        self.inner.accepts_focus()
7670    }
7671
7672    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
7673        self.inner.focus_changed(ctx, focused);
7674    }
7675}
7676
7677/// A lightweight single-line local date/time field. Values remain strings so
7678/// applications can choose their own parsing, timezone, and validation rules;
7679/// the suggested format is `YYYY-MM-DD HH:MM`.
7680pub struct DateTimeInput {
7681    inner: TextInput,
7682}
7683
7684impl DateTimeInput {
7685    pub fn new(name: impl Into<String>) -> Self {
7686        Self {
7687            inner: TextInput::new(name).placeholder("YYYY-MM-DD HH:MM"),
7688        }
7689    }
7690
7691    pub fn theme(mut self, theme: DefaultTheme) -> Self {
7692        self.inner = self.inner.theme(theme);
7693        self
7694    }
7695
7696    pub fn theme_when<F>(mut self, theme: F) -> Self
7697    where
7698        F: Fn() -> DefaultTheme + 'static,
7699    {
7700        self.inner = self.inner.theme_when(theme);
7701        self
7702    }
7703
7704    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
7705        self.inner = self.inner.placeholder(placeholder);
7706        self
7707    }
7708
7709    pub fn value(mut self, value: impl Into<String>) -> Self {
7710        self.inner = self.inner.value(value);
7711        self
7712    }
7713
7714    pub fn min_width(mut self, width: f32) -> Self {
7715        self.inner = self.inner.min_width(width);
7716        self
7717    }
7718
7719    pub fn read_only(mut self) -> Self {
7720        self.inner = self.inner.read_only();
7721        self
7722    }
7723
7724    pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
7725        self.inner = self.inner.selectable(selection_scope);
7726        self
7727    }
7728
7729    pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
7730        self.inner = self.inner.clipboard_behavior(behavior);
7731        self
7732    }
7733
7734    pub fn copy_to_clipboard(mut self, enabled: bool) -> Self {
7735        self.inner = self.inner.copy_to_clipboard(enabled);
7736        self
7737    }
7738
7739    pub fn on_change<F>(mut self, on_change: F) -> Self
7740    where
7741        F: FnMut(String) + 'static,
7742    {
7743        self.inner = self.inner.on_change(on_change);
7744        self
7745    }
7746
7747    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
7748    where
7749        F: FnMut(&mut EventCtx, String) + 'static,
7750    {
7751        self.inner = self.inner.on_change_with_ctx(on_change);
7752        self
7753    }
7754
7755    pub fn current_value(&self) -> &str {
7756        self.inner.current_value()
7757    }
7758
7759    pub fn set_value(&mut self, value: impl Into<String>) {
7760        self.inner.set_value(value);
7761    }
7762
7763    pub fn selected_text(&self) -> &str {
7764        self.inner.selected_text()
7765    }
7766
7767    pub fn select_all(&mut self, ctx: &mut EventCtx) {
7768        self.inner.select_all(ctx);
7769    }
7770
7771    pub fn copy(&mut self, ctx: &mut EventCtx) {
7772        self.inner.copy(ctx);
7773    }
7774
7775    pub fn cut(&mut self, ctx: &mut EventCtx) {
7776        self.inner.cut(ctx);
7777    }
7778
7779    pub fn paste(&mut self, ctx: &mut EventCtx) {
7780        self.inner.paste(ctx);
7781    }
7782}
7783
7784impl Widget for DateTimeInput {
7785    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
7786        self.inner.event(ctx, event);
7787    }
7788
7789    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
7790        self.inner.measure(ctx, constraints)
7791    }
7792
7793    fn paint(&self, ctx: &mut PaintCtx) {
7794        self.inner.paint(ctx);
7795    }
7796
7797    fn semantics(&self, ctx: &mut SemanticsCtx) {
7798        self.inner.semantics(ctx);
7799    }
7800
7801    fn accepts_focus(&self) -> bool {
7802        self.inner.accepts_focus()
7803    }
7804
7805    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
7806        self.inner.focus_changed(ctx, focused);
7807    }
7808}
7809
7810fn measure_text(ctx: &mut MeasureCtx, text: &str, style: &TextStyle) -> TextMeasurement {
7811    ctx.layout()
7812        .measure_text(text.to_string(), style.clone())
7813        .unwrap_or(TextMeasurement {
7814            width: 0.0,
7815            height: style.line_height,
7816            bounds: Rect::new(0.0, 0.0, 0.0, style.line_height),
7817            ascent: style.font_size,
7818            descent: 0.0,
7819            cap_height: Some(style.font_size),
7820        })
7821}
7822
7823fn measure_text_size(ctx: &mut MeasureCtx, text: &str, style: &TextStyle) -> Size {
7824    ctx.layout()
7825        .measure_text_size(text.to_owned(), style.clone())
7826        .unwrap_or(Size::new(0.0, style.line_height))
7827}
7828
7829fn numeric_text_style(mut style: TextStyle) -> TextStyle {
7830    style.features.enable(FontFeature::TABULAR_FIGURES);
7831    style
7832}
7833
7834fn center_square(bounds: Rect, side: f32) -> Rect {
7835    let side = side.min(bounds.width()).min(bounds.height()).max(0.0);
7836    Rect::new(
7837        bounds.x() + ((bounds.width() - side) * 0.5),
7838        bounds.y() + ((bounds.height() - side) * 0.5),
7839        side,
7840        side,
7841    )
7842}
7843
7844fn rect_center(rect: Rect) -> Point {
7845    Point::new(
7846        rect.x() + (rect.width() * 0.5),
7847        rect.y() + (rect.height() * 0.5),
7848    )
7849}
7850
7851fn switch_track_rect(bounds: Rect, padding: Insets, metrics: ControlMetrics) -> Rect {
7852    Rect::new(
7853        bounds.x() + padding.left,
7854        bounds.y() + ((bounds.height() - metrics.switch_track_height) * 0.5),
7855        metrics.switch_track_width,
7856        metrics.switch_track_height,
7857    )
7858}
7859
7860fn switch_label_rect(bounds: Rect, padding: Insets, metrics: ControlMetrics, gap: f32) -> Rect {
7861    let x = bounds.x() + padding.left + metrics.switch_track_width + gap;
7862    Rect::new(
7863        x,
7864        bounds.y(),
7865        (bounds.width() - (x - bounds.x()) - padding.right).max(0.0),
7866        bounds.height(),
7867    )
7868}
7869
7870fn horizontal_text_inset_rect(bounds: Rect, padding: Insets) -> Rect {
7871    Rect::new(
7872        bounds.x() + padding.left,
7873        bounds.y(),
7874        (bounds.width() - padding.left - padding.right).max(0.0),
7875        bounds.height(),
7876    )
7877}
7878
7879fn select_chevron_icon_rect(header: Rect) -> Rect {
7880    let x = header.max_x() - SELECT_CHEVRON_SLOT_WIDTH
7881        + ((SELECT_CHEVRON_SLOT_WIDTH - SELECT_CHEVRON_ICON_SIZE).max(0.0) * 0.5);
7882    Rect::new(x, header.y(), SELECT_CHEVRON_ICON_SIZE, header.height())
7883}
7884
7885fn number_input_stepper_rect(bounds: Rect, metrics: ControlMetrics) -> Rect {
7886    Rect::new(
7887        bounds.max_x() - metrics.number_input_stepper_width,
7888        bounds.y(),
7889        metrics.number_input_stepper_width,
7890        bounds.height(),
7891    )
7892}
7893
7894fn number_input_stepper_part(
7895    bounds: Rect,
7896    metrics: ControlMetrics,
7897    position: Point,
7898) -> Option<NumberInputStepperPart> {
7899    let stepper = number_input_stepper_rect(bounds, metrics);
7900    if !stepper.contains(position) {
7901        return None;
7902    }
7903    if position.y < stepper.y() + (stepper.height() * 0.5) {
7904        Some(NumberInputStepperPart::Increment)
7905    } else {
7906        Some(NumberInputStepperPart::Decrement)
7907    }
7908}
7909
7910fn number_input_text_rect(bounds: Rect, metrics: ControlMetrics) -> Rect {
7911    let padding = metrics.text_input_padding;
7912    Rect::new(
7913        bounds.x() + padding.left,
7914        bounds.y(),
7915        (bounds.width() - padding.left - padding.right - metrics.number_input_stepper_width)
7916            .max(0.0),
7917        bounds.height(),
7918    )
7919}
7920
7921fn clamp_and_snap_value(value: f64, min: f64, max: f64, step: f64) -> f64 {
7922    let clamped = value.clamp(min, max);
7923    if !step.is_finite() || step <= f64::EPSILON {
7924        return clamped;
7925    }
7926
7927    let snapped = (clamped / step).round() * step;
7928    snapped.clamp(min, max)
7929}
7930
7931fn format_number(value: f64, precision: usize) -> String {
7932    let mut text = format!("{value:.precision$}");
7933    if precision > 0 && text.contains('.') {
7934        while text.ends_with('0') {
7935            text.pop();
7936        }
7937        if text.ends_with('.') {
7938            text.pop();
7939        }
7940    }
7941    if text == "-0" { "0".to_string() } else { text }
7942}
7943
7944fn is_numeric_input_char(ch: char) -> bool {
7945    ch.is_ascii_digit() || matches!(ch, '.' | '-' | '+')
7946}
7947
7948/// Draw an [`IconGlyph`] tinted `color`, centered and fit within `bounds`. Exposed for bespoke
7949/// painters (application chrome) that draw an icon mark without composing an [`Icon`] widget; the
7950/// glyph is painted directly as native SUI path geometry.
7951pub fn draw_glyph(ctx: &mut PaintCtx, glyph: IconGlyph, bounds: Rect, color: Color) {
7952    draw_icon_glyph(ctx, glyph, bounds, color);
7953}
7954
7955pub(crate) fn draw_icon_glyph(ctx: &mut PaintCtx, glyph: IconGlyph, bounds: Rect, color: Color) {
7956    glyph.lucide_icon().paint(ctx, bounds, color);
7957}
7958
7959fn line_path(start: Point, end: Point) -> Path {
7960    let mut builder = PathBuilder::new();
7961    builder.move_to(start).line_to(end);
7962    builder.build()
7963}
7964
7965pub(crate) fn apply_hdr_policy_cap(color: Color, peak_lift: f32) -> Color {
7966    let cap = if peak_lift.is_finite() {
7967        peak_lift.max(0.0)
7968    } else {
7969        return color;
7970    };
7971
7972    Color {
7973        red: color.red.clamp(0.0, cap),
7974        green: color.green.clamp(0.0, cap),
7975        blue: color.blue.clamp(0.0, cap),
7976        ..color
7977    }
7978}
7979
7980pub(crate) fn cap_resolved_hdr_style(style: ResolvedHdrStyle) -> ResolvedHdrStyle {
7981    ResolvedHdrStyle {
7982        color: apply_hdr_policy_cap(style.color, style.peak_lift),
7983        effect: style.effect.map(|effect| ResolvedEffectStyle {
7984            color: apply_hdr_policy_cap(effect.color, style.peak_lift),
7985            ..effect
7986        }),
7987        ..style
7988    }
7989}
7990
7991fn draw_control_frame(
7992    ctx: &mut PaintCtx,
7993    bounds: Rect,
7994    radius: f32,
7995    metrics: ControlMetrics,
7996    background: Color,
7997    border: Color,
7998    focus_ring: Option<Color>,
7999) {
8000    draw_control_shape(
8001        ctx,
8002        bounds,
8003        radius,
8004        physical_pixels(ctx, metrics.border_width),
8005        background,
8006        border,
8007    );
8008
8009    draw_control_focus_ring(ctx, bounds, radius, metrics, focus_ring);
8010}
8011
8012fn draw_choice_control_frame(
8013    ctx: &mut PaintCtx,
8014    bounds: Rect,
8015    radius: f32,
8016    metrics: ControlMetrics,
8017    appearance: ChoiceAppearance,
8018    visuals: ChoiceFrameVisuals,
8019    focus_ring: Option<Color>,
8020) {
8021    if appearance == ChoiceAppearance::Framed {
8022        draw_control_frame(
8023            ctx,
8024            bounds,
8025            radius,
8026            metrics,
8027            visuals.background,
8028            visuals.border,
8029            focus_ring,
8030        );
8031        return;
8032    }
8033
8034    if visuals.background.alpha > f32::EPSILON {
8035        ctx.fill(rounded_rect_path(bounds, radius), visuals.background);
8036    }
8037    draw_control_focus_ring(ctx, bounds, radius, metrics, focus_ring);
8038}
8039
8040fn draw_control_focus_ring(
8041    ctx: &mut PaintCtx,
8042    bounds: Rect,
8043    radius: f32,
8044    metrics: ControlMetrics,
8045    focus_ring: Option<Color>,
8046) {
8047    if let Some(focus_ring) = focus_ring {
8048        let focus_ring_outset = physical_pixels(ctx, metrics.focus_ring_outset);
8049        ctx.stroke(
8050            rounded_rect_path(
8051                bounds.inflate(focus_ring_outset, focus_ring_outset),
8052                radius + focus_ring_outset,
8053            ),
8054            focus_ring,
8055            StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
8056        );
8057    }
8058}
8059
8060fn draw_control_shape(
8061    ctx: &mut PaintCtx,
8062    bounds: Rect,
8063    radius: f32,
8064    border_width: f32,
8065    background: Color,
8066    border: Color,
8067) {
8068    let fill_shape = rounded_rect_path(bounds, radius);
8069    ctx.fill(fill_shape, background);
8070
8071    if border_width > 0.0 {
8072        let inset = border_width * 0.5;
8073        let stroke_shape =
8074            rounded_rect_path(bounds.inflate(-inset, -inset), (radius - inset).max(0.0));
8075        ctx.stroke(stroke_shape, border, StrokeStyle::new(border_width));
8076    }
8077}
8078
8079fn rounded_rect_path(rect: Rect, radius: f32) -> Path {
8080    Path::rounded_rect(rect, radius.min(rect.width().min(rect.height()) * 0.5))
8081}
8082
8083fn checkmark_path(rect: Rect) -> Path {
8084    let mut builder = PathBuilder::new();
8085    builder
8086        .move_to(Point::new(
8087            rect.x() + (rect.width() * 0.18),
8088            rect.y() + (rect.height() * 0.54),
8089        ))
8090        .line_to(Point::new(
8091            rect.x() + (rect.width() * 0.42),
8092            rect.y() + (rect.height() * 0.76),
8093        ))
8094        .line_to(Point::new(
8095            rect.x() + (rect.width() * 0.82),
8096            rect.y() + (rect.height() * 0.28),
8097        ));
8098    builder.build()
8099}
8100
8101fn inset_rect(rect: Rect, padding: Insets) -> Rect {
8102    Rect::new(
8103        rect.x() + padding.left,
8104        rect.y() + padding.top,
8105        (rect.width() - padding.left - padding.right).max(0.0),
8106        (rect.height() - padding.top - padding.bottom).max(0.0),
8107    )
8108}
8109
8110fn choice_control_height(
8111    content_height: f32,
8112    padding: Insets,
8113    baseline_height: f32,
8114    has_explicit_padding: bool,
8115) -> f32 {
8116    let padding_height = if has_explicit_padding {
8117        padding.top + padding.bottom
8118    } else {
8119        0.0
8120    };
8121    (content_height + padding_height).max(baseline_height)
8122}
8123
8124fn default_form_control_height(theme: &DefaultTheme) -> f32 {
8125    let style = theme.body_text_style();
8126    let padding = theme.metrics.text_input_padding;
8127    (style.line_height + padding.top + padding.bottom).max(theme.metrics.min_height)
8128}
8129
8130fn choice_control_layout_padding(padding: Insets, has_explicit_padding: bool) -> Insets {
8131    if has_explicit_padding {
8132        padding
8133    } else {
8134        Insets {
8135            top: 0.0,
8136            bottom: 0.0,
8137            ..padding
8138        }
8139    }
8140}
8141
8142fn indicator_rect(bounds: Rect, padding: Insets, indicator_size: f32) -> Rect {
8143    let x = bounds.x() + padding.left;
8144    let content = inset_rect(bounds, padding);
8145    let y = content.y() + ((content.height() - indicator_size) * 0.5);
8146    Rect::new(x, y, indicator_size, indicator_size)
8147}
8148
8149fn checkbox_label_rect(bounds: Rect, padding: Insets, indicator_size: f32, gap: f32) -> Rect {
8150    let x = bounds.x() + padding.left + indicator_size + gap;
8151    let width = (bounds.width() - padding.left - padding.right - indicator_size - gap).max(0.0);
8152    let content = inset_rect(bounds, padding);
8153    Rect::new(x, content.y(), width, content.height())
8154}
8155
8156fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
8157    if value <= 0.0 {
8158        return 0.0;
8159    }
8160
8161    ctx.dpi().physical_pixels_to_logical(value)
8162}
8163
8164fn rect_is_finite(rect: Rect) -> bool {
8165    rect.x().is_finite()
8166        && rect.y().is_finite()
8167        && rect.width().is_finite()
8168        && rect.height().is_finite()
8169}
8170
8171fn request_selection_change(ctx: &mut EventCtx, change: SelectionChange) {
8172    for owner in change.affected_owners() {
8173        let widget_id = WidgetId::new(owner.get());
8174        ctx.request(InvalidationRequest::new(
8175            InvalidationTarget::Widget(widget_id),
8176            InvalidationKind::Paint,
8177        ));
8178        ctx.request(InvalidationRequest::new(
8179            InvalidationTarget::Widget(widget_id),
8180            InvalidationKind::Semantics,
8181        ));
8182    }
8183}
8184
8185#[cfg(test)]
8186mod tests;