Skip to main content

sui_widgets/
controls.rs

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