Skip to main content

sui_widgets/
controls.rs

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