Skip to main content

sui_widgets/
media.rs

1use crate::binding::Binding;
2use crate::draw::{inset_rect, mix_color};
3use sui_core::{
4    Color, ColorSpace, Event, ImageHandle, KeyState, Oklch, Path, PathBuilder, Point,
5    PointerButton, PointerEventKind, Rect, SemanticsAction, SemanticsNode, SemanticsRole,
6    SemanticsValue, Size, WidgetId,
7};
8use sui_layout::{Constraints, Padding as Insets};
9use sui_reactive::Observable;
10use sui_runtime::{EventCtx, FrameClock, MeasureCtx, PaintCtx, SemanticsCtx, Widget};
11use sui_scene::{Brush, GradientStop, ImageSource, StrokeStyle, WidgetShader};
12use sui_text::{FontFeature, TextAlign, TextStyle};
13
14use crate::frame::{
15    draw_control_shape, draw_focus_ring, physical_pixels, snap_to_pixels, stroke_border,
16};
17use crate::{
18    ControlMetrics, DefaultTheme, Progress, SemanticTone, ThemeDensity, ThemeTextToken,
19    text_align::paint_text_line,
20};
21
22const SIGNAL_METER_PATTERN: [f32; 12] = [
23    0.32, 0.58, 0.86, 0.44, 0.72, 0.96, 0.52, 0.78, 0.38, 0.64, 0.90, 0.48,
24];
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ImageFit {
28    Fill,
29    Contain,
30    Cover,
31    None,
32}
33
34pub struct Image {
35    theme: Box<DefaultTheme>,
36    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
37    image: ImageHandle,
38    label: Option<String>,
39    fit: ImageFit,
40    width: Option<f32>,
41    height: Option<f32>,
42    aspect_ratio: Option<f32>,
43    source_rect: Option<Rect>,
44    tint: Option<Color>,
45    background: Option<Color>,
46    background_reader: Option<Box<dyn Fn() -> Color>>,
47    show_border: bool,
48    corner_radius: Option<f32>,
49    resolved_source_size: Size,
50}
51
52impl Image {
53    pub fn new(image: ImageHandle) -> Self {
54        Self {
55            theme: Box::new(DefaultTheme::default()),
56            theme_reader: None,
57            image,
58            label: None,
59            fit: ImageFit::Contain,
60            width: None,
61            height: None,
62            aspect_ratio: None,
63            source_rect: None,
64            tint: None,
65            background: None,
66            background_reader: None,
67            show_border: true,
68            corner_radius: None,
69            resolved_source_size: Size::new(96.0, 96.0),
70        }
71    }
72
73    pub fn theme(mut self, theme: DefaultTheme) -> Self {
74        self.theme = Box::new(theme);
75        self.theme_reader = None;
76        self
77    }
78
79    pub fn theme_when<F>(mut self, theme: F) -> Self
80    where
81        F: Fn() -> DefaultTheme + 'static,
82    {
83        self.theme_reader = Some(Box::new(theme));
84        self
85    }
86
87    /// Name the image for accessibility and automation, as alternative
88    /// text. An image without a name is decorative.
89    pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
90        self.label = Some(name.into());
91        self
92    }
93
94    pub fn fit(mut self, fit: ImageFit) -> Self {
95        self.fit = fit;
96        self
97    }
98
99    pub fn width(mut self, width: f32) -> Self {
100        self.width = Some(width.max(0.0));
101        self
102    }
103
104    pub fn height(mut self, height: f32) -> Self {
105        self.height = Some(height.max(0.0));
106        self
107    }
108
109    pub fn size(mut self, size: Size) -> Self {
110        self.width = Some(size.width.max(0.0));
111        self.height = Some(size.height.max(0.0));
112        self
113    }
114
115    pub fn aspect_ratio(mut self, aspect_ratio: f32) -> Self {
116        self.aspect_ratio = Some(aspect_ratio.max(0.01));
117        self
118    }
119
120    pub fn source_rect(mut self, source_rect: Rect) -> Self {
121        self.source_rect = Some(source_rect);
122        self
123    }
124
125    pub fn tint(mut self, tint: Color) -> Self {
126        self.tint = Some(tint);
127        self
128    }
129
130    pub fn background(mut self, background: Color) -> Self {
131        self.background = Some(background);
132        self.background_reader = None;
133        self
134    }
135
136    pub fn background_when<F>(mut self, background: F) -> Self
137    where
138        F: Fn() -> Color + 'static,
139    {
140        self.background_reader = Some(Box::new(background));
141        self
142    }
143
144    /// Whether the image draws its frame border; on by default.
145    pub fn show_border(mut self, show_border: bool) -> Self {
146        self.show_border = show_border;
147        self
148    }
149
150    pub fn corner_radius(mut self, corner_radius: f32) -> Self {
151        self.corner_radius = Some(corner_radius.max(0.0));
152        self
153    }
154
155    fn effective_source_size(&self, ctx: &MeasureCtx) -> Size {
156        self.source_rect
157            .map(|rect| rect.size)
158            .or_else(|| ctx.layout().image_size(self.image))
159            .unwrap_or(Size::new(96.0, 96.0))
160    }
161
162    fn resolved_size(&self) -> Size {
163        let aspect_ratio = self.aspect_ratio.unwrap_or_else(|| {
164            (self.resolved_source_size.width / self.resolved_source_size.height.max(1.0)).max(0.01)
165        });
166        match (self.width, self.height) {
167            (Some(width), Some(height)) => Size::new(width, height),
168            (Some(width), None) => Size::new(width, width / aspect_ratio),
169            (None, Some(height)) => Size::new(height * aspect_ratio, height),
170            (None, None) => self.resolved_source_size,
171        }
172    }
173
174    fn resolved_theme(&self) -> DefaultTheme {
175        self.theme_reader
176            .as_ref()
177            .map(|theme| theme())
178            .unwrap_or_else(|| *self.theme)
179    }
180
181    fn resolved_background(&self) -> Option<Color> {
182        self.background_reader
183            .as_ref()
184            .map(|background| background())
185            .or(self.background)
186    }
187
188    fn resolved_corner_radius(&self, theme: &DefaultTheme) -> f32 {
189        self.corner_radius
190            .unwrap_or(theme.metrics.image_corner_radius)
191    }
192}
193
194impl Widget for Image {
195    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
196        self.resolved_source_size = self.effective_source_size(ctx);
197        constraints.clamp(self.resolved_size())
198    }
199
200    fn paint(&self, ctx: &mut PaintCtx) {
201        let bounds = ctx.bounds();
202        let theme = self.resolved_theme();
203        let corner_radius = self.resolved_corner_radius(&theme);
204        let image_rect = fit_rect(bounds, self.resolved_source_size, self.fit);
205        if let Some(background) = self.resolved_background() {
206            ctx.fill(Path::rounded_rect(bounds, corner_radius), background);
207        }
208
209        if corner_radius > 0.0 {
210            ctx.push_clip(Path::rounded_rect(bounds, corner_radius));
211        } else {
212            ctx.push_clip_rect(bounds);
213        }
214        let mut source = ImageSource::new(self.image);
215        if let Some(source_rect) = self.source_rect {
216            source = source.with_source_rect(source_rect);
217        }
218        if let Some(tint) = self.tint {
219            source = source.with_tint(tint);
220        }
221        ctx.draw_image_source(image_rect, source);
222        ctx.pop_clip();
223
224        if self.show_border {
225            stroke_border(
226                ctx,
227                bounds,
228                corner_radius,
229                physical_pixels(ctx, theme.metrics.border_width.max(1.0)),
230                theme.palette.border,
231            );
232        }
233    }
234
235    fn semantics(&self, ctx: &mut SemanticsCtx) {
236        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Image, ctx.bounds());
237        node.name = self.label.clone();
238        ctx.push(node);
239    }
240}
241
242pub struct SignalMeter {
243    theme: Box<DefaultTheme>,
244    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
245    name: String,
246    description: Option<String>,
247    active: bool,
248    active_reader: Option<Box<dyn Fn() -> bool>>,
249    level: Option<f32>,
250    level_reader: Option<Box<dyn Fn() -> f32>>,
251    tone: SemanticTone,
252    tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
253    bars: usize,
254    size: Option<Size>,
255    gap: Option<f32>,
256}
257
258impl SignalMeter {
259    pub fn new(name: impl Into<String>) -> Self {
260        Self {
261            theme: Box::new(DefaultTheme::default()),
262            theme_reader: None,
263            name: name.into(),
264            description: None,
265            active: false,
266            active_reader: None,
267            level: None,
268            level_reader: None,
269            tone: SemanticTone::Accent,
270            tone_reader: None,
271            bars: 12,
272            size: None,
273            gap: None,
274        }
275    }
276
277    pub fn theme(mut self, theme: DefaultTheme) -> Self {
278        self.theme = Box::new(theme);
279        self.theme_reader = None;
280        self
281    }
282
283    pub fn theme_when<F>(mut self, theme: F) -> Self
284    where
285        F: Fn() -> DefaultTheme + 'static,
286    {
287        self.theme_reader = Some(Box::new(theme));
288        self
289    }
290
291    pub fn description(mut self, description: impl Into<String>) -> Self {
292        self.description = Some(description.into());
293        self
294    }
295
296    pub fn active(mut self, active: bool) -> Self {
297        self.active = active;
298        self.active_reader = None;
299        self
300    }
301
302    pub fn active_when<F>(mut self, active: F) -> Self
303    where
304        F: Fn() -> bool + 'static,
305    {
306        self.active_reader = Some(Box::new(active));
307        self
308    }
309
310    /// Set the normalized signal level used to light the meter bars.
311    ///
312    /// Values outside `0.0..=1.0`, including non-finite values, are sanitized
313    /// when the widget paints and publishes semantics. [`Self::active`] still
314    /// controls whether reached bars use the semantic tone or the idle color.
315    pub fn level(mut self, level: f32) -> Self {
316        self.level = Some(level);
317        self.level_reader = None;
318        self
319    }
320
321    /// Read the normalized signal level when the meter paints or publishes semantics.
322    ///
323    /// The owner remains responsible for waking and invalidating the UI when the
324    /// underlying signal changes.
325    pub fn level_when<F>(mut self, level: F) -> Self
326    where
327        F: Fn() -> f32 + 'static,
328    {
329        self.level_reader = Some(Box::new(level));
330        self
331    }
332
333    pub fn tone(mut self, tone: SemanticTone) -> Self {
334        self.tone = tone;
335        self.tone_reader = None;
336        self
337    }
338
339    pub fn tone_when<F>(mut self, tone: F) -> Self
340    where
341        F: Fn() -> SemanticTone + 'static,
342    {
343        self.tone_reader = Some(Box::new(tone));
344        self
345    }
346
347    pub fn bars(mut self, bars: usize) -> Self {
348        self.bars = bars.clamp(3, 64);
349        self
350    }
351
352    pub fn size(mut self, size: Size) -> Self {
353        self.size = Some(Size::new(size.width.max(0.0), size.height.max(0.0)));
354        self
355    }
356
357    pub fn gap(mut self, gap: f32) -> Self {
358        self.gap = Some(gap.max(0.0));
359        self
360    }
361
362    fn resolved_theme(&self) -> DefaultTheme {
363        self.theme_reader
364            .as_ref()
365            .map(|theme| theme())
366            .unwrap_or_else(|| *self.theme)
367    }
368
369    fn is_active(&self) -> bool {
370        self.active_reader
371            .as_ref()
372            .map(|active| active())
373            .unwrap_or(self.active)
374    }
375
376    fn resolved_level(&self) -> Option<f32> {
377        self.level_reader
378            .as_ref()
379            .map(|level| level())
380            .or(self.level)
381            .map(|level| {
382                if level.is_finite() {
383                    level.clamp(0.0, 1.0)
384                } else {
385                    0.0
386                }
387            })
388    }
389
390    fn resolved_tone(&self) -> SemanticTone {
391        self.tone_reader
392            .as_ref()
393            .map(|tone| tone())
394            .unwrap_or(self.tone)
395    }
396
397    fn bar_count(&self) -> usize {
398        self.bars.clamp(3, 64)
399    }
400
401    fn resolved_size(&self) -> Size {
402        self.size.unwrap_or(Size::new(76.0, 16.0))
403    }
404}
405
406fn signal_meter_bar_layout(
407    width: f32,
408    requested_bars: usize,
409    requested_gap: f32,
410) -> (usize, f32, f32) {
411    let width = if width.is_finite() {
412        width.max(0.0)
413    } else {
414        0.0
415    };
416    // At very narrow constraints, keeping every configured bar at the old
417    // one-pixel minimum painted beyond the widget bounds. Prefer fewer visible
418    // bars so the meter remains a contained, useful signal.
419    let bars = requested_bars.max(1).min(width.floor().max(1.0) as usize);
420    let max_gap = if bars > 1 {
421        ((width - bars as f32).max(0.0) / (bars - 1) as f32).max(0.0)
422    } else {
423        0.0
424    };
425    let gap = requested_gap.max(0.0).min(max_gap);
426    let total_gap = gap * bars.saturating_sub(1) as f32;
427    let bar_width = ((width - total_gap) / bars as f32).max(0.0);
428    (bars, gap, bar_width)
429}
430
431impl Widget for SignalMeter {
432    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
433        constraints.clamp(self.resolved_size())
434    }
435
436    fn paint(&self, ctx: &mut PaintCtx) {
437        let theme = self.resolved_theme();
438        let bounds = ctx.bounds();
439        let active = self.is_active();
440        let (bars, gap, bar_w) =
441            signal_meter_bar_layout(bounds.width(), self.bar_count(), self.gap.unwrap_or(3.0));
442        let reached_bars = self
443            .resolved_level()
444            .map(|level| (level * bars as f32).ceil() as usize);
445        let tone = theme.semantic_tone_color(self.resolved_tone());
446        let idle_fill = theme.palette.text_muted.with_alpha(0.48);
447        let min_h = (bounds.height() * if active { 0.20 } else { 0.12 }).max(1.0);
448        let max_h = bounds.height().max(1.0);
449        for index in 0..bars {
450            let pattern = SIGNAL_METER_PATTERN[index % SIGNAL_METER_PATTERN.len()];
451            let level = if active {
452                pattern
453            } else {
454                (pattern * 0.26).max(0.12)
455            };
456            let bar_h = (min_h + (max_h - min_h) * level).min(max_h);
457            let x = bounds.x() + index as f32 * (bar_w + gap);
458            let y = bounds.max_y() - bar_h;
459            let rect = Rect::new(x, y, bar_w, bar_h);
460            let reached = reached_bars.is_none_or(|reached| index < reached);
461            let fill = if active && reached { tone } else { idle_fill };
462            ctx.fill(Path::rounded_rect(rect, (bar_w * 0.5).min(3.0)), fill);
463        }
464    }
465
466    fn semantics(&self, ctx: &mut SemanticsCtx) {
467        let level = self.resolved_level();
468        let mut node = SemanticsNode::new(
469            ctx.widget_id(),
470            if level.is_some() {
471                SemanticsRole::ProgressBar
472            } else {
473                SemanticsRole::GenericContainer
474            },
475            ctx.bounds(),
476        );
477        node.name = Some(self.name.clone());
478        node.description = self.description.clone();
479        node.value = Some(match level {
480            Some(level) => SemanticsValue::Range {
481                value: level as f64,
482                min: 0.0,
483                max: 1.0,
484            },
485            None => SemanticsValue::Text(if self.is_active() {
486                "active".to_string()
487            } else {
488                "idle".to_string()
489            }),
490        });
491        ctx.push(node);
492    }
493}
494
495pub struct ColorSwatch {
496    theme: Box<DefaultTheme>,
497    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
498    name: String,
499    color: Color,
500    color_reader: Option<Box<dyn Fn() -> Color>>,
501    size: Option<Size>,
502    hovered: bool,
503    pressed: bool,
504    hover_animation: AnimatedScalar,
505    press_animation: AnimatedScalar,
506    focus_animation: AnimatedScalar,
507    read_only: bool,
508    on_press: Option<Box<dyn FnMut(Color)>>,
509    on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, Color)>>,
510}
511
512impl ColorSwatch {
513    pub fn new(name: impl Into<String>, color: Color) -> Self {
514        Self {
515            theme: Box::new(DefaultTheme::default()),
516            theme_reader: None,
517            name: name.into(),
518            color,
519            color_reader: None,
520            size: None,
521            hovered: false,
522            pressed: false,
523            hover_animation: AnimatedScalar::new(0.0),
524            press_animation: AnimatedScalar::new(0.0),
525            focus_animation: AnimatedScalar::new(0.0),
526            read_only: false,
527            on_press: None,
528            on_press_with_ctx: None,
529        }
530    }
531
532    pub fn theme(mut self, theme: DefaultTheme) -> Self {
533        self.theme = Box::new(theme);
534        self.theme_reader = None;
535        self
536    }
537
538    pub fn theme_when<F>(mut self, theme: F) -> Self
539    where
540        F: Fn() -> DefaultTheme + 'static,
541    {
542        self.theme_reader = Some(Box::new(theme));
543        self
544    }
545
546    pub fn size(mut self, size: Size) -> Self {
547        self.size = Some(Size::new(size.width.max(24.0), size.height.max(24.0)));
548        self
549    }
550
551    pub fn color_when<F>(mut self, color: F) -> Self
552    where
553        F: Fn() -> Color + 'static,
554    {
555        self.color_reader = Some(Box::new(color));
556        self
557    }
558
559    pub fn read_only(mut self, read_only: bool) -> Self {
560        self.read_only = read_only;
561        self
562    }
563
564    pub fn is_read_only(&self) -> bool {
565        self.read_only
566    }
567
568    pub fn on_press<F>(mut self, on_press: F) -> Self
569    where
570        F: FnMut(Color) + 'static,
571    {
572        self.on_press = Some(Box::new(on_press));
573        self
574    }
575
576    pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
577    where
578        F: FnMut(&mut EventCtx, Color) + 'static,
579    {
580        self.on_press_with_ctx = Some(Box::new(on_press));
581        self
582    }
583
584    fn current_color(&self) -> Color {
585        self.color_reader
586            .as_ref()
587            .map(|reader| reader())
588            .unwrap_or(self.color)
589    }
590
591    fn resolved_theme(&self) -> DefaultTheme {
592        self.theme_reader
593            .as_ref()
594            .map(|theme| theme())
595            .unwrap_or_else(|| *self.theme)
596    }
597
598    fn activate(&mut self, ctx: &mut EventCtx) {
599        let color = self.current_color();
600        if let Some(on_press) = &mut self.on_press {
601            on_press(color);
602        }
603        if let Some(on_press) = &mut self.on_press_with_ctx {
604            on_press(ctx, color);
605        }
606    }
607
608    fn resolved_size(&self, theme: &DefaultTheme) -> Size {
609        self.size.unwrap_or(Size::new(
610            theme.metrics.color_swatch_width,
611            theme.metrics.color_swatch_height,
612        ))
613    }
614
615    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
616        if self.hovered != hovered {
617            let theme = self.resolved_theme();
618            self.hovered = hovered;
619            set_hover_animation_target(
620                &mut self.hover_animation,
621                hovered as u8 as f32,
622                &theme,
623                ctx,
624            );
625            ctx.request_paint();
626            ctx.request_semantics();
627        }
628    }
629
630    fn set_pressed(&mut self, pressed: bool, ctx: &mut EventCtx) {
631        if self.pressed != pressed {
632            let theme = self.resolved_theme();
633            self.pressed = pressed;
634            set_press_animation_target(
635                &mut self.press_animation,
636                pressed as u8 as f32,
637                &theme,
638                ctx,
639            );
640            ctx.request_paint();
641            ctx.request_semantics();
642        }
643    }
644}
645
646impl Widget for ColorSwatch {
647    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
648        if self.read_only {
649            if matches!(
650                event,
651                Event::Pointer(pointer)
652                    if matches!(
653                        pointer.kind,
654                        PointerEventKind::Move
655                            | PointerEventKind::Leave
656                            | PointerEventKind::Cancel
657                    )
658            ) {
659                ctx.request_paint();
660                ctx.request_semantics();
661            }
662            return;
663        }
664
665        match event {
666            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
667                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
668            }
669            Event::Pointer(pointer)
670                if pointer.kind == PointerEventKind::Down
671                    && pointer.button == Some(PointerButton::Primary)
672                    && ctx.bounds().contains(pointer.position) =>
673            {
674                self.set_pressed(true, ctx);
675                self.set_hovered(true, ctx);
676                ctx.request_focus();
677                ctx.request_pointer_capture(pointer.pointer_id);
678                ctx.set_handled();
679            }
680            Event::Pointer(pointer)
681                if pointer.kind == PointerEventKind::Up
682                    && pointer.button == Some(PointerButton::Primary) =>
683            {
684                let hovered = ctx.bounds().contains(pointer.position);
685                if self.pressed && hovered {
686                    self.activate(ctx);
687                }
688                self.set_pressed(false, ctx);
689                self.set_hovered(hovered, ctx);
690                ctx.release_pointer_capture(pointer.pointer_id);
691                ctx.set_handled();
692            }
693            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
694                self.set_hovered(false, ctx);
695            }
696            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
697                if self.pressed {
698                    self.set_pressed(false, ctx);
699                    self.set_hovered(false, ctx);
700                    ctx.release_pointer_capture(pointer.pointer_id);
701                }
702            }
703            Event::Keyboard(key)
704                if ctx.is_focused()
705                    && key.state == KeyState::Pressed
706                    && matches!(key.key.as_str(), "Enter" | " ") =>
707            {
708                self.activate(ctx);
709                ctx.request_paint();
710                ctx.request_semantics();
711                ctx.set_handled();
712            }
713            _ => {}
714        }
715    }
716
717    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
718        let theme = self.resolved_theme();
719        constraints.clamp(self.resolved_size(&theme))
720    }
721
722    fn paint(&self, ctx: &mut PaintCtx) {
723        let theme = self.resolved_theme();
724        let metrics = theme.metrics;
725        let palette = theme.palette;
726        let pressed_offset = self.press_animation.get(ctx) * theme.interaction.pressed_offset;
727        let body = Rect::new(
728            ctx.bounds().x(),
729            ctx.bounds().y() + pressed_offset,
730            ctx.bounds().width(),
731            (ctx.bounds().height() - pressed_offset).max(0.0),
732        );
733        let outer_radius = metrics.corner_radius.min(body.height() * 0.5);
734        let inner_inset = metrics.color_swatch_inner_inset + pressed_offset * 0.5;
735        let inner_radius = (outer_radius - inner_inset).max(0.0);
736        let inner_body = inset_rect(body, Insets::all(inner_inset));
737        let color = self.current_color();
738
739        if self.focus_animation.get(ctx) > 0.0 {
740            draw_focus_ring(
741                ctx,
742                ctx.bounds(),
743                outer_radius,
744                metrics,
745                palette.focus_ring.with_alpha(self.focus_animation.get(ctx)),
746            );
747        }
748
749        if self.press_animation.get(ctx) > 0.0 {
750            ctx.fill(
751                Path::rounded_rect(ctx.bounds(), outer_radius),
752                mix_color(
753                    palette.control_hover,
754                    palette.control_active,
755                    theme.interaction.pressed_blend * self.press_animation.get(ctx),
756                ),
757            );
758        } else if self.hover_animation.get(ctx) > 0.0 {
759            ctx.fill(
760                Path::rounded_rect(ctx.bounds(), outer_radius),
761                palette
762                    .control_hover
763                    .with_alpha(self.hover_animation.get(ctx) * palette.control_hover.alpha),
764            );
765        }
766
767        draw_rounded_checkerboard(
768            ctx,
769            inner_body,
770            inner_radius,
771            metrics.color_swatch_checker_size,
772            &theme,
773        );
774        ctx.fill(Path::rounded_rect(inner_body, inner_radius), color);
775        stroke_border(
776            ctx,
777            body,
778            outer_radius,
779            physical_pixels(ctx, metrics.border_width.max(1.0)),
780            if ctx.is_focused() {
781                palette.border_focus
782            } else if self.hovered || self.hover_animation.get(ctx) > 0.0 {
783                palette.border_hover
784            } else if self.read_only {
785                palette
786                    .border
787                    .with_alpha(theme.interaction.disabled_opacity)
788            } else {
789                palette.border
790            },
791        );
792    }
793
794    fn semantics(&self, ctx: &mut SemanticsCtx) {
795        let mut node =
796            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ColorSwatch, ctx.bounds());
797        node.name = Some(self.name.clone());
798        node.state.focused = ctx.is_focused();
799        node.value = Some(SemanticsValue::Text(format_color(self.current_color())));
800        if !self.read_only {
801            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
802        }
803        ctx.push(node);
804    }
805
806    fn accepts_focus(&self) -> bool {
807        !self.read_only
808    }
809
810    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
811        let theme = self.resolved_theme();
812        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
813        ctx.request_paint();
814        ctx.request_semantics();
815    }
816}
817
818#[derive(Debug, Clone, PartialEq)]
819pub struct ColorPaletteSwatch {
820    name: String,
821    color: Color,
822}
823
824impl ColorPaletteSwatch {
825    pub fn new(name: impl Into<String>, color: Color) -> Self {
826        Self {
827            name: name.into(),
828            color,
829        }
830    }
831
832    pub fn name(&self) -> &str {
833        &self.name
834    }
835
836    pub const fn color(&self) -> Color {
837        self.color
838    }
839}
840
841pub struct ColorPalette {
842    theme: Box<DefaultTheme>,
843    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
844    enabled: Binding<bool>,
845    name: String,
846    swatches: Vec<ColorPaletteSwatch>,
847    selected: Option<usize>,
848    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
849    hovered: Option<usize>,
850    hover_visual: Option<usize>,
851    pressed: Option<usize>,
852    press_visual: Option<usize>,
853    hover_animation: AnimatedScalar,
854    press_animation: AnimatedScalar,
855    focus_animation: AnimatedScalar,
856    columns: usize,
857    swatch_size: Option<f32>,
858    gap: Option<f32>,
859    on_change: Option<Box<dyn FnMut(usize, String, Color)>>,
860    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String, Color)>>,
861}
862
863impl ColorPalette {
864    pub fn new(name: impl Into<String>) -> Self {
865        Self {
866            theme: Box::new(DefaultTheme::default()),
867            theme_reader: None,
868            enabled: Binding::new(true),
869            name: name.into(),
870            swatches: Vec::new(),
871            selected: None,
872            selected_reader: None,
873            hovered: None,
874            hover_visual: None,
875            pressed: None,
876            press_visual: None,
877            hover_animation: AnimatedScalar::new(0.0),
878            press_animation: AnimatedScalar::new(0.0),
879            focus_animation: AnimatedScalar::new(0.0),
880            columns: 8,
881            swatch_size: None,
882            gap: None,
883            on_change: None,
884            on_change_with_ctx: None,
885        }
886    }
887
888    pub fn theme(mut self, theme: DefaultTheme) -> Self {
889        self.theme = Box::new(theme);
890        self.theme_reader = None;
891        self
892    }
893
894    pub fn theme_when<F>(mut self, theme: F) -> Self
895    where
896        F: Fn() -> DefaultTheme + 'static,
897    {
898        self.theme_reader = Some(Box::new(theme));
899        self
900    }
901
902    /// Whether the user can use the widget. Disabled, it ignores input,
903    /// can't take focus, draws in the theme's disabled colors, and tells
904    /// assistive technology it and its items are unavailable.
905    pub fn enabled(mut self, enabled: bool) -> Self {
906        self.enabled.set(enabled);
907        self
908    }
909
910    /// [`Self::enabled`], read whenever the widget needs it.
911    pub fn enabled_when<F>(mut self, enabled: F) -> Self
912    where
913        F: Fn() -> bool + 'static,
914    {
915        self.enabled.set_when(enabled);
916        self
917    }
918
919    /// [`Self::enabled`], following an observable and repainting when it
920    /// changes.
921    pub fn enabled_from<O>(mut self, enabled: O) -> Self
922    where
923        O: Observable<bool> + 'static,
924    {
925        self.enabled.set_from(enabled);
926        self
927    }
928
929    pub fn is_enabled(&self) -> bool {
930        self.enabled.get()
931    }
932
933    /// The theme to paint with: the disabled look while the widget is
934    /// disabled.
935    fn paint_theme(&self) -> DefaultTheme {
936        let theme = self.resolved_theme();
937        if self.enabled.get() {
938            theme
939        } else {
940            theme.for_disabled_control()
941        }
942    }
943
944    pub fn swatch(mut self, swatch: ColorPaletteSwatch) -> Self {
945        self.swatches.push(swatch);
946        self
947    }
948
949    pub fn swatches<I>(mut self, swatches: I) -> Self
950    where
951        I: IntoIterator<Item = ColorPaletteSwatch>,
952    {
953        self.swatches.extend(swatches);
954        self
955    }
956
957    /// Select item `index`, or nothing with `None`; `selected(2)` and
958    /// `selected(None)` both work.
959    pub fn selected(mut self, selected: impl Into<Option<usize>>) -> Self {
960        let selected = selected.into();
961        self.selected = selected;
962        self.selected_reader = None;
963        self
964    }
965
966    pub fn selected_when<F>(mut self, selected: F) -> Self
967    where
968        F: Fn() -> Option<usize> + 'static,
969    {
970        self.selected_reader = Some(Box::new(selected));
971        self
972    }
973
974    pub fn columns(mut self, columns: usize) -> Self {
975        self.columns = columns.max(1);
976        self
977    }
978
979    pub fn swatch_size(mut self, size: f32) -> Self {
980        self.swatch_size = Some(size.max(18.0));
981        self
982    }
983
984    pub fn gap(mut self, gap: f32) -> Self {
985        self.gap = Some(gap.max(0.0));
986        self
987    }
988
989    pub fn on_change<F>(mut self, on_change: F) -> Self
990    where
991        F: FnMut(usize, String, Color) + 'static,
992    {
993        self.on_change = Some(Box::new(on_change));
994        self
995    }
996
997    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
998    where
999        F: FnMut(&mut EventCtx, usize, String, Color) + 'static,
1000    {
1001        self.on_change_with_ctx = Some(Box::new(on_change));
1002        self
1003    }
1004
1005    pub fn selected_index(&self) -> Option<usize> {
1006        self.current_selected()
1007    }
1008
1009    fn current_selected(&self) -> Option<usize> {
1010        self.selected_reader
1011            .as_ref()
1012            .map(|selected| selected())
1013            .unwrap_or(self.selected)
1014            .filter(|index| *index < self.swatches.len())
1015    }
1016
1017    fn resolved_theme(&self) -> DefaultTheme {
1018        self.theme_reader
1019            .as_ref()
1020            .map(|theme| theme())
1021            .unwrap_or_else(|| *self.theme)
1022    }
1023
1024    fn grid_columns(&self) -> usize {
1025        self.columns.max(1).min(self.swatches.len().max(1))
1026    }
1027
1028    fn grid_rows(&self) -> usize {
1029        if self.swatches.is_empty() {
1030            1
1031        } else {
1032            self.swatches.len().div_ceil(self.grid_columns())
1033        }
1034    }
1035
1036    fn resolved_swatch_size(&self, theme: &DefaultTheme) -> f32 {
1037        self.swatch_size
1038            .unwrap_or(theme.metrics.color_palette_swatch_size)
1039    }
1040
1041    fn resolved_gap(&self, theme: &DefaultTheme) -> f32 {
1042        self.gap.unwrap_or(theme.metrics.color_palette_gap)
1043    }
1044
1045    fn swatch_rect(&self, bounds: Rect, index: usize, theme: &DefaultTheme) -> Option<Rect> {
1046        if index >= self.swatches.len() {
1047            return None;
1048        }
1049
1050        let swatch_size = self.resolved_swatch_size(theme);
1051        let gap = self.resolved_gap(theme);
1052        let columns = self.grid_columns();
1053        let column = index % columns;
1054        let row = index / columns;
1055        let x = bounds.x() + column as f32 * (swatch_size + gap);
1056        let y = bounds.y() + row as f32 * (swatch_size + gap);
1057        let available_width = (bounds.max_x() - x).max(0.0);
1058        let available_height = (bounds.max_y() - y).max(0.0);
1059        let rect = Rect::new(
1060            x,
1061            y,
1062            swatch_size.min(available_width),
1063            swatch_size.min(available_height),
1064        );
1065        (!rect.is_empty()).then_some(rect)
1066    }
1067
1068    fn swatch_at(&self, bounds: Rect, position: Point, theme: &DefaultTheme) -> Option<usize> {
1069        self.swatches.iter().enumerate().find_map(|(index, _)| {
1070            self.swatch_rect(bounds, index, theme)
1071                .filter(|rect| rect.contains(position))
1072                .map(|_| index)
1073        })
1074    }
1075
1076    fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
1077        if self.swatches.is_empty() {
1078            return;
1079        }
1080
1081        let index = index.min(self.swatches.len() - 1);
1082        self.selected = Some(index);
1083        let swatch = &self.swatches[index];
1084        let name = swatch.name.clone();
1085        let color = swatch.color;
1086        if let Some(on_change) = &mut self.on_change {
1087            on_change(index, name.clone(), color);
1088        }
1089        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
1090            on_change_with_ctx(ctx, index, name, color);
1091        }
1092    }
1093
1094    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
1095        if self.swatches.is_empty() {
1096            return;
1097        }
1098
1099        let current = self.current_selected().unwrap_or(0) as isize;
1100        let last = self.swatches.len() as isize - 1;
1101        let next = (current + delta).clamp(0, last) as usize;
1102        self.set_hovered(Some(next), ctx);
1103        self.activate(ctx, next);
1104    }
1105
1106    fn selected_value(&self) -> Option<String> {
1107        self.current_selected()
1108            .and_then(|index| self.swatches.get(index))
1109            .map(|swatch| format!("{} {}", swatch.name, format_color(swatch.color)))
1110    }
1111
1112    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
1113        if self.hovered == hovered {
1114            return;
1115        }
1116        let theme = self.resolved_theme();
1117        self.hovered = hovered;
1118        if let Some(index) = hovered {
1119            self.hover_visual = Some(index);
1120            self.hover_animation = AnimatedScalar::new(0.0);
1121            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
1122        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
1123            self.hover_visual = None;
1124        }
1125        ctx.request_paint();
1126        ctx.request_semantics();
1127    }
1128
1129    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
1130        if self.pressed == pressed {
1131            return;
1132        }
1133        let theme = self.resolved_theme();
1134        self.pressed = pressed;
1135        if let Some(index) = pressed {
1136            self.press_visual = Some(index);
1137            self.press_animation = AnimatedScalar::new(0.0);
1138            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
1139        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
1140            self.press_visual = None;
1141        }
1142        ctx.request_paint();
1143        ctx.request_semantics();
1144    }
1145
1146    fn hover_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
1147        if self.hover_visual == Some(index) {
1148            self.hover_animation.get(clock)
1149        } else {
1150            0.0
1151        }
1152    }
1153
1154    fn press_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
1155        if self.press_visual == Some(index) {
1156            self.press_animation.get(clock)
1157        } else {
1158            0.0
1159        }
1160    }
1161}
1162
1163impl Widget for ColorPalette {
1164    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1165        if !self.enabled.get() {
1166            // Disabled, the widget takes no input, but it lets go of a
1167            // pointer it captured while enabled.
1168            if let Event::Pointer(pointer) = event
1169                && pointer.kind == PointerEventKind::Up
1170            {
1171                ctx.release_pointer_capture(pointer.pointer_id);
1172            }
1173            return;
1174        }
1175        match event {
1176            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1177                let theme = self.resolved_theme();
1178                self.set_hovered(self.swatch_at(ctx.bounds(), pointer.position, &theme), ctx);
1179            }
1180            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
1181                self.set_hovered(None, ctx);
1182            }
1183            Event::Pointer(pointer)
1184                if pointer.kind == PointerEventKind::Down
1185                    && pointer.button == Some(PointerButton::Primary) =>
1186            {
1187                let theme = self.resolved_theme();
1188                let hovered = self.swatch_at(ctx.bounds(), pointer.position, &theme);
1189                self.set_hovered(hovered, ctx);
1190                self.set_pressed(hovered, ctx);
1191                if self.hovered.is_some() {
1192                    ctx.request_focus();
1193                    ctx.request_pointer_capture(pointer.pointer_id);
1194                    ctx.set_handled();
1195                }
1196            }
1197            Event::Pointer(pointer)
1198                if pointer.kind == PointerEventKind::Up
1199                    && pointer.button == Some(PointerButton::Primary) =>
1200            {
1201                let theme = self.resolved_theme();
1202                let hovered = self.swatch_at(ctx.bounds(), pointer.position, &theme);
1203                if let Some(index) = self
1204                    .pressed
1205                    .zip(hovered)
1206                    .filter(|(left, right)| left == right)
1207                    .map(|(index, _)| index)
1208                {
1209                    self.activate(ctx, index);
1210                }
1211                self.set_hovered(hovered, ctx);
1212                self.set_pressed(None, ctx);
1213                ctx.release_pointer_capture(pointer.pointer_id);
1214                ctx.set_handled();
1215            }
1216            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1217                if self.pressed.is_some() {
1218                    self.set_pressed(None, ctx);
1219                    self.set_hovered(None, ctx);
1220                    ctx.release_pointer_capture(pointer.pointer_id);
1221                    ctx.set_handled();
1222                }
1223            }
1224            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1225                let columns = self.grid_columns() as isize;
1226                match key.key.as_str() {
1227                    "ArrowLeft" => self.move_selection(-1, ctx),
1228                    "ArrowRight" => self.move_selection(1, ctx),
1229                    "ArrowUp" => self.move_selection(-columns, ctx),
1230                    "ArrowDown" => self.move_selection(columns, ctx),
1231                    "Home" => self.activate(ctx, 0),
1232                    "End" if !self.swatches.is_empty() => {
1233                        self.activate(ctx, self.swatches.len() - 1);
1234                    }
1235                    "Enter" | " " => {
1236                        if let Some(selected) = self.current_selected().or(Some(0)) {
1237                            self.activate(ctx, selected);
1238                        }
1239                    }
1240                    _ => return,
1241                }
1242                ctx.request_paint();
1243                ctx.request_semantics();
1244                ctx.set_handled();
1245            }
1246            _ => {}
1247        }
1248    }
1249
1250    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1251        let theme = self.resolved_theme();
1252        let swatch_size = self.resolved_swatch_size(&theme);
1253        let gap = self.resolved_gap(&theme);
1254        let columns = self.grid_columns() as f32;
1255        let rows = self.grid_rows() as f32;
1256        constraints.clamp(Size::new(
1257            columns * swatch_size + (columns - 1.0).max(0.0) * gap,
1258            rows * swatch_size + (rows - 1.0).max(0.0) * gap,
1259        ))
1260    }
1261
1262    fn paint(&self, ctx: &mut PaintCtx) {
1263        self.enabled.observe(|source| {
1264            ctx.observe(source);
1265        });
1266        let theme = self.paint_theme();
1267        let palette = theme.palette;
1268        let metrics = theme.metrics;
1269        let interaction = theme.interaction;
1270        let swatch_size = self.resolved_swatch_size(&theme);
1271        let radius = metrics.corner_radius.min(swatch_size * 0.25);
1272        let selected = self.current_selected();
1273
1274        if self.focus_animation.get(ctx) > 0.0 {
1275            draw_focus_ring(
1276                ctx,
1277                ctx.bounds(),
1278                radius,
1279                metrics,
1280                palette.focus_ring.with_alpha(self.focus_animation.get(ctx)),
1281            );
1282        }
1283
1284        for (index, swatch) in self.swatches.iter().enumerate() {
1285            let Some(rect) = self.swatch_rect(ctx.bounds(), index, &theme) else {
1286                continue;
1287            };
1288            let selected = selected == Some(index);
1289            let hovered = self.hovered == Some(index);
1290            let hover_amount = self.hover_amount_for(index, ctx);
1291            let press_amount = self.press_amount_for(index, ctx);
1292            let pressed_offset = press_amount * interaction.pressed_offset;
1293            let body = Rect::new(
1294                rect.x(),
1295                rect.y() + pressed_offset,
1296                rect.width(),
1297                (rect.height() - pressed_offset).max(0.0),
1298            );
1299            let ring = if selected {
1300                palette.selection_border
1301            } else if hovered || hover_amount > 0.0 || press_amount > 0.0 {
1302                palette.border_hover
1303            } else {
1304                palette.border
1305            };
1306            let ring_width = physical_pixels(
1307                ctx,
1308                if selected {
1309                    metrics.border_width.max(1.0) + 1.0
1310                } else {
1311                    metrics.border_width.max(1.0)
1312                },
1313            );
1314            let fill_inset = if selected {
1315                metrics.color_palette_selected_swatch_inset
1316            } else {
1317                metrics.color_palette_swatch_inset
1318            } + pressed_offset * 0.5;
1319            let fill_rect = inset_rect(body, Insets::all(fill_inset));
1320
1321            let base_background = if selected {
1322                palette.selection
1323            } else {
1324                palette.control
1325            };
1326            let hover_background = if hover_amount > 0.0 {
1327                mix_color(
1328                    base_background,
1329                    palette.control_hover,
1330                    interaction.hover_blend * hover_amount,
1331                )
1332            } else {
1333                base_background
1334            };
1335            let background = if press_amount > 0.0 {
1336                mix_color(
1337                    hover_background,
1338                    palette.control_active,
1339                    interaction.pressed_blend * press_amount,
1340                )
1341            } else {
1342                hover_background
1343            };
1344
1345            if selected {
1346                ctx.fill(Path::rounded_rect(body, radius), background);
1347            } else if hover_amount > 0.0 || press_amount > 0.0 {
1348                ctx.fill(Path::rounded_rect(rect, radius), background);
1349            }
1350            draw_rounded_checkerboard(
1351                ctx,
1352                fill_rect,
1353                (radius - fill_inset).max(0.0),
1354                metrics.color_palette_checker_size,
1355                &theme,
1356            );
1357            ctx.fill(
1358                Path::rounded_rect(fill_rect, (radius - fill_inset).max(0.0)),
1359                swatch.color,
1360            );
1361            stroke_border(ctx, body, radius, ring_width, ring);
1362        }
1363    }
1364
1365    fn semantics(&self, ctx: &mut SemanticsCtx) {
1366        self.enabled.observe(|source| {
1367            ctx.observe(source);
1368        });
1369        let enabled = self.enabled.get();
1370        let mut node = SemanticsNode::new(
1371            ctx.widget_id(),
1372            SemanticsRole::GenericContainer,
1373            ctx.bounds(),
1374        );
1375        node.name = Some(self.name.clone());
1376        node.value = self.selected_value().map(SemanticsValue::Text);
1377        node.state.focused = ctx.is_focused();
1378        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
1379        if !enabled {
1380            node.state.disabled = true;
1381            node.actions.clear();
1382        }
1383        ctx.push(node);
1384
1385        let selected = self.current_selected();
1386        let theme = self.resolved_theme();
1387        for (index, swatch) in self.swatches.iter().enumerate() {
1388            let Some(rect) = self.swatch_rect(ctx.bounds(), index, &theme) else {
1389                continue;
1390            };
1391            let mut node = SemanticsNode::new(
1392                color_palette_swatch_id(ctx.widget_id(), index),
1393                SemanticsRole::ColorSwatch,
1394                rect,
1395            );
1396            node.parent = Some(ctx.widget_id());
1397            node.name = Some(swatch.name.clone());
1398            node.value = Some(SemanticsValue::Text(format_color(swatch.color)));
1399            node.state.hovered = self.hovered == Some(index);
1400            node.state.selected = selected == Some(index);
1401            node.actions = vec![SemanticsAction::Activate];
1402            if !enabled {
1403                node.state.disabled = true;
1404                node.actions.clear();
1405            }
1406            ctx.push(node);
1407        }
1408    }
1409
1410    fn accepts_focus(&self) -> bool {
1411        self.enabled.get() && (!self.swatches.is_empty())
1412    }
1413
1414    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1415        let theme = self.resolved_theme();
1416        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1417        ctx.request_paint();
1418        ctx.request_semantics();
1419    }
1420}
1421
1422fn color_palette_swatch_id(parent: WidgetId, index: usize) -> WidgetId {
1423    const TAG: u64 = 7_u64 << 50;
1424    const LOW_MASK: u64 = (1_u64 << 50) - 1;
1425
1426    WidgetId::new(
1427        TAG | (parent
1428            .get()
1429            .wrapping_mul(509)
1430            .wrapping_add(index as u64 + 1)
1431            & LOW_MASK),
1432    )
1433}
1434
1435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1436pub enum BrushPreviewShape {
1437    Round,
1438    Square,
1439}
1440
1441impl BrushPreviewShape {
1442    pub const fn label(self) -> &'static str {
1443        match self {
1444            Self::Round => "Round",
1445            Self::Square => "Square",
1446        }
1447    }
1448}
1449
1450#[derive(Debug, Clone, Copy, PartialEq)]
1451pub struct BrushPreviewSpec {
1452    pub color: Color,
1453    pub size: f32,
1454    pub opacity: f32,
1455    pub shape: BrushPreviewShape,
1456}
1457
1458impl Default for BrushPreviewSpec {
1459    fn default() -> Self {
1460        Self::new(Color::BLACK, 12.0, 1.0, BrushPreviewShape::Round)
1461    }
1462}
1463
1464impl BrushPreviewSpec {
1465    /// A brush preview; the preview draws at least 1 unit wide and clamps
1466    /// `opacity` to 0 through 1.
1467    pub fn new(color: Color, size: f32, opacity: f32, shape: BrushPreviewShape) -> Self {
1468        Self {
1469            color,
1470            size,
1471            opacity,
1472            shape,
1473        }
1474    }
1475}
1476
1477pub struct BrushPreview {
1478    theme: Box<DefaultTheme>,
1479    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1480    name: String,
1481    kind: String,
1482    spec: BrushPreviewSpec,
1483    spec_reader: Option<Box<dyn Fn() -> BrushPreviewSpec>>,
1484    size: Option<Size>,
1485}
1486
1487impl BrushPreview {
1488    pub fn new(name: impl Into<String>) -> Self {
1489        let default_theme = DefaultTheme::default();
1490        Self {
1491            theme: Box::new(DefaultTheme::default()),
1492            theme_reader: None,
1493            name: name.into(),
1494            kind: "brush".to_string(),
1495            spec: BrushPreviewSpec::new(
1496                default_theme.palette.accent,
1497                18.0,
1498                1.0,
1499                BrushPreviewShape::Round,
1500            ),
1501            spec_reader: None,
1502            size: None,
1503        }
1504    }
1505
1506    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1507        self.theme = Box::new(theme);
1508        self.theme_reader = None;
1509        self
1510    }
1511
1512    pub fn theme_when<F>(mut self, theme: F) -> Self
1513    where
1514        F: Fn() -> DefaultTheme + 'static,
1515    {
1516        self.theme_reader = Some(Box::new(theme));
1517        self
1518    }
1519
1520    pub fn spec(mut self, spec: BrushPreviewSpec) -> Self {
1521        self.spec = spec;
1522        self.spec_reader = None;
1523        self
1524    }
1525
1526    pub fn spec_when<F>(mut self, reader: F) -> Self
1527    where
1528        F: Fn() -> BrushPreviewSpec + 'static,
1529    {
1530        self.spec_reader = Some(Box::new(reader));
1531        self
1532    }
1533
1534    pub fn kind(mut self, kind: impl Into<String>) -> Self {
1535        self.kind = kind.into();
1536        self
1537    }
1538
1539    pub fn size(mut self, size: Size) -> Self {
1540        self.size = Some(Size::new(size.width.max(80.0), size.height.max(44.0)));
1541        self
1542    }
1543
1544    fn current_spec(&self) -> BrushPreviewSpec {
1545        let spec = self
1546            .spec_reader
1547            .as_ref()
1548            .map(|reader| reader())
1549            .unwrap_or(self.spec);
1550        BrushPreviewSpec {
1551            size: if spec.size.is_finite() {
1552                spec.size.max(1.0)
1553            } else {
1554                1.0
1555            },
1556            opacity: if spec.opacity.is_finite() {
1557                spec.opacity.clamp(0.0, 1.0)
1558            } else {
1559                1.0
1560            },
1561            ..spec
1562        }
1563    }
1564
1565    fn resolved_theme(&self) -> DefaultTheme {
1566        self.theme_reader
1567            .as_ref()
1568            .map(|theme| theme())
1569            .unwrap_or_else(|| *self.theme)
1570    }
1571
1572    fn value_text(kind: &str, spec: BrushPreviewSpec) -> String {
1573        format!(
1574            "{} {}, {:.0} px, {:.0}% opacity",
1575            spec.shape.label(),
1576            kind,
1577            spec.size,
1578            spec.opacity * 100.0
1579        )
1580    }
1581
1582    fn resolved_size(&self, theme: &DefaultTheme) -> Size {
1583        self.size.unwrap_or(Size::new(
1584            theme.metrics.brush_preview_min_width,
1585            theme.metrics.brush_preview_min_height,
1586        ))
1587    }
1588}
1589
1590impl Widget for BrushPreview {
1591    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1592        let theme = self.resolved_theme();
1593        constraints.clamp(self.resolved_size(&theme))
1594    }
1595
1596    fn paint(&self, ctx: &mut PaintCtx) {
1597        let bounds = ctx.bounds();
1598        let theme = self.resolved_theme();
1599        let palette = theme.palette;
1600        let metrics = theme.metrics;
1601        let spec = self.current_spec();
1602        let content = inset_rect(bounds, metrics.brush_preview_padding);
1603        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
1604        let swatch = Rect::new(content.x(), content.y(), swatch_width, content.height());
1605        let sample = Rect::new(
1606            swatch.max_x() + metrics.brush_preview_swatch_gap,
1607            content.y(),
1608            (content.max_x() - swatch.max_x() - metrics.brush_preview_swatch_gap).max(0.0),
1609            content.height(),
1610        );
1611        let preview_color = spec
1612            .color
1613            .with_alpha((spec.color.alpha * spec.opacity).clamp(0.0, 1.0));
1614
1615        draw_control_shape(
1616            ctx,
1617            bounds,
1618            metrics.corner_radius,
1619            physical_pixels(ctx, metrics.border_width.max(1.0)),
1620            palette.surface_raised,
1621            palette.border,
1622        );
1623        draw_checkerboard(ctx, swatch, metrics.brush_preview_checker_size, &theme);
1624        stroke_border(
1625            ctx,
1626            swatch,
1627            metrics.indicator_corner_radius,
1628            physical_pixels(ctx, metrics.border_width.max(1.0)),
1629            palette.border.with_alpha(0.70),
1630        );
1631        paint_brush_preview_mark(ctx, swatch, spec, preview_color);
1632
1633        let track = Rect::new(
1634            sample.x(),
1635            sample.y() + sample.height() * 0.44,
1636            sample.width(),
1637            sample.height() * 0.24,
1638        );
1639        draw_checkerboard(ctx, track, metrics.brush_preview_checker_size, &theme);
1640        paint_brush_preview_stroke(ctx, track, spec, preview_color);
1641
1642        let text_token = theme.text.xs;
1643        let text_height = metrics
1644            .brush_preview_text_height
1645            .max(text_token.line_height);
1646        let text_slot = Rect::new(
1647            sample.x(),
1648            sample.max_y() - text_height,
1649            sample.width(),
1650            text_height,
1651        );
1652        let value_text = Self::value_text(&self.kind, spec);
1653        let text_style = TextStyle {
1654            font_size: text_token.size,
1655            line_height: text_token.line_height,
1656            color: palette.text.with_alpha(0.72),
1657            ..theme.body_text_style()
1658        };
1659        ctx.push_clip_rect(text_slot);
1660        paint_text_line(ctx, text_slot, &value_text, &text_style, TextAlign::Start);
1661        ctx.pop_clip();
1662    }
1663
1664    fn semantics(&self, ctx: &mut SemanticsCtx) {
1665        let spec = self.current_spec();
1666        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Image, ctx.bounds());
1667        node.name = Some(self.name.clone());
1668        node.value = Some(SemanticsValue::Text(Self::value_text(&self.kind, spec)));
1669        ctx.push(node);
1670    }
1671}
1672
1673fn paint_brush_preview_mark(ctx: &mut PaintCtx, rect: Rect, spec: BrushPreviewSpec, color: Color) {
1674    let diameter = spec
1675        .size
1676        .min(rect.width().min(rect.height()) - 10.0)
1677        .max(6.0);
1678    let center = Point::new(
1679        rect.x() + rect.width() * 0.5,
1680        rect.y() + rect.height() * 0.5,
1681    );
1682    let mark = Rect::new(
1683        center.x - diameter * 0.5,
1684        center.y - diameter * 0.5,
1685        diameter,
1686        diameter,
1687    );
1688    match spec.shape {
1689        BrushPreviewShape::Round => ctx.fill(Path::circle(center, diameter * 0.5), color),
1690        BrushPreviewShape::Square => ctx.fill(Path::rounded_rect(mark, 2.0), color),
1691    }
1692}
1693
1694fn paint_brush_preview_stroke(
1695    ctx: &mut PaintCtx,
1696    rect: Rect,
1697    spec: BrushPreviewSpec,
1698    color: Color,
1699) {
1700    let dot_count = 7;
1701    let diameter = (spec.size * 0.62).clamp(4.0, rect.height().max(4.0));
1702    for index in 0..dot_count {
1703        let t = if dot_count <= 1 {
1704            0.0
1705        } else {
1706            index as f32 / (dot_count - 1) as f32
1707        };
1708        let center = Point::new(
1709            rect.x() + diameter * 0.5 + t * (rect.width() - diameter).max(0.0),
1710            rect.y() + rect.height() * 0.5,
1711        );
1712        let alpha = 0.35 + t * 0.65;
1713        let color = color.with_alpha((color.alpha * alpha).clamp(0.0, 1.0));
1714        match spec.shape {
1715            BrushPreviewShape::Round => ctx.fill(Path::circle(center, diameter * 0.5), color),
1716            BrushPreviewShape::Square => ctx.fill(
1717                Path::rounded_rect(
1718                    Rect::new(
1719                        center.x - diameter * 0.5,
1720                        center.y - diameter * 0.5,
1721                        diameter,
1722                        diameter,
1723                    ),
1724                    1.5,
1725                ),
1726                color,
1727            ),
1728        }
1729    }
1730}
1731
1732#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1733enum ActiveChannel {
1734    ColorWheel,
1735    SaturationValue,
1736    Hue,
1737    Saturation,
1738    Value,
1739    Alpha,
1740    EncodingSelector,
1741    EncodingOption(usize),
1742    RgbRed,
1743    RgbGreen,
1744    RgbBlue,
1745}
1746
1747/// The channel sliders a [`SimpleColorPicker`] shows.
1748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1749pub enum SimpleColorPickerMode {
1750    Hsl,
1751    Hsv,
1752    Rgb,
1753    /// Perceptual lightness, chroma, and hue. Equal lightness steps look
1754    /// equally bright across hues, which suits editing theme colors. Chroma
1755    /// beyond the editing space's gamut is reduced to fit, keeping lightness
1756    /// and hue; the chroma track marks where that begins.
1757    Oklch,
1758}
1759
1760/// Top of the OKLCH chroma slider. Display P3 reaches about this far; sRGB
1761/// colors stop sooner, which the chroma track marks.
1762const OKLCH_MAX_CHROMA: f32 = 0.37;
1763
1764/// Below this chroma a color reads as gray and its hue is meaningless.
1765const OKLCH_ACHROMATIC_CHROMA: f32 = 1.0e-4;
1766
1767#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1768enum ColorSliderChannel {
1769    Hue,
1770    HsvSaturation,
1771    HsvValue,
1772    HslSaturation,
1773    HslLightness,
1774    Alpha,
1775    Red,
1776    Green,
1777    Blue,
1778    OklchLightness,
1779    OklchChroma,
1780    OklchHue,
1781}
1782
1783impl ColorSliderChannel {
1784    fn label(self) -> &'static str {
1785        match self {
1786            ColorSliderChannel::Hue | ColorSliderChannel::OklchHue => "H",
1787            ColorSliderChannel::HsvSaturation | ColorSliderChannel::HslSaturation => "S",
1788            ColorSliderChannel::HsvValue => "V",
1789            ColorSliderChannel::HslLightness | ColorSliderChannel::OklchLightness => "L",
1790            ColorSliderChannel::OklchChroma => "C",
1791            ColorSliderChannel::Alpha => "A",
1792            ColorSliderChannel::Red => "R",
1793            ColorSliderChannel::Green => "G",
1794            ColorSliderChannel::Blue => "B",
1795        }
1796    }
1797
1798    fn name(self) -> &'static str {
1799        match self {
1800            ColorSliderChannel::Hue | ColorSliderChannel::OklchHue => "Hue",
1801            ColorSliderChannel::HsvSaturation | ColorSliderChannel::HslSaturation => "Saturation",
1802            ColorSliderChannel::HsvValue => "Value",
1803            ColorSliderChannel::HslLightness | ColorSliderChannel::OklchLightness => "Lightness",
1804            ColorSliderChannel::OklchChroma => "Chroma",
1805            ColorSliderChannel::Alpha => "Alpha",
1806            ColorSliderChannel::Red => "Red",
1807            ColorSliderChannel::Green => "Green",
1808            ColorSliderChannel::Blue => "Blue",
1809        }
1810    }
1811}
1812
1813#[derive(Debug, Clone)]
1814struct ColorSliderRow {
1815    channel: ColorSliderChannel,
1816    label: &'static str,
1817    name: &'static str,
1818    value: f32,
1819    min: f32,
1820    max: f32,
1821    position: f32,
1822    value_text: String,
1823}
1824
1825impl ColorSliderRow {
1826    fn new(
1827        channel: ColorSliderChannel,
1828        value: f32,
1829        min: f32,
1830        max: f32,
1831        position: f32,
1832        value_text: String,
1833    ) -> Self {
1834        Self {
1835            channel,
1836            label: channel.label(),
1837            name: channel.name(),
1838            value,
1839            min,
1840            max,
1841            position: position.clamp(0.0, 1.0),
1842            value_text,
1843        }
1844    }
1845}
1846
1847#[derive(Debug, Clone, Copy)]
1848struct ColorSliderValues {
1849    color: Color,
1850    editing_space: ColorSpace,
1851    hue: f32,
1852    hsv_saturation: f32,
1853    hsv_value: f32,
1854    hsl_saturation: f32,
1855    hsl_lightness: f32,
1856    alpha: f32,
1857    red: f32,
1858    green: f32,
1859    blue: f32,
1860    /// OKLCH coordinates, with hue in degrees.
1861    oklch: Oklch,
1862    max_channel_value: f32,
1863    hdr_capable: bool,
1864}
1865
1866impl ColorSliderValues {
1867    fn from_color(color: Color) -> Self {
1868        let (hue, hsv_saturation, hsv_value) = rgb_to_hsv(color);
1869        let max_channel_value = color_space_max_channel_value(color.space);
1870        let (_, hsl_saturation, hsl_lightness) = rgb_to_hsl(color, max_channel_value);
1871        Self {
1872            color,
1873            editing_space: color.space,
1874            hue,
1875            hsv_saturation,
1876            hsv_value,
1877            hsl_saturation,
1878            hsl_lightness,
1879            alpha: color.alpha,
1880            red: color.red,
1881            green: color.green,
1882            blue: color.blue,
1883            oklch: color.to_oklch(),
1884            max_channel_value,
1885            hdr_capable: color_space_hdr_capable(color.space),
1886        }
1887    }
1888
1889    fn from_hsv(
1890        editing_space: ColorSpace,
1891        hue: f32,
1892        saturation: f32,
1893        value: f32,
1894        alpha: f32,
1895    ) -> Self {
1896        let color = hsv_to_color(editing_space, hue, saturation, value, alpha);
1897        let max_channel_value = color_space_max_channel_value(editing_space);
1898        let (_, hsl_saturation, hsl_lightness) = rgb_to_hsl(color, max_channel_value);
1899        Self {
1900            color,
1901            editing_space,
1902            hue,
1903            hsv_saturation: saturation,
1904            hsv_value: value,
1905            hsl_saturation,
1906            hsl_lightness,
1907            alpha,
1908            red: color.red,
1909            green: color.green,
1910            blue: color.blue,
1911            oklch: color.to_oklch(),
1912            max_channel_value,
1913            hdr_capable: color_space_hdr_capable(editing_space),
1914        }
1915    }
1916
1917    fn from_hsl(
1918        editing_space: ColorSpace,
1919        hue: f32,
1920        saturation: f32,
1921        lightness: f32,
1922        alpha: f32,
1923    ) -> Self {
1924        let max_channel_value = color_space_max_channel_value(editing_space);
1925        let color = hsl_to_color(
1926            editing_space,
1927            hue,
1928            saturation,
1929            lightness,
1930            alpha,
1931            max_channel_value,
1932        );
1933        let (_, hsv_saturation, hsv_value) = rgb_to_hsv(color);
1934        Self {
1935            color,
1936            editing_space,
1937            hue,
1938            hsv_saturation,
1939            hsv_value,
1940            hsl_saturation: saturation,
1941            hsl_lightness: lightness,
1942            alpha,
1943            red: color.red,
1944            green: color.green,
1945            blue: color.blue,
1946            oklch: color.to_oklch(),
1947            max_channel_value,
1948            hdr_capable: color_space_hdr_capable(editing_space),
1949        }
1950    }
1951
1952    fn from_rgb(editing_space: ColorSpace, red: f32, green: f32, blue: f32, alpha: f32) -> Self {
1953        Self::from_color(Color::new(editing_space, red, green, blue, alpha))
1954    }
1955
1956    /// Values for an OKLCH edit. The coordinates are kept as given, so the
1957    /// sliders do not jump when the gamut-mapped color reads back slightly
1958    /// differently, and hue survives while chroma is zero.
1959    fn from_oklch(editing_space: ColorSpace, oklch: Oklch) -> Self {
1960        Self {
1961            oklch,
1962            ..Self::from_color(oklch_to_color(editing_space, oklch))
1963        }
1964    }
1965}
1966
1967/// Converts OKLCH to a color in `space`, reducing chroma to fit its gamut.
1968fn oklch_to_color(space: ColorSpace, oklch: Oklch) -> Color {
1969    match space {
1970        ColorSpace::Srgb => oklch.to_srgb(),
1971        ColorSpace::LinearSrgb => oklch.to_srgb().to_linear_srgb(),
1972        ColorSpace::DisplayP3 => oklch.to_display_p3(),
1973        ColorSpace::LinearDisplayP3 => oklch.to_linear_display_p3(),
1974    }
1975}
1976
1977/// The largest chroma `space` can display at this lightness and hue.
1978fn oklch_gamut_chroma(space: ColorSpace, oklch: Oklch) -> f32 {
1979    match space {
1980        ColorSpace::Srgb | ColorSpace::LinearSrgb => oklch.max_srgb_chroma(),
1981        ColorSpace::DisplayP3 | ColorSpace::LinearDisplayP3 => oklch.max_display_p3_chroma(),
1982    }
1983}
1984
1985#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1986enum ColorPickerSemanticPart {
1987    CurrentColor,
1988    PreviousColor,
1989    ColorRange,
1990    ColorRangeMenu,
1991    ColorRangeOption(usize),
1992    SaturationValue,
1993    Hue,
1994    Saturation,
1995    Value,
1996    Alpha,
1997    Red,
1998    Green,
1999    Blue,
2000    Hex,
2001}
2002
2003/// Widget-owned color-tool paint overrides. The default appearance is derived
2004/// from common semantic theme roles rather than global picker-specific tokens.
2005#[derive(Debug, Clone, Copy, PartialEq, Default)]
2006pub struct ColorPickerColors {
2007    pub checkerboard_light: Option<Color>,
2008    pub checkerboard_dark: Option<Color>,
2009    pub chrome_border: Option<Color>,
2010    pub plane_border: Option<Color>,
2011    pub bar_border: Option<Color>,
2012    pub marker_outer: Option<Color>,
2013    pub marker_dark: Option<Color>,
2014    pub marker_light: Option<Color>,
2015    pub sdr_marker: Option<Color>,
2016    pub hdr_divider: Option<Color>,
2017}
2018
2019impl ColorPickerColors {
2020    fn apply(self, mut theme: DefaultTheme) -> DefaultTheme {
2021        let dark = theme.surfaces.dark;
2022        theme.surfaces.checkerboard_light = self
2023            .checkerboard_light
2024            .unwrap_or(theme.palette.surface_raised);
2025        theme.surfaces.checkerboard_dark = self
2026            .checkerboard_dark
2027            .unwrap_or(theme.palette.control_active);
2028        theme.surfaces.color_picker_chrome_border =
2029            self.chrome_border
2030                .unwrap_or(
2031                    theme
2032                        .palette
2033                        .text
2034                        .with_alpha(if dark { 0.24 } else { 0.18 }),
2035                );
2036        theme.surfaces.color_picker_plane_border =
2037            self.plane_border
2038                .unwrap_or(
2039                    theme
2040                        .palette
2041                        .text
2042                        .with_alpha(if dark { 0.22 } else { 0.16 }),
2043                );
2044        theme.surfaces.color_picker_bar_border =
2045            self.bar_border
2046                .unwrap_or(
2047                    theme
2048                        .palette
2049                        .text
2050                        .with_alpha(if dark { 0.20 } else { 0.14 }),
2051                );
2052        theme.surfaces.color_picker_marker_outer = self.marker_outer.unwrap_or(if dark {
2053            Color::BLACK.with_alpha(0.92)
2054        } else {
2055            Color::WHITE.with_alpha(0.96)
2056        });
2057        theme.surfaces.color_picker_marker_dark =
2058            self.marker_dark.unwrap_or(Color::BLACK.with_alpha(0.88));
2059        theme.surfaces.color_picker_marker_light =
2060            self.marker_light.unwrap_or(Color::WHITE.with_alpha(0.92));
2061        theme.surfaces.color_picker_sdr_marker = self
2062            .sdr_marker
2063            .unwrap_or(theme.palette.text.with_alpha(0.38));
2064        theme.surfaces.color_picker_hdr_divider = self
2065            .hdr_divider
2066            .unwrap_or(theme.palette.warning.with_alpha(0.55));
2067        theme
2068    }
2069}
2070
2071pub struct ColorPicker {
2072    theme: Box<DefaultTheme>,
2073    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2074    enabled: Binding<bool>,
2075    name: String,
2076    editing_space: ColorSpace,
2077    hue: f32,
2078    saturation: f32,
2079    value: f32,
2080    alpha: f32,
2081    previous_color: Color,
2082    show_alpha: bool,
2083    compact: bool,
2084    encoding_dropdown_open: bool,
2085    active: Option<ActiveChannel>,
2086    focus_animation: AnimatedScalar,
2087    color_reader: Option<Box<dyn Fn() -> Color>>,
2088    on_change: Option<Box<dyn FnMut(Color)>>,
2089    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, Color)>>,
2090    appearance: ColorPickerColors,
2091}
2092
2093#[derive(Debug, Clone, Copy)]
2094struct ColorPickerResolvedState {
2095    color: Color,
2096    editing_space: ColorSpace,
2097    hue: f32,
2098    saturation: f32,
2099    value: f32,
2100    alpha: f32,
2101    hdr_capable: bool,
2102    max_channel_value: f32,
2103}
2104
2105pub struct SimpleColorPicker {
2106    theme: Box<DefaultTheme>,
2107    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2108    name: String,
2109    mode: SimpleColorPickerMode,
2110    editing_space: ColorSpace,
2111    hue: f32,
2112    hsv_saturation: f32,
2113    hsv_value: f32,
2114    hsl_saturation: f32,
2115    hsl_lightness: f32,
2116    red: f32,
2117    green: f32,
2118    blue: f32,
2119    /// OKLCH coordinates edited in [`SimpleColorPickerMode::Oklch`]; alpha
2120    /// lives in `alpha`.
2121    oklch: Oklch,
2122    alpha: f32,
2123    show_alpha: bool,
2124    compact: bool,
2125    active: Option<ColorSliderChannel>,
2126    focus_animation: AnimatedScalar,
2127    color_reader: Option<Box<dyn Fn() -> Color>>,
2128    on_change: Option<Box<dyn FnMut(Color)>>,
2129    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, Color)>>,
2130    appearance: ColorPickerColors,
2131}
2132
2133impl ColorPicker {
2134    const MAX_HDR_VALUE: f32 = 12.0;
2135    const ENCODING_OPTIONS: [ColorSpace; 4] = [
2136        ColorSpace::Srgb,
2137        ColorSpace::LinearSrgb,
2138        ColorSpace::DisplayP3,
2139        ColorSpace::LinearDisplayP3,
2140    ];
2141
2142    pub fn new(name: impl Into<String>) -> Self {
2143        let theme = DefaultTheme::default();
2144        Self::from_color(name, theme.palette.accent)
2145    }
2146
2147    pub fn from_color(name: impl Into<String>, color: Color) -> Self {
2148        let (hue, saturation, value) = rgb_to_hsv(color);
2149        Self {
2150            theme: Box::new(DefaultTheme::default()),
2151            theme_reader: None,
2152            enabled: Binding::new(true),
2153            name: name.into(),
2154            editing_space: color.space,
2155            hue,
2156            saturation,
2157            value,
2158            alpha: color.alpha,
2159            previous_color: color,
2160            show_alpha: true,
2161            compact: false,
2162            encoding_dropdown_open: false,
2163            active: None,
2164            focus_animation: AnimatedScalar::new(0.0),
2165            color_reader: None,
2166            on_change: None,
2167            on_change_with_ctx: None,
2168            appearance: ColorPickerColors::default(),
2169        }
2170    }
2171
2172    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2173        self.theme = Box::new(theme);
2174        self.theme_reader = None;
2175        self
2176    }
2177
2178    pub fn theme_when<F>(mut self, theme: F) -> Self
2179    where
2180        F: Fn() -> DefaultTheme + 'static,
2181    {
2182        self.theme_reader = Some(Box::new(theme));
2183        self
2184    }
2185
2186    /// Whether the user can use the widget. Disabled, it ignores input,
2187    /// can't take focus, draws in the theme's disabled colors, and tells
2188    /// assistive technology it and its items are unavailable.
2189    pub fn enabled(mut self, enabled: bool) -> Self {
2190        self.enabled.set(enabled);
2191        self
2192    }
2193
2194    /// [`Self::enabled`], read whenever the widget needs it.
2195    pub fn enabled_when<F>(mut self, enabled: F) -> Self
2196    where
2197        F: Fn() -> bool + 'static,
2198    {
2199        self.enabled.set_when(enabled);
2200        self
2201    }
2202
2203    /// [`Self::enabled`], following an observable and repainting when it
2204    /// changes.
2205    pub fn enabled_from<O>(mut self, enabled: O) -> Self
2206    where
2207        O: Observable<bool> + 'static,
2208    {
2209        self.enabled.set_from(enabled);
2210        self
2211    }
2212
2213    pub fn is_enabled(&self) -> bool {
2214        self.enabled.get()
2215    }
2216
2217    /// The theme to paint with: the disabled look while the widget is
2218    /// disabled.
2219    fn paint_theme(&self) -> DefaultTheme {
2220        let theme = self.resolved_theme();
2221        if self.enabled.get() {
2222            theme
2223        } else {
2224            theme.for_disabled_control()
2225        }
2226    }
2227
2228    pub fn show_alpha(mut self, show_alpha: bool) -> Self {
2229        self.show_alpha = show_alpha;
2230        self
2231    }
2232
2233    pub fn compact(mut self, compact: bool) -> Self {
2234        self.compact = compact;
2235        self
2236    }
2237
2238    pub fn colors(mut self, colors: ColorPickerColors) -> Self {
2239        self.appearance = colors;
2240        self
2241    }
2242
2243    pub fn on_change<F>(mut self, on_change: F) -> Self
2244    where
2245        F: FnMut(Color) + 'static,
2246    {
2247        self.on_change = Some(Box::new(on_change));
2248        self
2249    }
2250
2251    /// [`Self::on_change`], with the event context first.
2252    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
2253    where
2254        F: FnMut(&mut EventCtx, Color) + 'static,
2255    {
2256        self.on_change_with_ctx = Some(Box::new(on_change));
2257        self
2258    }
2259
2260    pub fn color_when<F>(mut self, color: F) -> Self
2261    where
2262        F: Fn() -> Color + 'static,
2263    {
2264        self.color_reader = Some(Box::new(color));
2265        self
2266    }
2267
2268    pub fn current_color(&self) -> Color {
2269        hsv_to_color(
2270            self.editing_space,
2271            self.hue,
2272            self.saturation,
2273            self.value,
2274            self.alpha,
2275        )
2276    }
2277
2278    fn hdr_capable(&self) -> bool {
2279        color_space_hdr_capable(self.editing_space)
2280    }
2281
2282    fn max_channel_value(&self) -> f32 {
2283        color_space_max_channel_value(self.editing_space)
2284    }
2285
2286    fn external_color(&self) -> Option<Color> {
2287        if self.active.is_none() && !self.encoding_dropdown_open {
2288            self.color_reader.as_ref().map(|reader| reader())
2289        } else {
2290            None
2291        }
2292    }
2293
2294    fn resolved_theme(&self) -> DefaultTheme {
2295        let theme = self
2296            .theme_reader
2297            .as_ref()
2298            .map(|theme| theme())
2299            .unwrap_or_else(|| *self.theme);
2300        self.appearance.apply(theme)
2301    }
2302
2303    fn layout_metrics_for(&self, theme: &DefaultTheme) -> ControlMetrics {
2304        if self.compact {
2305            ControlMetrics::from_tokens(theme.spacing, theme.radius, ThemeDensity::Compact)
2306        } else {
2307            theme.metrics
2308        }
2309    }
2310
2311    fn layout_metrics(&self) -> ControlMetrics {
2312        let theme = self.resolved_theme();
2313        self.layout_metrics_for(&theme)
2314    }
2315
2316    fn resolved_state(&self) -> ColorPickerResolvedState {
2317        if let Some(color) = self.external_color() {
2318            let (hue, saturation, value) = rgb_to_hsv(color);
2319            let hdr_capable = color_space_hdr_capable(color.space);
2320            return ColorPickerResolvedState {
2321                color,
2322                editing_space: color.space,
2323                hue,
2324                saturation,
2325                value,
2326                alpha: color.alpha,
2327                hdr_capable,
2328                max_channel_value: color_space_max_channel_value(color.space),
2329            };
2330        }
2331
2332        ColorPickerResolvedState {
2333            color: self.current_color(),
2334            editing_space: self.editing_space,
2335            hue: self.hue,
2336            saturation: self.saturation,
2337            value: self.value,
2338            alpha: self.alpha,
2339            hdr_capable: self.hdr_capable(),
2340            max_channel_value: self.max_channel_value(),
2341        }
2342    }
2343
2344    fn sync_external_color(&mut self) -> bool {
2345        let Some(color) = self.external_color() else {
2346            return false;
2347        };
2348        if !colors_close(self.current_color(), color) {
2349            self.apply_color(color);
2350            return true;
2351        }
2352        false
2353    }
2354
2355    fn content_inset(&self) -> f32 {
2356        self.layout_metrics().color_picker_content_inset
2357    }
2358
2359    fn panel_gap(&self) -> f32 {
2360        self.layout_metrics().color_picker_panel_gap
2361    }
2362
2363    fn top_bar_height(&self) -> f32 {
2364        self.layout_metrics().color_picker_top_bar_height
2365    }
2366
2367    fn swatch_width(&self) -> f32 {
2368        self.layout_metrics().color_picker_swatch_width
2369    }
2370
2371    fn swatch_gap(&self) -> f32 {
2372        self.layout_metrics().color_picker_swatch_gap
2373    }
2374
2375    fn section_gap(&self) -> f32 {
2376        self.layout_metrics().color_picker_section_gap
2377    }
2378
2379    fn wheel_size(&self) -> f32 {
2380        self.layout_metrics().color_picker_wheel_size
2381    }
2382
2383    fn map_size(&self) -> f32 {
2384        self.layout_metrics().color_picker_map_size
2385    }
2386
2387    fn right_panel_width(&self) -> f32 {
2388        self.layout_metrics().color_picker_right_panel_width
2389    }
2390
2391    fn row_height(&self) -> f32 {
2392        self.layout_metrics().color_picker_row_height
2393    }
2394
2395    fn row_gap(&self) -> f32 {
2396        self.layout_metrics().color_picker_row_gap
2397    }
2398
2399    fn field_height(&self) -> f32 {
2400        self.layout_metrics().color_picker_field_height
2401    }
2402
2403    fn field_gap(&self) -> f32 {
2404        self.layout_metrics().color_picker_field_gap
2405    }
2406
2407    fn dropdown_gap(&self) -> f32 {
2408        self.layout_metrics().color_picker_dropdown_gap
2409    }
2410
2411    fn encoding_menu_row_height(&self) -> f32 {
2412        self.layout_metrics().color_picker_encoding_menu_row_height
2413    }
2414
2415    fn channel_slider_count(&self) -> usize {
2416        if self.show_alpha { 4 } else { 3 }
2417    }
2418
2419    fn desired_size(&self) -> Size {
2420        let inset = self.content_inset();
2421        let left_height = self.wheel_size()
2422            + self.section_gap()
2423            + self.channel_slider_count() as f32 * self.row_height()
2424            + self.channel_slider_count().saturating_sub(1) as f32 * self.row_gap();
2425        let right_height = self.map_size()
2426            + self.section_gap()
2427            + 3.0 * self.row_height()
2428            + 2.0 * self.row_gap()
2429            + self.field_gap()
2430            + self.field_height();
2431        Size::new(
2432            inset * 2.0 + self.wheel_size() + self.panel_gap() + self.right_panel_width(),
2433            inset * 2.0 + self.top_bar_height() + self.panel_gap() + left_height.max(right_height),
2434        )
2435    }
2436
2437    fn content_rect(&self, bounds: Rect) -> Rect {
2438        inset_rect(bounds, Insets::all(self.content_inset()))
2439    }
2440
2441    fn header_rect(&self, bounds: Rect) -> Rect {
2442        let content = self.content_rect(bounds);
2443        Rect::new(
2444            content.x(),
2445            content.y(),
2446            content.width(),
2447            self.top_bar_height(),
2448        )
2449    }
2450
2451    fn current_swatch_rect(&self, bounds: Rect) -> Rect {
2452        let header = self.header_rect(bounds);
2453        Rect::new(header.x(), header.y(), self.swatch_width(), header.height())
2454    }
2455
2456    fn previous_swatch_rect(&self, bounds: Rect) -> Rect {
2457        let current = self.current_swatch_rect(bounds);
2458        Rect::new(
2459            current.max_x() + self.swatch_gap(),
2460            current.y(),
2461            self.swatch_width(),
2462            current.height(),
2463        )
2464    }
2465
2466    fn left_column_rect(&self, bounds: Rect) -> Rect {
2467        let content = self.content_rect(bounds);
2468        let y = self.header_rect(bounds).max_y() + self.panel_gap();
2469        let width = self.wheel_size().min(content.width());
2470        Rect::new(content.x(), y, width, content.max_y() - y)
2471    }
2472
2473    fn right_column_rect(&self, bounds: Rect) -> Rect {
2474        let content = self.content_rect(bounds);
2475        let left = self.left_column_rect(bounds);
2476        Rect::new(
2477            left.max_x() + self.panel_gap(),
2478            left.y(),
2479            content.max_x() - (left.max_x() + self.panel_gap()),
2480            content.max_y() - left.y(),
2481        )
2482    }
2483
2484    fn color_wheel_rect(&self, bounds: Rect) -> Rect {
2485        let left = self.left_column_rect(bounds);
2486        Rect::new(left.x(), left.y(), self.wheel_size(), self.wheel_size())
2487    }
2488
2489    fn saturation_value_rect(&self, bounds: Rect) -> Rect {
2490        let right = self.right_column_rect(bounds);
2491        Rect::new(
2492            right.x(),
2493            right.y(),
2494            right.width().min(self.map_size()),
2495            self.map_size(),
2496        )
2497    }
2498
2499    fn left_slider_rect(&self, bounds: Rect, index: usize) -> Rect {
2500        let wheel = self.color_wheel_rect(bounds);
2501        let y = wheel.max_y()
2502            + self.section_gap()
2503            + index as f32 * (self.row_height() + self.row_gap());
2504        Rect::new(wheel.x(), y, wheel.width(), self.row_height())
2505    }
2506
2507    fn encoding_rect(&self, bounds: Rect) -> Rect {
2508        let header = self.header_rect(bounds);
2509        let selector_x = header.x()
2510            + self.swatch_width()
2511            + self.swatch_gap()
2512            + self.swatch_width()
2513            + self.panel_gap();
2514        Rect::new(
2515            selector_x,
2516            header.y() + ((header.height() - self.field_height()) * 0.5),
2517            (header.max_x() - selector_x).max(0.0),
2518            self.field_height(),
2519        )
2520    }
2521
2522    fn encoding_menu_rect(&self, bounds: Rect) -> Rect {
2523        let encoding = self.encoding_rect(bounds);
2524        Rect::new(
2525            encoding.x(),
2526            encoding.max_y() + self.dropdown_gap(),
2527            encoding.width(),
2528            self.encoding_menu_row_height() * Self::ENCODING_OPTIONS.len() as f32,
2529        )
2530    }
2531
2532    fn encoding_option_rect(&self, bounds: Rect, index: usize) -> Rect {
2533        let menu = self.encoding_menu_rect(bounds);
2534        Rect::new(
2535            menu.x(),
2536            menu.y() + index as f32 * self.encoding_menu_row_height(),
2537            menu.width(),
2538            self.encoding_menu_row_height(),
2539        )
2540    }
2541
2542    fn encoding_option_at(&self, bounds: Rect, position: Point) -> Option<usize> {
2543        if !self.encoding_dropdown_open || !self.encoding_menu_rect(bounds).contains(position) {
2544            return None;
2545        }
2546
2547        Self::ENCODING_OPTIONS
2548            .iter()
2549            .enumerate()
2550            .find_map(|(index, _)| {
2551                self.encoding_option_rect(bounds, index)
2552                    .contains(position)
2553                    .then_some(index)
2554            })
2555    }
2556
2557    fn rgb_row_rect(&self, bounds: Rect, index: usize) -> Rect {
2558        let map = self.saturation_value_rect(bounds);
2559        let y =
2560            map.max_y() + self.section_gap() + index as f32 * (self.row_height() + self.row_gap());
2561        Rect::new(map.x(), y, map.width(), self.row_height())
2562    }
2563
2564    fn hex_rect(&self, bounds: Rect) -> Rect {
2565        let last_row = self.rgb_row_rect(bounds, 2);
2566        Rect::new(
2567            last_row.x(),
2568            last_row.max_y() + self.field_gap(),
2569            last_row.width(),
2570            self.field_height(),
2571        )
2572    }
2573
2574    /// Move `channel` to `position` and report the new color to the change
2575    /// callbacks.
2576    fn update_from_position(
2577        &mut self,
2578        ctx: &mut EventCtx,
2579        bounds: Rect,
2580        channel: ActiveChannel,
2581        position: Point,
2582    ) {
2583        if self.apply_position(bounds, channel, position) {
2584            self.emit_change(ctx);
2585        }
2586    }
2587
2588    /// Move `channel` to `position`, returning whether the color changed.
2589    fn apply_position(&mut self, bounds: Rect, channel: ActiveChannel, position: Point) -> bool {
2590        match channel {
2591            ActiveChannel::ColorWheel => {
2592                let rect = self.color_wheel_rect(bounds);
2593                let center = Point::new(
2594                    rect.x() + rect.width() * 0.5,
2595                    rect.y() + rect.height() * 0.5,
2596                );
2597                let dx = position.x - center.x;
2598                let dy = position.y - center.y;
2599                let angle = dy.atan2(dx);
2600                self.hue = ((angle / std::f32::consts::TAU) + 1.0).rem_euclid(1.0);
2601                true
2602            }
2603            ActiveChannel::SaturationValue => {
2604                let rect = self.saturation_value_rect(bounds);
2605                self.saturation = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2606                let t = (1.0 - ((position.y - rect.y()) / rect.height())).clamp(0.0, 1.0);
2607                self.value = if self.hdr_capable() {
2608                    hdr_slider_to_value(t)
2609                } else {
2610                    t
2611                };
2612                true
2613            }
2614            ActiveChannel::Hue => {
2615                self.hue = self.slider_position(self.left_slider_rect(bounds, 0), position);
2616                true
2617            }
2618            ActiveChannel::Saturation => {
2619                self.saturation = self.slider_position(self.left_slider_rect(bounds, 1), position);
2620                true
2621            }
2622            ActiveChannel::Value => {
2623                let t = self.slider_position(self.left_slider_rect(bounds, 2), position);
2624                self.value = if self.hdr_capable() {
2625                    hdr_slider_to_value(t)
2626                } else {
2627                    t
2628                };
2629                true
2630            }
2631            ActiveChannel::Alpha => {
2632                self.alpha = self.slider_position(self.left_slider_rect(bounds, 3), position);
2633                true
2634            }
2635            ActiveChannel::EncodingSelector | ActiveChannel::EncodingOption(_) => false,
2636            ActiveChannel::RgbRed => {
2637                self.apply_rgb_channel_from_position(bounds, 0, position);
2638                true
2639            }
2640            ActiveChannel::RgbGreen => {
2641                self.apply_rgb_channel_from_position(bounds, 1, position);
2642                true
2643            }
2644            ActiveChannel::RgbBlue => {
2645                self.apply_rgb_channel_from_position(bounds, 2, position);
2646                true
2647            }
2648        }
2649    }
2650
2651    fn emit_change(&mut self, ctx: &mut EventCtx) {
2652        let color = self.current_color();
2653        if let Some(on_change) = &mut self.on_change {
2654            on_change(color);
2655        }
2656        if let Some(on_change) = &mut self.on_change_with_ctx {
2657            on_change(ctx, color);
2658        }
2659    }
2660
2661    /// Where `position` falls along the track of the slider row `rect`.
2662    fn slider_position(&self, rect: Rect, position: Point) -> f32 {
2663        ColorSliderRowSlots::new(rect, &self.resolved_theme()).position(position.x)
2664    }
2665
2666    fn apply_color(&mut self, color: Color) {
2667        self.editing_space = color.space;
2668        let (hue, saturation, value) = rgb_to_hsv(color);
2669        self.hue = hue;
2670        self.saturation = saturation;
2671        self.value = value;
2672        self.alpha = color.alpha;
2673    }
2674
2675    fn set_editing_space(&mut self, ctx: &mut EventCtx, next_space: ColorSpace) {
2676        if self.editing_space == next_space {
2677            return;
2678        }
2679
2680        let current = self.current_color();
2681        self.apply_color(Color::new(
2682            next_space,
2683            current.red,
2684            current.green,
2685            current.blue,
2686            current.alpha,
2687        ));
2688        self.emit_change(ctx);
2689    }
2690
2691    fn apply_rgb_channel_from_position(
2692        &mut self,
2693        bounds: Rect,
2694        channel_index: usize,
2695        position: Point,
2696    ) {
2697        let t = self.slider_position(self.rgb_row_rect(bounds, channel_index), position);
2698        let mut channels = [
2699            self.current_color().red,
2700            self.current_color().green,
2701            self.current_color().blue,
2702        ];
2703        channels[channel_index] = self.max_channel_value() * t;
2704        self.apply_color(Color::new(
2705            self.editing_space,
2706            channels[0],
2707            channels[1],
2708            channels[2],
2709            self.alpha,
2710        ));
2711    }
2712
2713    fn hit_channel(&self, bounds: Rect, position: Point) -> Option<ActiveChannel> {
2714        if point_in_wheel_ring(self.color_wheel_rect(bounds), position) {
2715            Some(ActiveChannel::ColorWheel)
2716        } else if self.saturation_value_rect(bounds).contains(position) {
2717            Some(ActiveChannel::SaturationValue)
2718        } else if self.left_slider_rect(bounds, 0).contains(position) {
2719            Some(ActiveChannel::Hue)
2720        } else if self.left_slider_rect(bounds, 1).contains(position) {
2721            Some(ActiveChannel::Saturation)
2722        } else if self.left_slider_rect(bounds, 2).contains(position) {
2723            Some(ActiveChannel::Value)
2724        } else if self.show_alpha && self.left_slider_rect(bounds, 3).contains(position) {
2725            Some(ActiveChannel::Alpha)
2726        } else if self.encoding_rect(bounds).contains(position) {
2727            Some(ActiveChannel::EncodingSelector)
2728        } else if self.rgb_row_rect(bounds, 0).contains(position) {
2729            Some(ActiveChannel::RgbRed)
2730        } else if self.rgb_row_rect(bounds, 1).contains(position) {
2731            Some(ActiveChannel::RgbGreen)
2732        } else if self.rgb_row_rect(bounds, 2).contains(position) {
2733            Some(ActiveChannel::RgbBlue)
2734        } else {
2735            None
2736        }
2737    }
2738
2739    fn color_semantics_text(&self, color: Color, hdr_capable: bool) -> String {
2740        if hdr_capable && is_hdr_color(color) {
2741            format!(
2742                "R {:.3} G {:.3} B {:.3} A {:.3}",
2743                color.red, color.green, color.blue, color.alpha
2744            )
2745        } else {
2746            format_color(color)
2747        }
2748    }
2749
2750    fn push_color_swatch_semantics(
2751        &self,
2752        ctx: &mut SemanticsCtx,
2753        part: ColorPickerSemanticPart,
2754        name: &'static str,
2755        bounds: Rect,
2756        color: Color,
2757        hdr_capable: bool,
2758    ) {
2759        let mut node = color_picker_child_semantics_node(
2760            ctx.widget_id(),
2761            part,
2762            SemanticsRole::ColorSwatch,
2763            bounds,
2764            name,
2765        );
2766        node.value = Some(SemanticsValue::Text(
2767            self.color_semantics_text(color, hdr_capable),
2768        ));
2769        ctx.push(node);
2770    }
2771
2772    fn push_slider_semantics(
2773        &self,
2774        ctx: &mut SemanticsCtx,
2775        part: ColorPickerSemanticPart,
2776        name: &'static str,
2777        bounds: Rect,
2778        value: f32,
2779        min: f32,
2780        max: f32,
2781    ) {
2782        let mut node = color_picker_child_semantics_node(
2783            ctx.widget_id(),
2784            part,
2785            SemanticsRole::Slider,
2786            bounds,
2787            name,
2788        );
2789        node.value = Some(SemanticsValue::Range {
2790            value: value as f64,
2791            min: min as f64,
2792            max: max as f64,
2793        });
2794        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2795        ctx.push(node);
2796    }
2797
2798    fn push_component_semantics(&self, ctx: &mut SemanticsCtx, resolved: ColorPickerResolvedState) {
2799        let bounds = ctx.bounds();
2800        let current = resolved.color;
2801        self.push_color_swatch_semantics(
2802            ctx,
2803            ColorPickerSemanticPart::CurrentColor,
2804            "Current color",
2805            self.current_swatch_rect(bounds),
2806            current,
2807            resolved.hdr_capable,
2808        );
2809        self.push_color_swatch_semantics(
2810            ctx,
2811            ColorPickerSemanticPart::PreviousColor,
2812            "Previous color",
2813            self.previous_swatch_rect(bounds),
2814            self.previous_color,
2815            color_space_hdr_capable(self.previous_color.space),
2816        );
2817
2818        let mut range = color_picker_child_semantics_node(
2819            ctx.widget_id(),
2820            ColorPickerSemanticPart::ColorRange,
2821            SemanticsRole::ComboBox,
2822            self.encoding_rect(bounds),
2823            "Color range",
2824        );
2825        range.value = Some(SemanticsValue::Text(
2826            editing_space_label(resolved.editing_space).to_string(),
2827        ));
2828        range.state.expanded = Some(self.encoding_dropdown_open);
2829        range.actions = vec![
2830            SemanticsAction::Focus,
2831            if self.encoding_dropdown_open {
2832                SemanticsAction::Collapse
2833            } else {
2834                SemanticsAction::Expand
2835            },
2836            SemanticsAction::SetValue,
2837        ];
2838        ctx.push(range);
2839
2840        let mut saturation_value = color_picker_child_semantics_node(
2841            ctx.widget_id(),
2842            ColorPickerSemanticPart::SaturationValue,
2843            SemanticsRole::Slider,
2844            self.saturation_value_rect(bounds),
2845            "Saturation and value",
2846        );
2847        saturation_value.description = Some(format!(
2848            "Saturation {:.1}%, value {:.3}",
2849            resolved.saturation * 100.0,
2850            resolved.value
2851        ));
2852        saturation_value.value = Some(SemanticsValue::Range {
2853            value: resolved.value as f64,
2854            min: 0.0,
2855            max: resolved.max_channel_value as f64,
2856        });
2857        saturation_value.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2858        ctx.push(saturation_value);
2859
2860        self.push_slider_semantics(
2861            ctx,
2862            ColorPickerSemanticPart::Hue,
2863            "Hue",
2864            self.left_slider_rect(bounds, 0),
2865            resolved.hue * 360.0,
2866            0.0,
2867            360.0,
2868        );
2869        self.push_slider_semantics(
2870            ctx,
2871            ColorPickerSemanticPart::Saturation,
2872            "Saturation",
2873            self.left_slider_rect(bounds, 1),
2874            resolved.saturation * 100.0,
2875            0.0,
2876            100.0,
2877        );
2878        self.push_slider_semantics(
2879            ctx,
2880            ColorPickerSemanticPart::Value,
2881            "Value",
2882            self.left_slider_rect(bounds, 2),
2883            resolved.value,
2884            0.0,
2885            resolved.max_channel_value,
2886        );
2887        if self.show_alpha {
2888            self.push_slider_semantics(
2889                ctx,
2890                ColorPickerSemanticPart::Alpha,
2891                "Alpha",
2892                self.left_slider_rect(bounds, 3),
2893                resolved.alpha * 100.0,
2894                0.0,
2895                100.0,
2896            );
2897        }
2898
2899        let rgb = current.to_array();
2900        for (index, (part, name)) in [
2901            (ColorPickerSemanticPart::Red, "Red"),
2902            (ColorPickerSemanticPart::Green, "Green"),
2903            (ColorPickerSemanticPart::Blue, "Blue"),
2904        ]
2905        .into_iter()
2906        .enumerate()
2907        {
2908            self.push_slider_semantics(
2909                ctx,
2910                part,
2911                name,
2912                self.rgb_row_rect(bounds, index),
2913                rgb[index],
2914                0.0,
2915                resolved.max_channel_value,
2916            );
2917        }
2918
2919        let hex_name = if resolved.hdr_capable && is_hdr_color(current) {
2920            "HDR hex unavailable".to_string()
2921        } else {
2922            format!("Hex color {}", format_color(current))
2923        };
2924        let hex = color_picker_child_semantics_node(
2925            ctx.widget_id(),
2926            ColorPickerSemanticPart::Hex,
2927            SemanticsRole::Text,
2928            self.hex_rect(bounds),
2929            hex_name,
2930        );
2931        ctx.push(hex);
2932
2933        if self.encoding_dropdown_open {
2934            let menu_id = color_picker_child_semantics_id(
2935                ctx.widget_id(),
2936                ColorPickerSemanticPart::ColorRangeMenu,
2937            );
2938            let mut menu = color_picker_child_semantics_node(
2939                ctx.widget_id(),
2940                ColorPickerSemanticPart::ColorRangeMenu,
2941                SemanticsRole::Menu,
2942                self.encoding_menu_rect(bounds),
2943                "Color range options",
2944            );
2945            menu.state.expanded = Some(true);
2946            ctx.push(menu);
2947
2948            for (index, space) in Self::ENCODING_OPTIONS.iter().copied().enumerate() {
2949                let mut item = color_picker_child_semantics_node_with_parent(
2950                    ctx.widget_id(),
2951                    menu_id,
2952                    ColorPickerSemanticPart::ColorRangeOption(index),
2953                    SemanticsRole::MenuItem,
2954                    self.encoding_option_rect(bounds, index),
2955                    editing_space_label(space),
2956                );
2957                item.state.selected = space == resolved.editing_space;
2958                item.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
2959                ctx.push(item);
2960            }
2961        }
2962    }
2963}
2964
2965fn color_picker_child_semantics_id(parent: WidgetId, part: ColorPickerSemanticPart) -> WidgetId {
2966    let slot = match part {
2967        ColorPickerSemanticPart::CurrentColor => 1,
2968        ColorPickerSemanticPart::PreviousColor => 2,
2969        ColorPickerSemanticPart::ColorRange => 3,
2970        ColorPickerSemanticPart::ColorRangeMenu => 4,
2971        ColorPickerSemanticPart::ColorRangeOption(index) => 32 + index as u64,
2972        ColorPickerSemanticPart::SaturationValue => 5,
2973        ColorPickerSemanticPart::Hue => 6,
2974        ColorPickerSemanticPart::Saturation => 7,
2975        ColorPickerSemanticPart::Value => 8,
2976        ColorPickerSemanticPart::Alpha => 9,
2977        ColorPickerSemanticPart::Red => 10,
2978        ColorPickerSemanticPart::Green => 11,
2979        ColorPickerSemanticPart::Blue => 12,
2980        ColorPickerSemanticPart::Hex => 13,
2981    };
2982    const TAG: u64 = 3_u64 << 51;
2983    const LOW_MASK: u64 = (1_u64 << 51) - 1;
2984    WidgetId::new(TAG | (parent.get().wrapping_mul(397).wrapping_add(slot) & LOW_MASK))
2985}
2986
2987fn color_picker_child_semantics_node(
2988    parent: WidgetId,
2989    part: ColorPickerSemanticPart,
2990    role: SemanticsRole,
2991    bounds: Rect,
2992    name: impl Into<String>,
2993) -> SemanticsNode {
2994    color_picker_child_semantics_node_with_parent(parent, parent, part, role, bounds, name)
2995}
2996
2997fn color_picker_child_semantics_node_with_parent(
2998    owner: WidgetId,
2999    parent: WidgetId,
3000    part: ColorPickerSemanticPart,
3001    role: SemanticsRole,
3002    bounds: Rect,
3003    name: impl Into<String>,
3004) -> SemanticsNode {
3005    let mut node = SemanticsNode::new(color_picker_child_semantics_id(owner, part), role, bounds);
3006    node.parent = Some(parent);
3007    node.name = Some(name.into());
3008    node
3009}
3010
3011impl SimpleColorPicker {
3012    pub fn new(name: impl Into<String>) -> Self {
3013        let theme = DefaultTheme::default();
3014        Self::from_color(name, theme.palette.accent)
3015    }
3016
3017    pub fn from_color(name: impl Into<String>, color: Color) -> Self {
3018        let values = ColorSliderValues::from_color(color);
3019        Self {
3020            theme: Box::new(DefaultTheme::default()),
3021            theme_reader: None,
3022            name: name.into(),
3023            mode: SimpleColorPickerMode::Hsv,
3024            editing_space: color.space,
3025            hue: values.hue,
3026            hsv_saturation: values.hsv_saturation,
3027            hsv_value: values.hsv_value,
3028            hsl_saturation: values.hsl_saturation,
3029            hsl_lightness: values.hsl_lightness,
3030            red: values.red,
3031            green: values.green,
3032            blue: values.blue,
3033            oklch: values.oklch,
3034            alpha: values.alpha,
3035            show_alpha: true,
3036            compact: false,
3037            active: None,
3038            focus_animation: AnimatedScalar::new(0.0),
3039            color_reader: None,
3040            on_change: None,
3041            on_change_with_ctx: None,
3042            appearance: ColorPickerColors::default(),
3043        }
3044    }
3045
3046    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3047        self.theme = Box::new(theme);
3048        self.theme_reader = None;
3049        self
3050    }
3051
3052    pub fn theme_when<F>(mut self, theme: F) -> Self
3053    where
3054        F: Fn() -> DefaultTheme + 'static,
3055    {
3056        self.theme_reader = Some(Box::new(theme));
3057        self
3058    }
3059
3060    pub fn mode(mut self, mode: SimpleColorPickerMode) -> Self {
3061        if self.mode != mode {
3062            let current = self.current_color();
3063            self.mode = mode;
3064            self.apply_color(current);
3065        }
3066        self
3067    }
3068
3069    pub fn color_space(mut self, color_space: ColorSpace) -> Self {
3070        self.set_color_space(color_space);
3071        self
3072    }
3073
3074    pub fn show_alpha(mut self, show_alpha: bool) -> Self {
3075        self.show_alpha = show_alpha;
3076        self
3077    }
3078
3079    pub fn compact(mut self, compact: bool) -> Self {
3080        self.compact = compact;
3081        self
3082    }
3083
3084    pub fn colors(mut self, colors: ColorPickerColors) -> Self {
3085        self.appearance = colors;
3086        self
3087    }
3088
3089    pub fn on_change<F>(mut self, on_change: F) -> Self
3090    where
3091        F: FnMut(Color) + 'static,
3092    {
3093        self.on_change = Some(Box::new(on_change));
3094        self
3095    }
3096
3097    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
3098    where
3099        F: FnMut(&mut EventCtx, Color) + 'static,
3100    {
3101        self.on_change_with_ctx = Some(Box::new(on_change));
3102        self
3103    }
3104
3105    pub fn color_when<F>(mut self, color: F) -> Self
3106    where
3107        F: Fn() -> Color + 'static,
3108    {
3109        self.color_reader = Some(Box::new(color));
3110        self
3111    }
3112
3113    pub fn current_color(&self) -> Color {
3114        match self.mode {
3115            SimpleColorPickerMode::Hsl => hsl_to_color(
3116                self.editing_space,
3117                self.hue,
3118                self.hsl_saturation,
3119                self.hsl_lightness,
3120                self.alpha,
3121                self.max_channel_value(),
3122            ),
3123            SimpleColorPickerMode::Hsv => hsv_to_color(
3124                self.editing_space,
3125                self.hue,
3126                self.hsv_saturation,
3127                self.hsv_value,
3128                self.alpha,
3129            ),
3130            SimpleColorPickerMode::Rgb => Color::new(
3131                self.editing_space,
3132                self.red,
3133                self.green,
3134                self.blue,
3135                self.alpha,
3136            ),
3137            SimpleColorPickerMode::Oklch => {
3138                oklch_to_color(self.editing_space, self.oklch_with_alpha())
3139            }
3140        }
3141    }
3142
3143    fn oklch_with_alpha(&self) -> Oklch {
3144        Oklch {
3145            alpha: self.alpha,
3146            ..self.oklch
3147        }
3148    }
3149
3150    /// Takes OKLCH coordinates from `oklch`, keeping the current hue while
3151    /// the color has no chroma so a gray does not reset the hue slider.
3152    fn set_oklch_from(&mut self, oklch: Oklch) {
3153        let hue = if oklch.chroma < OKLCH_ACHROMATIC_CHROMA {
3154            self.oklch.hue
3155        } else {
3156            oklch.hue
3157        };
3158        self.oklch = Oklch { hue, ..oklch };
3159    }
3160
3161    fn hdr_capable(&self) -> bool {
3162        color_space_hdr_capable(self.editing_space)
3163    }
3164
3165    fn max_channel_value(&self) -> f32 {
3166        color_space_max_channel_value(self.editing_space)
3167    }
3168
3169    fn external_color(&self) -> Option<Color> {
3170        if self.active.is_none() {
3171            self.color_reader.as_ref().map(|reader| reader())
3172        } else {
3173            None
3174        }
3175    }
3176
3177    fn resolved_theme(&self) -> DefaultTheme {
3178        let theme = self
3179            .theme_reader
3180            .as_ref()
3181            .map(|theme| theme())
3182            .unwrap_or_else(|| *self.theme);
3183        self.appearance.apply(theme)
3184    }
3185
3186    fn layout_metrics_for(&self, theme: &DefaultTheme) -> ControlMetrics {
3187        if self.compact {
3188            ControlMetrics::from_tokens(theme.spacing, theme.radius, ThemeDensity::Compact)
3189        } else {
3190            theme.metrics
3191        }
3192    }
3193
3194    fn layout_metrics(&self) -> ControlMetrics {
3195        let theme = self.resolved_theme();
3196        self.layout_metrics_for(&theme)
3197    }
3198
3199    fn row_count(&self) -> usize {
3200        if self.show_alpha { 4 } else { 3 }
3201    }
3202
3203    fn content_inset(&self) -> f32 {
3204        self.layout_metrics().color_picker_content_inset
3205    }
3206
3207    fn row_height(&self) -> f32 {
3208        self.layout_metrics().color_picker_row_height
3209    }
3210
3211    fn row_gap(&self) -> f32 {
3212        self.layout_metrics().color_picker_row_gap
3213    }
3214
3215    fn desired_size(&self) -> Size {
3216        let metrics = self.layout_metrics();
3217        let inset = metrics.color_picker_content_inset;
3218        let row_count = self.row_count();
3219        let row_gap_count = row_count.saturating_sub(1);
3220        Size::new(
3221            inset * 2.0
3222                + metrics
3223                    .color_picker_right_panel_width
3224                    .max(metrics.color_picker_map_size),
3225            inset * 2.0
3226                + row_count as f32 * metrics.color_picker_row_height
3227                + row_gap_count as f32 * metrics.color_picker_row_gap,
3228        )
3229    }
3230
3231    fn content_rect(&self, bounds: Rect) -> Rect {
3232        inset_rect(bounds, Insets::all(self.content_inset()))
3233    }
3234
3235    fn slider_rect(&self, bounds: Rect, index: usize) -> Rect {
3236        let content = self.content_rect(bounds);
3237        Rect::new(
3238            content.x(),
3239            content.y() + index as f32 * (self.row_height() + self.row_gap()),
3240            content.width(),
3241            self.row_height(),
3242        )
3243    }
3244
3245    fn slider_rect_for_channel(&self, bounds: Rect, channel: ColorSliderChannel) -> Option<Rect> {
3246        self.current_rows()
3247            .into_iter()
3248            .position(|row| row.channel == channel)
3249            .map(|index| self.slider_rect(bounds, index))
3250    }
3251
3252    fn current_values(&self) -> ColorSliderValues {
3253        match self.mode {
3254            SimpleColorPickerMode::Hsl => ColorSliderValues::from_hsl(
3255                self.editing_space,
3256                self.hue,
3257                self.hsl_saturation,
3258                self.hsl_lightness,
3259                self.alpha,
3260            ),
3261            SimpleColorPickerMode::Hsv => ColorSliderValues::from_hsv(
3262                self.editing_space,
3263                self.hue,
3264                self.hsv_saturation,
3265                self.hsv_value,
3266                self.alpha,
3267            ),
3268            SimpleColorPickerMode::Rgb => ColorSliderValues::from_rgb(
3269                self.editing_space,
3270                self.red,
3271                self.green,
3272                self.blue,
3273                self.alpha,
3274            ),
3275            SimpleColorPickerMode::Oklch => {
3276                ColorSliderValues::from_oklch(self.editing_space, self.oklch_with_alpha())
3277            }
3278        }
3279    }
3280
3281    fn resolved_values(&self) -> ColorSliderValues {
3282        match self.external_color() {
3283            Some(color) if !colors_close(self.current_color(), color) => {
3284                let mut values = ColorSliderValues::from_color(color);
3285                if values.oklch.chroma < OKLCH_ACHROMATIC_CHROMA {
3286                    values.oklch.hue = self.oklch.hue;
3287                }
3288                values
3289            }
3290            _ => self.current_values(),
3291        }
3292    }
3293
3294    fn current_rows(&self) -> Vec<ColorSliderRow> {
3295        color_slider_rows(self.mode, self.current_values(), self.show_alpha)
3296    }
3297
3298    fn resolved_rows(&self, values: ColorSliderValues) -> Vec<ColorSliderRow> {
3299        color_slider_rows(self.mode, values, self.show_alpha)
3300    }
3301
3302    fn sync_external_color(&mut self) -> bool {
3303        let Some(color) = self.external_color() else {
3304            return false;
3305        };
3306        if !colors_close(self.current_color(), color) {
3307            self.apply_color(color);
3308            return true;
3309        }
3310        false
3311    }
3312
3313    fn apply_color(&mut self, color: Color) {
3314        let values = ColorSliderValues::from_color(color);
3315        self.editing_space = color.space;
3316        self.hue = values.hue;
3317        self.hsv_saturation = values.hsv_saturation;
3318        self.hsv_value = values.hsv_value;
3319        self.hsl_saturation = values.hsl_saturation;
3320        self.hsl_lightness = values.hsl_lightness;
3321        self.red = values.red;
3322        self.green = values.green;
3323        self.blue = values.blue;
3324        self.set_oklch_from(values.oklch);
3325        self.alpha = values.alpha;
3326    }
3327
3328    fn set_color_space(&mut self, next_space: ColorSpace) {
3329        if self.editing_space == next_space {
3330            return;
3331        }
3332
3333        let current = self.current_color();
3334        self.apply_color(Color::new(
3335            next_space,
3336            current.red,
3337            current.green,
3338            current.blue,
3339            current.alpha,
3340        ));
3341    }
3342
3343    fn emit_change(&mut self, ctx: &mut EventCtx) {
3344        let color = self.current_color();
3345        if let Some(on_change) = &mut self.on_change {
3346            on_change(color);
3347        }
3348        if let Some(on_change) = &mut self.on_change_with_ctx {
3349            on_change(ctx, color);
3350        }
3351    }
3352
3353    fn update_from_position(
3354        &mut self,
3355        ctx: &mut EventCtx,
3356        bounds: Rect,
3357        channel: ColorSliderChannel,
3358        position: Point,
3359    ) {
3360        let Some(rect) = self.slider_rect_for_channel(bounds, channel) else {
3361            return;
3362        };
3363        let t = ColorSliderRowSlots::new(rect, &self.resolved_theme()).position(position.x);
3364        let max_channel_value = self.max_channel_value();
3365
3366        match channel {
3367            ColorSliderChannel::Hue => self.hue = t,
3368            ColorSliderChannel::HsvSaturation => self.hsv_saturation = t,
3369            ColorSliderChannel::HsvValue => {
3370                self.hsv_value = if self.hdr_capable() {
3371                    hdr_slider_to_value(t)
3372                } else {
3373                    t
3374                };
3375            }
3376            ColorSliderChannel::HslSaturation => self.hsl_saturation = t,
3377            ColorSliderChannel::HslLightness => self.hsl_lightness = max_channel_value * t,
3378            ColorSliderChannel::Alpha => self.alpha = t,
3379            ColorSliderChannel::Red => self.red = max_channel_value * t,
3380            ColorSliderChannel::Green => self.green = max_channel_value * t,
3381            ColorSliderChannel::Blue => self.blue = max_channel_value * t,
3382            ColorSliderChannel::OklchLightness => self.oklch.lightness = t,
3383            ColorSliderChannel::OklchChroma => self.oklch.chroma = t * OKLCH_MAX_CHROMA,
3384            ColorSliderChannel::OklchHue => self.oklch.hue = t * 360.0,
3385        }
3386        self.refresh_inactive_channels();
3387        self.emit_change(ctx);
3388    }
3389
3390    fn refresh_inactive_channels(&mut self) {
3391        let values = ColorSliderValues::from_color(self.current_color());
3392        match self.mode {
3393            SimpleColorPickerMode::Hsl => {
3394                self.hsv_saturation = values.hsv_saturation;
3395                self.hsv_value = values.hsv_value;
3396                self.red = values.red;
3397                self.green = values.green;
3398                self.blue = values.blue;
3399                self.set_oklch_from(values.oklch);
3400            }
3401            SimpleColorPickerMode::Hsv => {
3402                self.hsl_saturation = values.hsl_saturation;
3403                self.hsl_lightness = values.hsl_lightness;
3404                self.red = values.red;
3405                self.green = values.green;
3406                self.blue = values.blue;
3407                self.set_oklch_from(values.oklch);
3408            }
3409            SimpleColorPickerMode::Rgb => {
3410                self.hue = values.hue;
3411                self.hsv_saturation = values.hsv_saturation;
3412                self.hsv_value = values.hsv_value;
3413                self.hsl_saturation = values.hsl_saturation;
3414                self.hsl_lightness = values.hsl_lightness;
3415                self.set_oklch_from(values.oklch);
3416            }
3417            SimpleColorPickerMode::Oklch => {
3418                self.hue = values.hue;
3419                self.hsv_saturation = values.hsv_saturation;
3420                self.hsv_value = values.hsv_value;
3421                self.hsl_saturation = values.hsl_saturation;
3422                self.hsl_lightness = values.hsl_lightness;
3423                self.red = values.red;
3424                self.green = values.green;
3425                self.blue = values.blue;
3426            }
3427        }
3428    }
3429
3430    fn hit_channel(&self, bounds: Rect, position: Point) -> Option<ColorSliderChannel> {
3431        self.current_rows()
3432            .into_iter()
3433            .enumerate()
3434            .find_map(|(index, row)| {
3435                self.slider_rect(bounds, index)
3436                    .contains(position)
3437                    .then_some(row.channel)
3438            })
3439    }
3440
3441    fn color_semantics_text(&self, color: Color, hdr_capable: bool) -> String {
3442        if hdr_capable && is_hdr_color(color) {
3443            format!(
3444                "R {:.3} G {:.3} B {:.3} A {:.3}",
3445                color.red, color.green, color.blue, color.alpha
3446            )
3447        } else {
3448            format_color(color)
3449        }
3450    }
3451
3452    fn mode_label(&self) -> &'static str {
3453        match self.mode {
3454            SimpleColorPickerMode::Hsl => "HSL",
3455            SimpleColorPickerMode::Hsv => "HSV",
3456            SimpleColorPickerMode::Rgb => "RGB",
3457            SimpleColorPickerMode::Oklch => "OKLCH",
3458        }
3459    }
3460
3461    fn push_slider_semantics(&self, ctx: &mut SemanticsCtx, row: &ColorSliderRow, bounds: Rect) {
3462        let mut node = simple_color_picker_child_semantics_node(
3463            ctx.widget_id(),
3464            row.channel,
3465            SemanticsRole::Slider,
3466            bounds,
3467            row.name,
3468        );
3469        node.value = Some(SemanticsValue::Range {
3470            value: row.value as f64,
3471            min: row.min as f64,
3472            max: row.max as f64,
3473        });
3474        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
3475        ctx.push(node);
3476    }
3477}
3478
3479fn simple_color_picker_child_semantics_id(
3480    parent: WidgetId,
3481    channel: ColorSliderChannel,
3482) -> WidgetId {
3483    let slot = match channel {
3484        ColorSliderChannel::Hue => 1,
3485        ColorSliderChannel::HsvSaturation => 2,
3486        ColorSliderChannel::HsvValue => 3,
3487        ColorSliderChannel::HslSaturation => 4,
3488        ColorSliderChannel::HslLightness => 5,
3489        ColorSliderChannel::Alpha => 6,
3490        ColorSliderChannel::Red => 7,
3491        ColorSliderChannel::Green => 8,
3492        ColorSliderChannel::Blue => 9,
3493        ColorSliderChannel::OklchLightness => 10,
3494        ColorSliderChannel::OklchChroma => 11,
3495        ColorSliderChannel::OklchHue => 12,
3496    };
3497    const TAG: u64 = 4_u64 << 51;
3498    const LOW_MASK: u64 = (1_u64 << 51) - 1;
3499    WidgetId::new(TAG | (parent.get().wrapping_mul(397).wrapping_add(slot) & LOW_MASK))
3500}
3501
3502fn simple_color_picker_child_semantics_node(
3503    parent: WidgetId,
3504    channel: ColorSliderChannel,
3505    role: SemanticsRole,
3506    bounds: Rect,
3507    name: impl Into<String>,
3508) -> SemanticsNode {
3509    let mut node = SemanticsNode::new(
3510        simple_color_picker_child_semantics_id(parent, channel),
3511        role,
3512        bounds,
3513    );
3514    node.parent = Some(parent);
3515    node.name = Some(name.into());
3516    node
3517}
3518
3519impl Widget for SimpleColorPicker {
3520    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
3521        if self.sync_external_color() {
3522            ctx.request_paint();
3523            ctx.request_semantics();
3524        }
3525        match event {
3526            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
3527                if let Some(active) = self.active {
3528                    self.update_from_position(ctx, ctx.bounds(), active, pointer.position);
3529                    ctx.request_paint();
3530                    ctx.request_semantics();
3531                    ctx.set_handled();
3532                }
3533            }
3534            Event::Pointer(pointer)
3535                if pointer.kind == PointerEventKind::Down
3536                    && pointer.button == Some(PointerButton::Primary) =>
3537            {
3538                if let Some(active) = self.hit_channel(ctx.bounds(), pointer.position) {
3539                    self.active = Some(active);
3540                    self.update_from_position(ctx, ctx.bounds(), active, pointer.position);
3541                    ctx.request_focus();
3542                    ctx.request_pointer_capture(pointer.pointer_id);
3543                    ctx.request_paint();
3544                    ctx.request_semantics();
3545                    ctx.set_handled();
3546                }
3547            }
3548            Event::Pointer(pointer)
3549                if pointer.kind == PointerEventKind::Up
3550                    && pointer.button == Some(PointerButton::Primary) =>
3551            {
3552                if self.active.take().is_some() {
3553                    ctx.release_pointer_capture(pointer.pointer_id);
3554                    ctx.request_paint();
3555                    ctx.request_semantics();
3556                    ctx.set_handled();
3557                }
3558            }
3559            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
3560                if self.active.take().is_some() {
3561                    ctx.release_pointer_capture(pointer.pointer_id);
3562                    ctx.request_paint();
3563                    ctx.request_semantics();
3564                    ctx.set_handled();
3565                }
3566            }
3567            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
3568                let unit_step = if key.modifiers.shift { 0.1 } else { 0.02 };
3569                let value_step = if key.modifiers.shift { 0.5 } else { 0.1 };
3570                let chroma_step = if key.modifiers.shift { 0.02 } else { 0.005 };
3571                let lightness_step = if key.modifiers.shift { 0.05 } else { 0.01 };
3572                match key.key.as_str() {
3573                    "ArrowLeft" => match self.mode {
3574                        SimpleColorPickerMode::Hsl => {
3575                            self.hsl_saturation = (self.hsl_saturation - unit_step).clamp(0.0, 1.0)
3576                        }
3577                        SimpleColorPickerMode::Hsv => {
3578                            self.hsv_saturation = (self.hsv_saturation - unit_step).clamp(0.0, 1.0)
3579                        }
3580                        SimpleColorPickerMode::Rgb => {
3581                            self.red = (self.red - value_step).clamp(0.0, self.max_channel_value())
3582                        }
3583                        SimpleColorPickerMode::Oklch => {
3584                            self.oklch.chroma =
3585                                (self.oklch.chroma - chroma_step).clamp(0.0, OKLCH_MAX_CHROMA)
3586                        }
3587                    },
3588                    "ArrowRight" => match self.mode {
3589                        SimpleColorPickerMode::Hsl => {
3590                            self.hsl_saturation = (self.hsl_saturation + unit_step).clamp(0.0, 1.0)
3591                        }
3592                        SimpleColorPickerMode::Hsv => {
3593                            self.hsv_saturation = (self.hsv_saturation + unit_step).clamp(0.0, 1.0)
3594                        }
3595                        SimpleColorPickerMode::Rgb => {
3596                            self.red = (self.red + value_step).clamp(0.0, self.max_channel_value())
3597                        }
3598                        SimpleColorPickerMode::Oklch => {
3599                            self.oklch.chroma =
3600                                (self.oklch.chroma + chroma_step).clamp(0.0, OKLCH_MAX_CHROMA)
3601                        }
3602                    },
3603                    "ArrowUp" => match self.mode {
3604                        SimpleColorPickerMode::Hsl => {
3605                            self.hsl_lightness = (self.hsl_lightness + value_step)
3606                                .clamp(0.0, self.max_channel_value())
3607                        }
3608                        SimpleColorPickerMode::Hsv => {
3609                            self.hsv_value =
3610                                (self.hsv_value + value_step).clamp(0.0, self.max_channel_value())
3611                        }
3612                        SimpleColorPickerMode::Rgb => {
3613                            self.green =
3614                                (self.green + value_step).clamp(0.0, self.max_channel_value())
3615                        }
3616                        SimpleColorPickerMode::Oklch => {
3617                            self.oklch.lightness =
3618                                (self.oklch.lightness + lightness_step).clamp(0.0, 1.0)
3619                        }
3620                    },
3621                    "ArrowDown" => match self.mode {
3622                        SimpleColorPickerMode::Hsl => {
3623                            self.hsl_lightness = (self.hsl_lightness - value_step)
3624                                .clamp(0.0, self.max_channel_value())
3625                        }
3626                        SimpleColorPickerMode::Hsv => {
3627                            self.hsv_value =
3628                                (self.hsv_value - value_step).clamp(0.0, self.max_channel_value())
3629                        }
3630                        SimpleColorPickerMode::Rgb => {
3631                            self.green =
3632                                (self.green - value_step).clamp(0.0, self.max_channel_value())
3633                        }
3634                        SimpleColorPickerMode::Oklch => {
3635                            self.oklch.lightness =
3636                                (self.oklch.lightness - lightness_step).clamp(0.0, 1.0)
3637                        }
3638                    },
3639                    _ => return,
3640                }
3641                self.refresh_inactive_channels();
3642                self.emit_change(ctx);
3643                ctx.request_paint();
3644                ctx.request_semantics();
3645                ctx.set_handled();
3646            }
3647            _ => {}
3648        }
3649    }
3650
3651    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3652        self.sync_external_color();
3653        constraints.clamp(self.desired_size())
3654    }
3655
3656    fn paint(&self, ctx: &mut PaintCtx) {
3657        let theme = self.resolved_theme();
3658        let values = self.resolved_values();
3659        draw_surface(ctx, ctx.bounds(), &theme, self.focus_animation.get(ctx));
3660
3661        for (index, row) in self.resolved_rows(values).into_iter().enumerate() {
3662            let rect = self.slider_rect(ctx.bounds(), index);
3663            paint_color_slider_row(ctx, rect, &row, values, &theme);
3664        }
3665    }
3666
3667    fn semantics(&self, ctx: &mut SemanticsCtx) {
3668        let values = self.resolved_values();
3669        let mut node =
3670            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ColorPicker, ctx.bounds());
3671        node.name = Some(self.name.clone());
3672        node.description = Some(format!(
3673            "{} sliders; {} editing space; {} range available",
3674            self.mode_label(),
3675            editing_space_label(values.editing_space),
3676            if values.hdr_capable { "HDR" } else { "SDR" }
3677        ));
3678        node.state.focused = ctx.is_focused();
3679        node.value = Some(SemanticsValue::Text(
3680            self.color_semantics_text(values.color, values.hdr_capable),
3681        ));
3682        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
3683        ctx.push(node);
3684
3685        for (index, row) in self.resolved_rows(values).iter().enumerate() {
3686            self.push_slider_semantics(ctx, row, self.slider_rect(ctx.bounds(), index));
3687        }
3688    }
3689
3690    fn accepts_focus(&self) -> bool {
3691        true
3692    }
3693
3694    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3695        let theme = self.resolved_theme();
3696        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
3697        ctx.request_paint();
3698        ctx.request_semantics();
3699    }
3700}
3701
3702impl Widget for ColorPicker {
3703    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
3704        if !self.enabled.get() {
3705            // Disabled, the widget takes no input, but it lets go of a
3706            // pointer it captured while enabled.
3707            if let Event::Pointer(pointer) = event
3708                && pointer.kind == PointerEventKind::Up
3709            {
3710                ctx.release_pointer_capture(pointer.pointer_id);
3711            }
3712            return;
3713        }
3714        if self.sync_external_color() {
3715            ctx.request_paint();
3716            ctx.request_semantics();
3717        }
3718        match event {
3719            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
3720                if let Some(active) = self.active {
3721                    self.update_from_position(ctx, ctx.bounds(), active, pointer.position);
3722                    ctx.request_paint();
3723                    ctx.request_semantics();
3724                    ctx.set_handled();
3725                }
3726            }
3727            Event::Pointer(pointer)
3728                if pointer.kind == PointerEventKind::Down
3729                    && pointer.button == Some(PointerButton::Primary) =>
3730            {
3731                if let Some(option) = self.encoding_option_at(ctx.bounds(), pointer.position) {
3732                    self.active = Some(ActiveChannel::EncodingOption(option));
3733                    ctx.request_focus();
3734                    ctx.request_pointer_capture(pointer.pointer_id);
3735                    ctx.request_paint();
3736                    ctx.request_semantics();
3737                    ctx.set_handled();
3738                    return;
3739                }
3740
3741                let active = self.hit_channel(ctx.bounds(), pointer.position);
3742                if let Some(active) = active {
3743                    self.active = Some(active);
3744                    if active == ActiveChannel::EncodingSelector {
3745                        self.encoding_dropdown_open = !self.encoding_dropdown_open;
3746                    } else {
3747                        self.encoding_dropdown_open = false;
3748                        self.update_from_position(ctx, ctx.bounds(), active, pointer.position);
3749                    }
3750                    ctx.request_focus();
3751                    ctx.request_pointer_capture(pointer.pointer_id);
3752                    ctx.request_paint();
3753                    ctx.request_semantics();
3754                    ctx.set_handled();
3755                } else if self.encoding_dropdown_open {
3756                    self.encoding_dropdown_open = false;
3757                    ctx.request_paint();
3758                    ctx.request_semantics();
3759                }
3760            }
3761            Event::Pointer(pointer)
3762                if pointer.kind == PointerEventKind::Up
3763                    && pointer.button == Some(PointerButton::Primary) =>
3764            {
3765                if let Some(active) = self.active.take() {
3766                    if let ActiveChannel::EncodingOption(index) = active {
3767                        if self
3768                            .encoding_option_rect(ctx.bounds(), index)
3769                            .contains(pointer.position)
3770                        {
3771                            self.set_editing_space(ctx, Self::ENCODING_OPTIONS[index]);
3772                        }
3773                        self.encoding_dropdown_open = false;
3774                    }
3775                    ctx.release_pointer_capture(pointer.pointer_id);
3776                    ctx.request_paint();
3777                    ctx.request_semantics();
3778                    ctx.set_handled();
3779                }
3780            }
3781            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
3782                if self.active.take().is_some() {
3783                    self.encoding_dropdown_open = false;
3784                    ctx.release_pointer_capture(pointer.pointer_id);
3785                    ctx.request_paint();
3786                    ctx.request_semantics();
3787                    ctx.set_handled();
3788                }
3789            }
3790            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
3791                let saturation_step = if key.modifiers.shift { 0.1 } else { 0.02 };
3792                let value_step = if key.modifiers.shift { 0.5 } else { 0.1 };
3793                match key.key.as_str() {
3794                    "ArrowLeft" => {
3795                        self.saturation = (self.saturation - saturation_step).clamp(0.0, 1.0)
3796                    }
3797                    "ArrowRight" => {
3798                        self.saturation = (self.saturation + saturation_step).clamp(0.0, 1.0)
3799                    }
3800                    "ArrowUp" => {
3801                        self.value = (self.value + value_step).clamp(0.0, self.max_channel_value())
3802                    }
3803                    "ArrowDown" => {
3804                        self.value = (self.value - value_step).clamp(0.0, self.max_channel_value())
3805                    }
3806                    _ => return,
3807                }
3808                self.emit_change(ctx);
3809                ctx.request_paint();
3810                ctx.request_semantics();
3811                ctx.set_handled();
3812            }
3813            _ => {}
3814        }
3815    }
3816
3817    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3818        self.sync_external_color();
3819        constraints.clamp(self.desired_size())
3820    }
3821
3822    fn paint(&self, ctx: &mut PaintCtx) {
3823        self.enabled.observe(|source| {
3824            ctx.observe(source);
3825        });
3826        let theme = self.paint_theme();
3827        let resolved = self.resolved_state();
3828        let current = resolved.color;
3829        let wheel = self.color_wheel_rect(ctx.bounds());
3830        let map = self.saturation_value_rect(ctx.bounds());
3831        let encoding = self.encoding_rect(ctx.bounds());
3832
3833        draw_surface(ctx, ctx.bounds(), &theme, self.focus_animation.get(ctx));
3834        paint_picker_header(
3835            ctx,
3836            self.current_swatch_rect(ctx.bounds()),
3837            self.previous_swatch_rect(ctx.bounds()),
3838            &theme,
3839            self.previous_color,
3840            current,
3841        );
3842        paint_dropdown(
3843            ctx,
3844            encoding,
3845            &theme,
3846            editing_space_label(resolved.editing_space),
3847        );
3848
3849        paint_color_wheel(ctx, wheel, &theme);
3850        paint_wheel_marker(ctx, wheel, resolved.hue, &theme);
3851
3852        paint_saturation_value_plane(
3853            ctx,
3854            map,
3855            resolved.editing_space,
3856            resolved.hue,
3857            resolved.max_channel_value,
3858            &theme,
3859        );
3860        let marker = Point::new(
3861            map.x() + resolved.saturation * map.width(),
3862            map.y()
3863                + (1.0
3864                    - if resolved.hdr_capable {
3865                        hdr_value_to_slider(resolved.value)
3866                    } else {
3867                        resolved.value.clamp(0.0, 1.0)
3868                    })
3869                    * map.height(),
3870        );
3871        paint_marker(ctx, marker, contrast_color(current, &theme), &theme);
3872
3873        let slider_values = ColorSliderValues::from_hsv(
3874            resolved.editing_space,
3875            resolved.hue,
3876            resolved.saturation,
3877            resolved.value,
3878            resolved.alpha,
3879        );
3880        for (index, row) in
3881            color_slider_rows(SimpleColorPickerMode::Hsv, slider_values, self.show_alpha)
3882                .into_iter()
3883                .enumerate()
3884        {
3885            let rect = self.left_slider_rect(ctx.bounds(), index);
3886            paint_color_slider_row(ctx, rect, &row, slider_values, &theme);
3887        }
3888
3889        for (index, row) in color_slider_rows(SimpleColorPickerMode::Rgb, slider_values, false)
3890            .into_iter()
3891            .enumerate()
3892        {
3893            let rect = self.rgb_row_rect(ctx.bounds(), index);
3894            paint_color_slider_row(ctx, rect, &row, slider_values, &theme);
3895        }
3896
3897        if resolved.hdr_capable && is_hdr_color(current) {
3898            paint_disabled_field(
3899                ctx,
3900                self.hex_rect(ctx.bounds()),
3901                &theme,
3902                "HDR hex unavailable",
3903            );
3904        } else {
3905            paint_hex_field(
3906                ctx,
3907                self.hex_rect(ctx.bounds()),
3908                &theme,
3909                &format_color(current),
3910            );
3911        }
3912
3913        if self.encoding_dropdown_open {
3914            paint_encoding_menu(
3915                ctx,
3916                self.encoding_menu_rect(ctx.bounds()),
3917                &theme,
3918                resolved.editing_space,
3919                self.encoding_menu_row_height(),
3920            );
3921        }
3922    }
3923
3924    fn semantics(&self, ctx: &mut SemanticsCtx) {
3925        self.enabled.observe(|source| {
3926            ctx.observe(source);
3927        });
3928        let enabled = self.enabled.get();
3929        let resolved = self.resolved_state();
3930        let current = resolved.color;
3931        let mut node =
3932            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ColorPicker, ctx.bounds());
3933        node.name = Some(self.name.clone());
3934        node.description = Some(format!(
3935            "{} editing space; {} range available",
3936            editing_space_label(resolved.editing_space),
3937            if resolved.hdr_capable { "HDR" } else { "SDR" }
3938        ));
3939        node.state.focused = ctx.is_focused();
3940        node.value = Some(SemanticsValue::Text(
3941            self.color_semantics_text(current, resolved.hdr_capable),
3942        ));
3943        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
3944        if !enabled {
3945            node.state.disabled = true;
3946            node.actions.clear();
3947        }
3948        ctx.push(node);
3949        self.push_component_semantics(ctx, resolved);
3950    }
3951
3952    fn accepts_focus(&self) -> bool {
3953        self.enabled.get()
3954    }
3955
3956    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3957        let theme = self.resolved_theme();
3958        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
3959        ctx.request_paint();
3960        ctx.request_semantics();
3961    }
3962}
3963
3964fn color_slider_rows(
3965    mode: SimpleColorPickerMode,
3966    values: ColorSliderValues,
3967    show_alpha: bool,
3968) -> Vec<ColorSliderRow> {
3969    let mut rows = Vec::with_capacity(if show_alpha { 4 } else { 3 });
3970    match mode {
3971        SimpleColorPickerMode::Hsl => {
3972            rows.push(hue_slider_row(values.hue));
3973            rows.push(percent_slider_row(
3974                ColorSliderChannel::HslSaturation,
3975                values.hsl_saturation,
3976            ));
3977            rows.push(channel_slider_row(
3978                ColorSliderChannel::HslLightness,
3979                values.hsl_lightness,
3980                values.max_channel_value,
3981            ));
3982        }
3983        SimpleColorPickerMode::Hsv => {
3984            rows.push(hue_slider_row(values.hue));
3985            rows.push(percent_slider_row(
3986                ColorSliderChannel::HsvSaturation,
3987                values.hsv_saturation,
3988            ));
3989            rows.push(ColorSliderRow::new(
3990                ColorSliderChannel::HsvValue,
3991                values.hsv_value,
3992                0.0,
3993                values.max_channel_value,
3994                if values.hdr_capable {
3995                    hdr_value_to_slider(values.hsv_value)
3996                } else {
3997                    values.hsv_value.clamp(0.0, 1.0)
3998                },
3999                format!("{:.3}", values.hsv_value),
4000            ));
4001        }
4002        SimpleColorPickerMode::Rgb => {
4003            rows.push(channel_slider_row(
4004                ColorSliderChannel::Red,
4005                values.red,
4006                values.max_channel_value,
4007            ));
4008            rows.push(channel_slider_row(
4009                ColorSliderChannel::Green,
4010                values.green,
4011                values.max_channel_value,
4012            ));
4013            rows.push(channel_slider_row(
4014                ColorSliderChannel::Blue,
4015                values.blue,
4016                values.max_channel_value,
4017            ));
4018        }
4019        SimpleColorPickerMode::Oklch => {
4020            let oklch = values.oklch;
4021            rows.push(percent_slider_row(
4022                ColorSliderChannel::OklchLightness,
4023                oklch.lightness.clamp(0.0, 1.0),
4024            ));
4025            rows.push(ColorSliderRow::new(
4026                ColorSliderChannel::OklchChroma,
4027                oklch.chroma,
4028                0.0,
4029                OKLCH_MAX_CHROMA,
4030                oklch.chroma / OKLCH_MAX_CHROMA,
4031                format!("{:.3}", oklch.chroma),
4032            ));
4033            rows.push(ColorSliderRow::new(
4034                ColorSliderChannel::OklchHue,
4035                oklch.hue,
4036                0.0,
4037                360.0,
4038                oklch.hue / 360.0,
4039                format!("{:.1}", oklch.hue),
4040            ));
4041        }
4042    }
4043
4044    if show_alpha {
4045        rows.push(percent_slider_row(ColorSliderChannel::Alpha, values.alpha));
4046    }
4047    rows
4048}
4049
4050fn hue_slider_row(hue: f32) -> ColorSliderRow {
4051    ColorSliderRow::new(
4052        ColorSliderChannel::Hue,
4053        hue * 360.0,
4054        0.0,
4055        360.0,
4056        hue,
4057        format!("{:.2}", hue * 360.0),
4058    )
4059}
4060
4061fn percent_slider_row(channel: ColorSliderChannel, value: f32) -> ColorSliderRow {
4062    ColorSliderRow::new(
4063        channel,
4064        value * 100.0,
4065        0.0,
4066        100.0,
4067        value,
4068        format!("{:.1}", value * 100.0),
4069    )
4070}
4071
4072fn channel_slider_row(channel: ColorSliderChannel, value: f32, max_value: f32) -> ColorSliderRow {
4073    ColorSliderRow::new(
4074        channel,
4075        value,
4076        0.0,
4077        max_value,
4078        value / max_value.max(0.0001),
4079        format!("{:.3}", value),
4080    )
4081}
4082
4083fn paint_color_slider_row(
4084    ctx: &mut PaintCtx,
4085    row_rect: Rect,
4086    row: &ColorSliderRow,
4087    values: ColorSliderValues,
4088    theme: &DefaultTheme,
4089) {
4090    let slots = ColorSliderRowSlots::new(row_rect, theme);
4091    let rect = slots.track;
4092    match row.channel {
4093        ColorSliderChannel::Hue => paint_hue_bar(ctx, rect, theme),
4094        ColorSliderChannel::HsvSaturation => paint_saturation_bar(
4095            ctx,
4096            rect,
4097            values.editing_space,
4098            values.hue,
4099            values.hsv_value.max(1.0),
4100            theme,
4101        ),
4102        ColorSliderChannel::HsvValue => paint_value_bar(
4103            ctx,
4104            rect,
4105            values.editing_space,
4106            values.hue,
4107            values.hsv_saturation,
4108            values.hdr_capable,
4109            theme,
4110        ),
4111        ColorSliderChannel::HslSaturation => paint_hsl_saturation_bar(
4112            ctx,
4113            rect,
4114            values.editing_space,
4115            values.hue,
4116            values.hsl_lightness,
4117            values.max_channel_value,
4118            theme,
4119        ),
4120        ColorSliderChannel::HslLightness => paint_hsl_lightness_bar(
4121            ctx,
4122            rect,
4123            values.editing_space,
4124            values.hue,
4125            values.hsl_saturation,
4126            values.max_channel_value,
4127            theme,
4128        ),
4129        ColorSliderChannel::Alpha => {
4130            draw_checkerboard(ctx, rect, theme.metrics.color_swatch_checker_size, theme);
4131            paint_alpha_bar(ctx, rect, values.color, theme);
4132        }
4133        ColorSliderChannel::Red => {
4134            paint_rgb_channel_bar(ctx, rect, values.color, 0, values.max_channel_value, theme)
4135        }
4136        ColorSliderChannel::Green => {
4137            paint_rgb_channel_bar(ctx, rect, values.color, 1, values.max_channel_value, theme)
4138        }
4139        ColorSliderChannel::Blue => {
4140            paint_rgb_channel_bar(ctx, rect, values.color, 2, values.max_channel_value, theme)
4141        }
4142        ColorSliderChannel::OklchLightness => paint_oklch_bar(
4143            ctx,
4144            rect,
4145            values.editing_space,
4146            |t| values.oklch.with_lightness(t),
4147            theme,
4148        ),
4149        ColorSliderChannel::OklchChroma => {
4150            let space = values.editing_space;
4151            paint_oklch_bar(
4152                ctx,
4153                rect,
4154                space,
4155                |t| values.oklch.with_chroma(t * OKLCH_MAX_CHROMA),
4156                theme,
4157            );
4158            let gamut_edge = oklch_gamut_chroma(space, values.oklch) / OKLCH_MAX_CHROMA;
4159            if gamut_edge < 0.995 {
4160                ctx.fill_rect(
4161                    Rect::new(
4162                        rect.x() + rect.width() * gamut_edge,
4163                        rect.y(),
4164                        1.0,
4165                        rect.height(),
4166                    ),
4167                    theme.surfaces.color_picker_hdr_divider,
4168                );
4169            }
4170        }
4171        ColorSliderChannel::OklchHue => paint_oklch_bar(
4172            ctx,
4173            rect,
4174            values.editing_space,
4175            |t| Oklch {
4176                hue: t * 360.0,
4177                ..values.oklch
4178            },
4179            theme,
4180        ),
4181    }
4182
4183    paint_labeled_row_text(
4184        ctx,
4185        row_rect,
4186        row.label,
4187        &row.value_text,
4188        theme,
4189        theme.palette.text_muted,
4190    );
4191    paint_marker(
4192        ctx,
4193        Point::new(
4194            rect.x() + row.position * rect.width(),
4195            rect.y() + rect.height() * 0.5,
4196        ),
4197        theme.palette.border_focus,
4198        theme,
4199    );
4200}
4201
4202fn paint_picker_header(
4203    ctx: &mut PaintCtx,
4204    current_rect: Rect,
4205    previous_rect: Rect,
4206    theme: &DefaultTheme,
4207    previous: Color,
4208    current: Color,
4209) {
4210    let palette = theme.palette;
4211    let metrics = theme.metrics;
4212    let radius = metrics.indicator_corner_radius;
4213    let current_rect = snap_to_pixels(ctx, current_rect);
4214    let previous_rect = snap_to_pixels(ctx, previous_rect);
4215    draw_checkerboard(ctx, current_rect, metrics.color_swatch_checker_size, theme);
4216    draw_checkerboard(ctx, previous_rect, metrics.color_swatch_checker_size, theme);
4217    ctx.fill(Path::rounded_rect(current_rect, radius), current);
4218    ctx.fill(Path::rounded_rect(previous_rect, radius), previous);
4219    stroke_border(
4220        ctx,
4221        current_rect,
4222        radius,
4223        physical_pixels(ctx, metrics.border_width.max(1.0)),
4224        palette.border_focus,
4225    );
4226    stroke_border(
4227        ctx,
4228        previous_rect,
4229        radius,
4230        physical_pixels(ctx, metrics.border_width.max(1.0)),
4231        palette.border,
4232    );
4233}
4234
4235fn paint_color_wheel(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
4236    let center = Point::new(
4237        rect.x() + rect.width() * 0.5,
4238        rect.y() + rect.height() * 0.5,
4239    );
4240    let outer = rect.width().min(rect.height()) * 0.5;
4241    let inner = outer * 0.55;
4242    ctx.draw_shader_rect(rect, WidgetShader::ColorWheel);
4243    ctx.stroke(
4244        Path::circle(center, outer - 1.0),
4245        theme.surfaces.color_picker_chrome_border,
4246        StrokeStyle::new(1.0),
4247    );
4248    ctx.stroke(
4249        Path::circle(center, inner),
4250        theme.surfaces.color_picker_chrome_border,
4251        StrokeStyle::new(1.0),
4252    );
4253}
4254
4255fn paint_wheel_marker(ctx: &mut PaintCtx, rect: Rect, hue: f32, theme: &DefaultTheme) {
4256    let center = Point::new(
4257        rect.x() + rect.width() * 0.5,
4258        rect.y() + rect.height() * 0.5,
4259    );
4260    let outer = rect.width().min(rect.height()) * 0.5;
4261    let inner = outer * 0.55;
4262    let radius = (outer + inner) * 0.5;
4263    let angle = hue * std::f32::consts::TAU;
4264    let point = Point::new(
4265        center.x + angle.cos() * radius,
4266        center.y + angle.sin() * radius,
4267    );
4268    paint_marker(ctx, point, theme.surfaces.color_picker_marker_dark, theme);
4269}
4270
4271fn paint_saturation_value_plane(
4272    ctx: &mut PaintCtx,
4273    rect: Rect,
4274    space: ColorSpace,
4275    hue: f32,
4276    max_value: f32,
4277    theme: &DefaultTheme,
4278) {
4279    ctx.draw_shader_rect(
4280        rect,
4281        WidgetShader::ColorPickerSaturationValuePlane {
4282            color_space: space,
4283            hue,
4284            max_value,
4285        },
4286    );
4287    stroke_border(
4288        ctx,
4289        rect,
4290        0.0,
4291        1.0,
4292        theme.surfaces.color_picker_plane_border,
4293    );
4294    let sdr_marker = Rect::new(
4295        rect.x(),
4296        rect.y()
4297            + rect.height()
4298                * (1.0
4299                    - if max_value <= 1.0001 {
4300                        1.0
4301                    } else {
4302                        hdr_value_to_slider(1.0)
4303                    }),
4304        rect.width(),
4305        1.0,
4306    );
4307    ctx.fill_rect(sdr_marker, theme.surfaces.color_picker_sdr_marker);
4308}
4309
4310fn paint_hue_bar(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
4311    ctx.draw_shader_rect(rect, WidgetShader::ColorPickerHueBar);
4312    paint_bar_border(ctx, rect, theme);
4313}
4314
4315fn paint_saturation_bar(
4316    ctx: &mut PaintCtx,
4317    rect: Rect,
4318    space: ColorSpace,
4319    hue: f32,
4320    value: f32,
4321    theme: &DefaultTheme,
4322) {
4323    ctx.draw_shader_rect(
4324        rect,
4325        WidgetShader::ColorPickerSaturationBar {
4326            color_space: space,
4327            hue,
4328            value,
4329        },
4330    );
4331    paint_bar_border(ctx, rect, theme);
4332}
4333
4334fn paint_bar_border(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
4335    stroke_border(ctx, rect, 0.0, 1.0, theme.surfaces.color_picker_bar_border);
4336}
4337
4338fn paint_value_bar(
4339    ctx: &mut PaintCtx,
4340    rect: Rect,
4341    space: ColorSpace,
4342    hue: f32,
4343    saturation: f32,
4344    hdr_capable: bool,
4345    theme: &DefaultTheme,
4346) {
4347    ctx.draw_shader_rect(
4348        rect,
4349        WidgetShader::ColorPickerValueBar {
4350            color_space: space,
4351            hue,
4352            saturation,
4353            max_value: if hdr_capable {
4354                ColorPicker::MAX_HDR_VALUE
4355            } else {
4356                1.0
4357            },
4358        },
4359    );
4360    paint_bar_border(ctx, rect, theme);
4361    if hdr_capable {
4362        let divider_x = rect.x() + rect.width() * 0.5;
4363        ctx.fill_rect(
4364            Rect::new(divider_x, rect.y(), 1.0, rect.height()),
4365            theme.surfaces.color_picker_hdr_divider,
4366        );
4367    }
4368}
4369
4370fn paint_hsl_saturation_bar(
4371    ctx: &mut PaintCtx,
4372    rect: Rect,
4373    space: ColorSpace,
4374    hue: f32,
4375    lightness: f32,
4376    max_value: f32,
4377    theme: &DefaultTheme,
4378) {
4379    paint_linear_color_bar(
4380        ctx,
4381        rect,
4382        vec![
4383            GradientStop {
4384                offset: 0.0,
4385                color: hsl_to_color(space, hue, 0.0, lightness, 1.0, max_value),
4386            },
4387            GradientStop {
4388                offset: 1.0,
4389                color: hsl_to_color(space, hue, 1.0, lightness, 1.0, max_value),
4390            },
4391        ],
4392        theme,
4393    );
4394}
4395
4396fn paint_hsl_lightness_bar(
4397    ctx: &mut PaintCtx,
4398    rect: Rect,
4399    space: ColorSpace,
4400    hue: f32,
4401    saturation: f32,
4402    max_value: f32,
4403    theme: &DefaultTheme,
4404) {
4405    paint_linear_color_bar(
4406        ctx,
4407        rect,
4408        vec![
4409            GradientStop {
4410                offset: 0.0,
4411                color: hsl_to_color(space, hue, saturation, 0.0, 1.0, max_value),
4412            },
4413            GradientStop {
4414                offset: 0.5,
4415                color: hsl_to_color(space, hue, saturation, max_value * 0.5, 1.0, max_value),
4416            },
4417            GradientStop {
4418                offset: 1.0,
4419                color: hsl_to_color(space, hue, saturation, max_value, 1.0, max_value),
4420            },
4421        ],
4422        theme,
4423    );
4424    if max_value > 1.0001 {
4425        let divider_x = rect.x() + rect.width() / max_value.max(1.0);
4426        ctx.fill_rect(
4427            Rect::new(divider_x, rect.y(), 1.0, rect.height()),
4428            theme.surfaces.color_picker_hdr_divider,
4429        );
4430    }
4431}
4432
4433/// Paints `sample(t)` for `t` across the track, gamut-mapped into `space`.
4434fn paint_oklch_bar(
4435    ctx: &mut PaintCtx,
4436    rect: Rect,
4437    space: ColorSpace,
4438    sample: impl Fn(f32) -> Oklch,
4439    theme: &DefaultTheme,
4440) {
4441    const STOPS: usize = 16;
4442    let stops = (0..=STOPS)
4443        .map(|index| {
4444            let offset = index as f32 / STOPS as f32;
4445            GradientStop {
4446                offset,
4447                color: oklch_to_color(
4448                    space,
4449                    Oklch {
4450                        alpha: 1.0,
4451                        ..sample(offset)
4452                    },
4453                ),
4454            }
4455        })
4456        .collect();
4457    paint_linear_color_bar(ctx, rect, stops, theme);
4458}
4459
4460fn paint_linear_color_bar(
4461    ctx: &mut PaintCtx,
4462    rect: Rect,
4463    stops: Vec<GradientStop>,
4464    theme: &DefaultTheme,
4465) {
4466    ctx.fill_rect(
4467        rect,
4468        Brush::LinearGradient {
4469            start: rect.origin,
4470            end: Point::new(rect.max_x(), rect.y()),
4471            stops,
4472        },
4473    );
4474    paint_bar_border(ctx, rect, theme);
4475}
4476
4477fn paint_alpha_bar(ctx: &mut PaintCtx, rect: Rect, color: Color, theme: &DefaultTheme) {
4478    ctx.draw_shader_rect(rect, WidgetShader::ColorPickerAlphaBar { color });
4479    paint_bar_border(ctx, rect, theme);
4480}
4481
4482fn paint_rgb_channel_bar(
4483    ctx: &mut PaintCtx,
4484    rect: Rect,
4485    current: Color,
4486    channel_index: usize,
4487    max_value: f32,
4488    theme: &DefaultTheme,
4489) {
4490    ctx.draw_shader_rect(
4491        rect,
4492        WidgetShader::ColorPickerRgbChannelBar {
4493            color: current,
4494            channel: channel_index as u32,
4495            max_value,
4496        },
4497    );
4498    paint_bar_border(ctx, rect, theme);
4499}
4500
4501/// A color slider row: the channel label, the colored track, and the value,
4502/// side by side so neither text sits on the gradient or under the marker.
4503#[derive(Debug, Clone, Copy)]
4504struct ColorSliderRowSlots {
4505    label: Rect,
4506    track: Rect,
4507    value: Rect,
4508}
4509
4510impl ColorSliderRowSlots {
4511    /// Room between the track and its neighbors for the marker, which is
4512    /// centered on the track's ends at the extremes.
4513    const MARKER_CLEARANCE: f32 = 9.0;
4514
4515    fn new(rect: Rect, theme: &DefaultTheme) -> Self {
4516        let label_width = (theme.metrics.icon_size + theme.spacing * 2.0).max(20.0);
4517        let value_width = (rect.width() * 0.18).clamp(44.0, 64.0);
4518        let label = Rect::new(
4519            rect.x() + theme.spacing * 1.5,
4520            rect.y(),
4521            label_width,
4522            rect.height(),
4523        );
4524        let value = Rect::new(
4525            rect.max_x() - value_width - theme.spacing,
4526            rect.y(),
4527            value_width,
4528            rect.height(),
4529        );
4530        let track_x = label.max_x() + Self::MARKER_CLEARANCE;
4531        let track = Rect::new(
4532            track_x,
4533            rect.y(),
4534            (value.x() - Self::MARKER_CLEARANCE - track_x).max(1.0),
4535            rect.height(),
4536        );
4537        Self {
4538            label,
4539            track,
4540            value,
4541        }
4542    }
4543
4544    /// Where along the track `x` falls, from 0 to 1.
4545    fn position(&self, x: f32) -> f32 {
4546        ((x - self.track.x()) / self.track.width().max(1.0)).clamp(0.0, 1.0)
4547    }
4548}
4549
4550fn paint_labeled_row_text(
4551    ctx: &mut PaintCtx,
4552    rect: Rect,
4553    label: &str,
4554    value_text: &str,
4555    theme: &DefaultTheme,
4556    value_color: Color,
4557) {
4558    let text = theme.text.xs;
4559    let label_style = text_token_style(theme, text, theme.palette.text_muted);
4560    let value_style = numeric_text_style(text_token_style(theme, text, value_color));
4561    let slots = ColorSliderRowSlots::new(rect, theme);
4562    let label_slot = slots.label;
4563    let value_slot = slots.value;
4564    ctx.push_clip_rect(label_slot);
4565    paint_text_line(ctx, label_slot, label, &label_style, TextAlign::Start);
4566    ctx.pop_clip();
4567    ctx.push_clip_rect(value_slot);
4568    paint_text_line(ctx, value_slot, value_text, &value_style, TextAlign::End);
4569    ctx.pop_clip();
4570}
4571
4572fn paint_dropdown(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, label: &str) {
4573    let metrics = theme.metrics;
4574    let radius = metrics.corner_radius;
4575    let text = theme.text.xs;
4576    let padding = metrics.text_input_padding;
4577    let style = text_token_style(theme, text, theme.palette.text);
4578    let text_slot = Rect::new(
4579        rect.x() + padding.left.max(theme.spacing * 2.0),
4580        rect.y(),
4581        rect.width() - padding.left.max(theme.spacing * 2.0) - metrics.icon_size - theme.spacing,
4582        rect.height(),
4583    );
4584    draw_control_shape(
4585        ctx,
4586        rect,
4587        radius,
4588        physical_pixels(ctx, metrics.border_width.max(1.0)),
4589        theme.palette.control,
4590        theme.palette.border_focus,
4591    );
4592    ctx.push_clip_rect(text_slot);
4593    paint_text_line(ctx, text_slot, label, &style, TextAlign::Start);
4594    ctx.pop_clip();
4595    ctx.stroke(
4596        dropdown_chevron_path(rect),
4597        theme.palette.placeholder,
4598        StrokeStyle::new(1.4),
4599    );
4600}
4601
4602fn paint_encoding_menu(
4603    ctx: &mut PaintCtx,
4604    rect: Rect,
4605    theme: &DefaultTheme,
4606    selected: ColorSpace,
4607    row_height: f32,
4608) {
4609    let metrics = theme.metrics;
4610    let radius = metrics.corner_radius;
4611    let text = theme.text.xs;
4612    draw_control_shape(
4613        ctx,
4614        rect,
4615        radius,
4616        physical_pixels(ctx, metrics.border_width.max(1.0)),
4617        theme.palette.surface_raised,
4618        theme.palette.border_focus,
4619    );
4620
4621    for (index, space) in ColorPicker::ENCODING_OPTIONS.iter().copied().enumerate() {
4622        let row = Rect::new(
4623            rect.x(),
4624            rect.y() + index as f32 * row_height,
4625            rect.width(),
4626            row_height,
4627        );
4628        if space == selected {
4629            let selected_rect = inset_rect(row, metrics.menu_item_padding);
4630            ctx.fill(
4631                Path::rounded_rect(
4632                    selected_rect,
4633                    (radius - metrics.menu_item_padding.top).max(0.0),
4634                ),
4635                theme.palette.selection,
4636            );
4637            ctx.fill_rect(
4638                Rect::new(
4639                    selected_rect.x(),
4640                    selected_rect.y() + theme.spacing,
4641                    theme.interaction.active_indicator_thickness,
4642                    (selected_rect.height() - theme.spacing * 2.0).max(0.0),
4643                ),
4644                theme.palette.selection_border,
4645            );
4646        }
4647        let label = editing_space_label(space);
4648        let style = text_token_style(theme, text, theme.palette.text);
4649        let text_slot = Rect::new(
4650            row.x() + metrics.menu_item_padding.left + theme.spacing * 1.5,
4651            row.y(),
4652            row.width()
4653                - metrics.menu_item_padding.left
4654                - metrics.menu_item_padding.right
4655                - theme.spacing * 2.0,
4656            row.height(),
4657        );
4658        ctx.push_clip_rect(text_slot);
4659        paint_text_line(ctx, text_slot, label, &style, TextAlign::Start);
4660        ctx.pop_clip();
4661    }
4662}
4663
4664fn dropdown_chevron_path(rect: Rect) -> Path {
4665    let center = Point::new(rect.max_x() - 14.0, rect.y() + rect.height() * 0.5);
4666    let half_width = 4.0;
4667    let half_height = 2.5;
4668    let mut path = PathBuilder::new();
4669    path.move_to(Point::new(center.x - half_width, center.y - half_height));
4670    path.line_to(Point::new(center.x, center.y + half_height));
4671    path.line_to(Point::new(center.x + half_width, center.y - half_height));
4672    path.build()
4673}
4674
4675fn paint_hex_field(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, value: &str) {
4676    let metrics = theme.metrics;
4677    let text = theme.text.xs;
4678    let padding = metrics.text_input_padding;
4679    let style = text_token_style(theme, text, theme.palette.text);
4680    let text_slot = Rect::new(
4681        rect.x() + padding.left.max(theme.spacing * 2.0),
4682        rect.y(),
4683        rect.width() - (padding.left + padding.right).max(theme.spacing * 4.0),
4684        rect.height(),
4685    );
4686    draw_control_shape(
4687        ctx,
4688        rect,
4689        metrics.corner_radius,
4690        physical_pixels(ctx, metrics.border_width.max(1.0)),
4691        theme.palette.control,
4692        theme.palette.border,
4693    );
4694    ctx.push_clip_rect(text_slot);
4695    paint_text_line(ctx, text_slot, value, &style, TextAlign::Start);
4696    ctx.pop_clip();
4697}
4698
4699fn paint_disabled_field(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, value: &str) {
4700    let metrics = theme.metrics;
4701    let text = theme.text.xs;
4702    let padding = metrics.text_input_padding;
4703    let style = text_token_style(theme, text, theme.palette.placeholder);
4704    let text_slot = Rect::new(
4705        rect.x() + padding.left.max(theme.spacing * 2.0),
4706        rect.y(),
4707        rect.width() - (padding.left + padding.right).max(theme.spacing * 4.0),
4708        rect.height(),
4709    );
4710    draw_control_shape(
4711        ctx,
4712        rect,
4713        metrics.corner_radius,
4714        physical_pixels(ctx, metrics.border_width.max(1.0)),
4715        mix_color(theme.palette.control, theme.palette.surface, 0.5)
4716            .with_alpha(theme.interaction.disabled_opacity),
4717        theme.palette.border,
4718    );
4719    ctx.push_clip_rect(text_slot);
4720    paint_text_line(ctx, text_slot, value, &style, TextAlign::Start);
4721    ctx.pop_clip();
4722}
4723
4724fn point_in_wheel_ring(rect: Rect, position: Point) -> bool {
4725    let center = Point::new(
4726        rect.x() + rect.width() * 0.5,
4727        rect.y() + rect.height() * 0.5,
4728    );
4729    let dx = position.x - center.x;
4730    let dy = position.y - center.y;
4731    let distance = (dx * dx + dy * dy).sqrt();
4732    let outer = rect.width().min(rect.height()) * 0.5;
4733    let inner = outer * 0.55;
4734    distance >= inner && distance <= outer
4735}
4736
4737fn editing_space_label(space: ColorSpace) -> &'static str {
4738    match space {
4739        ColorSpace::Srgb => "sRGB",
4740        ColorSpace::LinearSrgb => "BT709 Linear",
4741        ColorSpace::DisplayP3 => "Display P3",
4742        ColorSpace::LinearDisplayP3 => "Display P3 Linear",
4743    }
4744}
4745
4746fn hdr_value_to_slider(value: f32) -> f32 {
4747    let value = value.clamp(0.0, ColorPicker::MAX_HDR_VALUE);
4748    if value <= 1.0 {
4749        value * 0.5
4750    } else {
4751        0.5 + (value.ln() / ColorPicker::MAX_HDR_VALUE.ln()) * 0.5
4752    }
4753}
4754
4755fn hdr_slider_to_value(t: f32) -> f32 {
4756    let t = t.clamp(0.0, 1.0);
4757    if t <= 0.5 {
4758        t / 0.5
4759    } else {
4760        ColorPicker::MAX_HDR_VALUE.powf((t - 0.5) / 0.5)
4761    }
4762}
4763
4764fn is_hdr_color(color: Color) -> bool {
4765    color.red > 1.0 || color.green > 1.0 || color.blue > 1.0
4766}
4767
4768/// Widget state progress the runtime animates (see [`Progress`]).
4769type AnimatedScalar = Progress;
4770
4771fn set_animation_target(
4772    animation: &mut AnimatedScalar,
4773    target: f32,
4774    duration: f64,
4775    easing: crate::Easing,
4776    ctx: &mut EventCtx,
4777) -> bool {
4778    animation.animate(target, crate::AnimationSpec::tween(duration, easing), ctx)
4779}
4780
4781fn set_hover_animation_target(
4782    animation: &mut AnimatedScalar,
4783    target: f32,
4784    theme: &DefaultTheme,
4785    ctx: &mut EventCtx,
4786) -> bool {
4787    set_animation_target(
4788        animation,
4789        target,
4790        theme.motion.hover_duration(),
4791        theme.motion.hover_easing(),
4792        ctx,
4793    )
4794}
4795
4796fn set_press_animation_target(
4797    animation: &mut AnimatedScalar,
4798    target: f32,
4799    theme: &DefaultTheme,
4800    ctx: &mut EventCtx,
4801) -> bool {
4802    set_animation_target(
4803        animation,
4804        target,
4805        theme.motion.press_duration(),
4806        theme.motion.press_easing(),
4807        ctx,
4808    )
4809}
4810
4811fn set_focus_animation_target(
4812    animation: &mut AnimatedScalar,
4813    target: f32,
4814    theme: &DefaultTheme,
4815    ctx: &mut EventCtx,
4816) -> bool {
4817    set_animation_target(
4818        animation,
4819        target,
4820        theme.motion.focus_duration(),
4821        theme.motion.focus_easing(),
4822        ctx,
4823    )
4824}
4825
4826fn fit_rect(bounds: Rect, source: Size, fit: ImageFit) -> Rect {
4827    if bounds.is_empty() || source.is_empty() {
4828        return bounds;
4829    }
4830
4831    let scale_x = bounds.width() / source.width.max(1.0);
4832    let scale_y = bounds.height() / source.height.max(1.0);
4833    let scale = match fit {
4834        ImageFit::Fill => None,
4835        ImageFit::Contain => Some(scale_x.min(scale_y)),
4836        ImageFit::Cover => Some(scale_x.max(scale_y)),
4837        ImageFit::None => Some(1.0),
4838    };
4839
4840    let size = if let Some(scale) = scale {
4841        Size::new(source.width * scale, source.height * scale)
4842    } else {
4843        bounds.size
4844    };
4845    Rect::new(
4846        bounds.x() + ((bounds.width() - size.width) * 0.5),
4847        bounds.y() + ((bounds.height() - size.height) * 0.5),
4848        size.width,
4849        size.height,
4850    )
4851}
4852
4853fn paint_marker(ctx: &mut PaintCtx, center: Point, color: Color, theme: &DefaultTheme) {
4854    ctx.stroke(
4855        Path::circle(center, 6.5),
4856        theme.surfaces.color_picker_marker_outer,
4857        StrokeStyle::new(2.0),
4858    );
4859    ctx.stroke(Path::circle(center, 5.0), color, StrokeStyle::new(1.5));
4860}
4861
4862fn draw_surface(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, focus_progress: f32) {
4863    let focus_progress = focus_progress.clamp(0.0, 1.0);
4864    draw_control_shape(
4865        ctx,
4866        rect,
4867        theme.metrics.corner_radius,
4868        physical_pixels(ctx, theme.metrics.border_width.max(1.0)),
4869        theme.palette.surface,
4870        mix_color(
4871            theme.palette.border,
4872            theme.palette.border_focus,
4873            focus_progress,
4874        ),
4875    );
4876    if focus_progress > AnimatedScalar::EPSILON {
4877        draw_focus_ring(
4878            ctx,
4879            rect,
4880            theme.metrics.corner_radius,
4881            theme.metrics,
4882            theme
4883                .palette
4884                .focus_ring
4885                .with_alpha(theme.palette.focus_ring.alpha * focus_progress),
4886        );
4887    }
4888}
4889
4890fn draw_checkerboard(ctx: &mut PaintCtx, rect: Rect, cell_size: f32, theme: &DefaultTheme) {
4891    let light = theme.surfaces.checkerboard_light;
4892    let dark = theme.surfaces.checkerboard_dark;
4893    let cell_size = cell_size.max(2.0);
4894    let cols = (rect.width() / cell_size).ceil() as usize;
4895    let rows = (rect.height() / cell_size).ceil() as usize;
4896    ctx.push_clip_rect(rect);
4897    for row in 0..rows {
4898        for col in 0..cols {
4899            let cell = Rect::new(
4900                rect.x() + col as f32 * cell_size,
4901                rect.y() + row as f32 * cell_size,
4902                cell_size,
4903                cell_size,
4904            );
4905            ctx.fill_rect(cell, if (row + col) % 2 == 0 { light } else { dark });
4906        }
4907    }
4908    ctx.pop_clip();
4909}
4910
4911fn draw_rounded_checkerboard(
4912    ctx: &mut PaintCtx,
4913    rect: Rect,
4914    radius: f32,
4915    cell_size: f32,
4916    theme: &DefaultTheme,
4917) {
4918    ctx.push_clip(Path::rounded_rect(rect, radius));
4919    draw_checkerboard(ctx, rect, cell_size, theme);
4920    ctx.pop_clip();
4921}
4922
4923fn format_color(color: Color) -> String {
4924    format!(
4925        "#{:02X}{:02X}{:02X}{:02X}",
4926        (color.red.clamp(0.0, 1.0) * 255.0).round() as u8,
4927        (color.green.clamp(0.0, 1.0) * 255.0).round() as u8,
4928        (color.blue.clamp(0.0, 1.0) * 255.0).round() as u8,
4929        (color.alpha.clamp(0.0, 1.0) * 255.0).round() as u8,
4930    )
4931}
4932
4933fn color_space_hdr_capable(space: ColorSpace) -> bool {
4934    space.is_linear() || matches!(space, ColorSpace::DisplayP3)
4935}
4936
4937fn color_space_max_channel_value(space: ColorSpace) -> f32 {
4938    if color_space_hdr_capable(space) {
4939        ColorPicker::MAX_HDR_VALUE
4940    } else {
4941        1.0
4942    }
4943}
4944
4945fn colors_close(left: Color, right: Color) -> bool {
4946    left.space == right.space
4947        && (left.red - right.red).abs() < 0.0001
4948        && (left.green - right.green).abs() < 0.0001
4949        && (left.blue - right.blue).abs() < 0.0001
4950        && (left.alpha - right.alpha).abs() < 0.0001
4951}
4952
4953fn contrast_color(color: Color, theme: &DefaultTheme) -> Color {
4954    if perceived_luminance(color) > 0.55 {
4955        theme.surfaces.color_picker_marker_dark
4956    } else {
4957        theme.surfaces.color_picker_marker_light
4958    }
4959}
4960
4961fn perceived_luminance(color: Color) -> f32 {
4962    (0.299 * color.red) + (0.587 * color.green) + (0.114 * color.blue)
4963}
4964
4965fn hsv_to_color(space: ColorSpace, hue: f32, saturation: f32, value: f32, alpha: f32) -> Color {
4966    let hue = hue.rem_euclid(1.0) * 6.0;
4967    let sector = hue.floor();
4968    let fraction = hue - sector;
4969    let p = value * (1.0 - saturation);
4970    let q = value * (1.0 - fraction * saturation);
4971    let t = value * (1.0 - (1.0 - fraction) * saturation);
4972    let (red, green, blue) = match sector as i32 {
4973        0 => (value, t, p),
4974        1 => (q, value, p),
4975        2 => (p, value, t),
4976        3 => (p, q, value),
4977        4 => (t, p, value),
4978        _ => (value, p, q),
4979    };
4980    Color::new(space, red, green, blue, alpha)
4981}
4982
4983#[cfg(test)]
4984fn hsv_to_rgb(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color {
4985    hsv_to_color(ColorSpace::Srgb, hue, saturation, value, alpha)
4986}
4987
4988fn rgb_to_hsv(color: Color) -> (f32, f32, f32) {
4989    let max = color.red.max(color.green).max(color.blue);
4990    let min = color.red.min(color.green).min(color.blue);
4991    let delta = max - min;
4992    let hue = if delta <= f32::EPSILON {
4993        0.0
4994    } else if (max - color.red).abs() <= f32::EPSILON {
4995        (((color.green - color.blue) / delta).rem_euclid(6.0)) / 6.0
4996    } else if (max - color.green).abs() <= f32::EPSILON {
4997        (((color.blue - color.red) / delta) + 2.0) / 6.0
4998    } else {
4999        (((color.red - color.green) / delta) + 4.0) / 6.0
5000    };
5001    let saturation = if max <= f32::EPSILON {
5002        0.0
5003    } else {
5004        delta / max
5005    };
5006    (hue, saturation, max)
5007}
5008
5009fn hsl_to_color(
5010    space: ColorSpace,
5011    hue: f32,
5012    saturation: f32,
5013    lightness: f32,
5014    alpha: f32,
5015    max_value: f32,
5016) -> Color {
5017    let max_value = max_value.max(0.0001);
5018    let lightness = (lightness / max_value).clamp(0.0, 1.0);
5019    let saturation = saturation.clamp(0.0, 1.0);
5020    let q = if lightness < 0.5 {
5021        lightness * (1.0 + saturation)
5022    } else {
5023        lightness + saturation - lightness * saturation
5024    };
5025    let p = 2.0 * lightness - q;
5026    let red = hue_to_rgb(p, q, hue + (1.0 / 3.0)) * max_value;
5027    let green = hue_to_rgb(p, q, hue) * max_value;
5028    let blue = hue_to_rgb(p, q, hue - (1.0 / 3.0)) * max_value;
5029    Color::new(space, red, green, blue, alpha)
5030}
5031
5032fn hue_to_rgb(p: f32, q: f32, hue: f32) -> f32 {
5033    let hue = hue.rem_euclid(1.0);
5034    if hue < 1.0 / 6.0 {
5035        p + (q - p) * 6.0 * hue
5036    } else if hue < 1.0 / 2.0 {
5037        q
5038    } else if hue < 2.0 / 3.0 {
5039        p + (q - p) * ((2.0 / 3.0) - hue) * 6.0
5040    } else {
5041        p
5042    }
5043}
5044
5045fn rgb_to_hsl(color: Color, max_value: f32) -> (f32, f32, f32) {
5046    let max_value = max_value.max(0.0001);
5047    let red = (color.red / max_value).clamp(0.0, 1.0);
5048    let green = (color.green / max_value).clamp(0.0, 1.0);
5049    let blue = (color.blue / max_value).clamp(0.0, 1.0);
5050    let max = red.max(green).max(blue);
5051    let min = red.min(green).min(blue);
5052    let lightness = (max + min) * 0.5;
5053    let delta = max - min;
5054    if delta <= f32::EPSILON {
5055        return (0.0, 0.0, lightness * max_value);
5056    }
5057
5058    let hue = if (max - red).abs() <= f32::EPSILON {
5059        (((green - blue) / delta).rem_euclid(6.0)) / 6.0
5060    } else if (max - green).abs() <= f32::EPSILON {
5061        (((blue - red) / delta) + 2.0) / 6.0
5062    } else {
5063        (((red - green) / delta) + 4.0) / 6.0
5064    };
5065    let saturation =
5066        (delta / (1.0 - (2.0 * lightness - 1.0).abs()).max(f32::EPSILON)).clamp(0.0, 1.0);
5067    (hue, saturation, lightness * max_value)
5068}
5069
5070fn numeric_text_style(mut style: TextStyle) -> TextStyle {
5071    style.features.enable(FontFeature::TABULAR_FIGURES);
5072    style
5073}
5074
5075fn text_token_style(theme: &DefaultTheme, token: ThemeTextToken, color: Color) -> TextStyle {
5076    TextStyle {
5077        font_size: token.size.max(1.0),
5078        line_height: token.line_height.max(1.0),
5079        color,
5080        ..theme.body_text_style()
5081    }
5082}
5083
5084#[cfg(test)]
5085mod tests {
5086    use std::{cell::RefCell, collections::BTreeSet, rc::Rc};
5087
5088    use crate::draw::rect_center;
5089
5090    use super::{
5091        ActiveChannel, BrushPreview, BrushPreviewShape, BrushPreviewSpec, ColorPalette,
5092        ColorPaletteSwatch, ColorPicker, ColorPickerColors, ColorPickerSemanticPart, ColorSwatch,
5093        Image, OKLCH_MAX_CHROMA, SignalMeter, SimpleColorPicker, SimpleColorPickerMode,
5094        color_picker_child_semantics_id, format_color, hsl_to_color, hsv_to_rgb, rgb_to_hsl,
5095        rgb_to_hsv, signal_meter_bar_layout,
5096    };
5097    use crate::{DefaultTheme, SemanticTone, ThemeTextToken};
5098    use sui_core::{
5099        Color, ColorSpace, Event, ImageHandle, Oklch, Point, PointerButton, PointerButtons,
5100        PointerEvent, PointerEventKind, Rect, Result, SemanticsAction, SemanticsNode,
5101        SemanticsRole, SemanticsValue, Size, Vector, WidgetId, WindowId,
5102    };
5103    use sui_layout::Padding as Insets;
5104    use sui_runtime::{Application, Runtime, Widget, WindowBuilder};
5105    use sui_scene::{Brush, GradientStop, RegisteredImage, SceneCommand, WidgetShader};
5106    use sui_text::{FontFeature, FontRegistry, TextSystem};
5107
5108    fn build_runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
5109    where
5110        W: Widget + 'static,
5111    {
5112        let runtime = Application::new()
5113            .window(WindowBuilder::new().title("Media widgets").root(root))
5114            .build()
5115            .unwrap();
5116        let window_id = runtime.window_ids()[0];
5117        (runtime, window_id)
5118    }
5119
5120    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
5121        let mut buttons = PointerButtons::NONE;
5122        if pressed {
5123            buttons.insert(PointerButton::Primary);
5124        }
5125
5126        Event::Pointer(PointerEvent {
5127            pointer_id: 1,
5128            kind,
5129            position,
5130            delta: Vector::ZERO,
5131            scroll_delta: None,
5132            button: Some(PointerButton::Primary),
5133            buttons,
5134            modifiers: sui_core::Modifiers::NONE,
5135            pointer_kind: sui_core::PointerKind::Mouse,
5136            is_primary: true,
5137        })
5138    }
5139
5140    fn handle_ready_events(runtime: &mut Runtime) -> Result<usize> {
5141        let ready = runtime.drain_ready_events();
5142        let count = ready.len();
5143        for (window_id, event) in ready {
5144            runtime.handle_event(window_id, event)?;
5145        }
5146        Ok(count)
5147    }
5148
5149    fn solid_fill_colors(output: &sui_runtime::RenderOutput) -> Vec<Color> {
5150        let mut colors = Vec::new();
5151        output.frame.scene.visit_commands(&mut |command| {
5152            if let SceneCommand::FillRect {
5153                brush: Brush::Solid(color),
5154                ..
5155            }
5156            | SceneCommand::FillPath {
5157                brush: Brush::Solid(color),
5158                ..
5159            } = command
5160            {
5161                colors.push(*color);
5162            }
5163        });
5164        colors
5165    }
5166
5167    fn solid_stroke_colors(output: &sui_runtime::RenderOutput) -> Vec<Color> {
5168        let mut colors = Vec::new();
5169        output.frame.scene.visit_commands(&mut |command| {
5170            if let SceneCommand::StrokeRect {
5171                brush: Brush::Solid(color),
5172                ..
5173            }
5174            | SceneCommand::StrokePath {
5175                brush: Brush::Solid(color),
5176                ..
5177            } = command
5178            {
5179                colors.push(*color);
5180            }
5181        });
5182        colors
5183    }
5184
5185    fn path_clip_bounds(output: &sui_runtime::RenderOutput) -> Vec<Rect> {
5186        output
5187            .frame
5188            .scene
5189            .commands()
5190            .iter()
5191            .filter_map(|command| match command {
5192                SceneCommand::PushClipPath { path } => Some(path.bounds()),
5193                _ => None,
5194            })
5195            .collect()
5196    }
5197
5198    fn rects_close(left: Rect, right: Rect) -> bool {
5199        (left.x() - right.x()).abs() < 0.001
5200            && (left.y() - right.y()).abs() < 0.001
5201            && (left.width() - right.width()).abs() < 0.001
5202            && (left.height() - right.height()).abs() < 0.001
5203    }
5204
5205    fn stroke_path_bounds_with_color_and_width(
5206        output: &sui_runtime::RenderOutput,
5207        color: Color,
5208        width: f32,
5209    ) -> Vec<Rect> {
5210        let mut bounds = Vec::new();
5211        output.frame.scene.visit_commands(&mut |command| {
5212            if let SceneCommand::StrokePath {
5213                path,
5214                brush: Brush::Solid(stroke_color),
5215                stroke,
5216            } = command
5217                && *stroke_color == color
5218                && (stroke.width - width).abs() < 0.01
5219            {
5220                bounds.push(path.bounds());
5221            }
5222        });
5223        bounds
5224    }
5225
5226    fn text_run_for(output: &sui_runtime::RenderOutput, text: &str) -> sui_text::TextRun {
5227        output
5228            .frame
5229            .scene
5230            .commands()
5231            .iter()
5232            .find_map(|command| match command {
5233                SceneCommand::DrawText(run) if run.text == text => Some(run.clone()),
5234                SceneCommand::DrawShapedText(run) => run
5235                    .resolve(output.frame.text_layout_registry.as_ref())
5236                    .filter(|layout| layout.text() == text)
5237                    .map(|layout| {
5238                        let mut style = layout.style().clone();
5239                        if let Some(color) = run.color_override {
5240                            style.color = color;
5241                        }
5242                        sui_text::TextRun {
5243                            rect: shaped_text_run_rect(run.origin, layout),
5244                            text: layout.text().to_string(),
5245                            style,
5246                        }
5247                    }),
5248                _ => None,
5249            })
5250            .expect("text draw command present")
5251    }
5252
5253    fn shaped_text_run_rect(origin: Point, layout: &sui_text::TextLayout) -> Rect {
5254        let measurement = layout.measurement();
5255        let bounds = measurement.bounds;
5256        let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
5257            bounds.width()
5258        } else {
5259            measurement.width
5260        };
5261        Rect::new(
5262            origin.x + bounds.x(),
5263            origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
5264            width,
5265            layout.style().line_height.max(measurement.height),
5266        )
5267    }
5268
5269    fn drawn_layout_for(output: &sui_runtime::RenderOutput, text: &str) -> sui_text::TextLayout {
5270        output
5271            .frame
5272            .scene
5273            .commands()
5274            .iter()
5275            .find_map(|command| match command {
5276                SceneCommand::DrawShapedText(run) => run
5277                    .resolve(output.frame.text_layout_registry.as_ref())
5278                    .filter(|layout| layout.text() == text)
5279                    .cloned(),
5280                _ => None,
5281            })
5282            .expect("shaped text draw command present")
5283    }
5284
5285    fn text_visual_center_for(output: &sui_runtime::RenderOutput, text: &str) -> f32 {
5286        output
5287            .frame
5288            .scene
5289            .commands()
5290            .iter()
5291            .find_map(|command| match command {
5292                SceneCommand::DrawText(run) if run.text == text => {
5293                    let layout = TextSystem::new()
5294                        .shape_text_run(run, &FontRegistry::new())
5295                        .expect("text run should shape");
5296                    let line = layout
5297                        .lines()
5298                        .first()
5299                        .expect("text run should contain one line");
5300                    Some(run.rect.y() + line.baseline + optical_visual_center(layout.measurement()))
5301                }
5302                SceneCommand::DrawShapedText(run) => {
5303                    let layout = run.resolve(output.frame.text_layout_registry.as_ref())?;
5304                    if layout.text() != text {
5305                        return None;
5306                    }
5307                    let line = layout
5308                        .lines()
5309                        .first()
5310                        .expect("shaped text should contain one line");
5311                    Some(run.origin.y + line.baseline + optical_visual_center(layout.measurement()))
5312                }
5313                _ => None,
5314            })
5315            .expect("text draw command present")
5316    }
5317
5318    fn optical_visual_center(measurement: sui_text::TextMeasurement) -> f32 {
5319        let top = -measurement.cap_height.unwrap_or(measurement.ascent);
5320        let bottom = measurement.descent * 0.5;
5321        (top + bottom) * 0.5
5322    }
5323
5324    fn assert_text_run_uses_token(run: &sui_text::TextRun, token: ThemeTextToken) {
5325        assert_eq!(run.style.font_size, token.size);
5326        assert_eq!(run.style.line_height, token.line_height);
5327    }
5328
5329    #[test]
5330    fn hsv_round_trip_stays_close() {
5331        let color = Color::rgba(0.25, 0.65, 0.82, 0.75);
5332        let (hue, saturation, value) = rgb_to_hsv(color);
5333        let round_trip = hsv_to_rgb(hue, saturation, value, color.alpha);
5334
5335        assert!((round_trip.red - color.red).abs() < 0.02);
5336        assert!((round_trip.green - color.green).abs() < 0.02);
5337        assert!((round_trip.blue - color.blue).abs() < 0.02);
5338        assert!((round_trip.alpha - color.alpha).abs() < f32::EPSILON);
5339    }
5340
5341    #[test]
5342    fn hsl_round_trip_stays_close() {
5343        let color = Color::rgba(0.25, 0.65, 0.82, 0.75);
5344        let (hue, saturation, lightness) = rgb_to_hsl(color, 1.0);
5345        let round_trip = hsl_to_color(color.space, hue, saturation, lightness, color.alpha, 1.0);
5346
5347        assert!((round_trip.red - color.red).abs() < 0.02);
5348        assert!((round_trip.green - color.green).abs() < 0.02);
5349        assert!((round_trip.blue - color.blue).abs() < 0.02);
5350        assert!((round_trip.alpha - color.alpha).abs() < f32::EPSILON);
5351    }
5352
5353    #[test]
5354    fn image_uses_registered_image_size_and_semantics() -> Result<()> {
5355        let handle = ImageHandle::new(7);
5356        let mut application = Application::new();
5357        application.register_image(
5358            handle,
5359            RegisteredImage::from_rgba8(32, 16, vec![255; 32 * 16 * 4])?,
5360        )?;
5361        let mut runtime = application
5362            .window(
5363                WindowBuilder::new()
5364                    .title("Image")
5365                    .root(Image::new(handle).semantic_name("Preview")),
5366            )
5367            .build()?;
5368        let window_id = runtime.window_ids()[0];
5369
5370        let output = runtime.render(window_id)?;
5371        assert_eq!(output.frame.viewport, Size::new(32.0, 16.0));
5372        let image = output
5373            .semantics
5374            .iter()
5375            .find(|node| node.role == SemanticsRole::Image)
5376            .expect("image semantics present");
5377        assert_eq!(image.name.as_deref(), Some("Preview"));
5378        Ok(())
5379    }
5380
5381    #[test]
5382    fn signal_meter_paints_tone_bars_and_semantics() -> Result<()> {
5383        let theme = DefaultTheme::default();
5384        let tone = theme.semantic_tone_color(SemanticTone::Success);
5385        let (mut runtime, window_id) = build_runtime(
5386            SignalMeter::new("Audio input signal")
5387                .description("Microphone activity")
5388                .active(true)
5389                .tone(SemanticTone::Success)
5390                .bars(10)
5391                .size(Size::new(120.0, 18.0))
5392                .theme(theme),
5393        );
5394
5395        let output = runtime.render(window_id)?;
5396        let fills = solid_fill_colors(&output);
5397        assert!(
5398            fills.iter().filter(|color| **color == tone).count() >= 10,
5399            "active signal meter should paint tone-colored bars"
5400        );
5401        let meter = output
5402            .semantics
5403            .iter()
5404            .find(|node| {
5405                node.role == SemanticsRole::GenericContainer
5406                    && node.name.as_deref() == Some("Audio input signal")
5407            })
5408            .expect("signal meter semantics should be present");
5409        assert_eq!(meter.description.as_deref(), Some("Microphone activity"));
5410        assert_eq!(
5411            meter.value.as_ref(),
5412            Some(&SemanticsValue::Text("active".to_string()))
5413        );
5414        Ok(())
5415    }
5416
5417    #[test]
5418    fn signal_meter_level_lights_reached_bars_and_publishes_range() -> Result<()> {
5419        let theme = DefaultTheme::default();
5420        let tone = theme.semantic_tone_color(SemanticTone::Success);
5421        let (mut runtime, window_id) = build_runtime(
5422            SignalMeter::new("Microphone level")
5423                .description("Current microphone input level")
5424                .active(true)
5425                .level_when(|| 0.5)
5426                .tone(SemanticTone::Success)
5427                .bars(10)
5428                .size(Size::new(120.0, 18.0))
5429                .theme(theme),
5430        );
5431
5432        let output = runtime.render(window_id)?;
5433        let fills = solid_fill_colors(&output);
5434        assert_eq!(
5435            fills.iter().filter(|color| **color == tone).count(),
5436            5,
5437            "a half-level signal should light half of the meter bars"
5438        );
5439        let meter = output
5440            .semantics
5441            .iter()
5442            .find(|node| {
5443                node.role == SemanticsRole::ProgressBar
5444                    && node.name.as_deref() == Some("Microphone level")
5445            })
5446            .expect("signal meter semantics should be present");
5447        assert_eq!(
5448            meter.value.as_ref(),
5449            Some(&SemanticsValue::Range {
5450                value: 0.5,
5451                min: 0.0,
5452                max: 1.0,
5453            })
5454        );
5455        Ok(())
5456    }
5457
5458    #[test]
5459    fn signal_meter_level_sanitizes_to_the_normalized_range() {
5460        assert_eq!(
5461            SignalMeter::new("Low").level(-0.25).resolved_level(),
5462            Some(0.0)
5463        );
5464        assert_eq!(
5465            SignalMeter::new("High").level(1.25).resolved_level(),
5466            Some(1.0)
5467        );
5468        assert_eq!(
5469            SignalMeter::new("Invalid")
5470                .level(f32::INFINITY)
5471                .resolved_level(),
5472            Some(0.0)
5473        );
5474    }
5475
5476    #[test]
5477    fn signal_meter_bar_layout_stays_inside_narrow_bounds() {
5478        for width in [0.0_f32, 0.5, 5.0, 10.0, 27.0, 120.0] {
5479            let (bars, gap, bar_width) = signal_meter_bar_layout(width, 18, 3.0);
5480            let painted_width = bar_width * bars as f32 + gap * bars.saturating_sub(1) as f32;
5481            assert!(bars >= 1);
5482            assert!(bar_width >= 0.0);
5483            assert!(painted_width <= width.max(0.0) + f32::EPSILON * 8.0);
5484        }
5485        assert_eq!(signal_meter_bar_layout(10.0, 18, 3.0), (10, 0.0, 1.0));
5486    }
5487
5488    #[test]
5489    fn image_without_border_omits_frame_stroke() -> Result<()> {
5490        let handle = ImageHandle::new(8);
5491        let mut application = Application::new();
5492        application.register_image(
5493            handle,
5494            RegisteredImage::from_rgba8(32, 32, vec![255; 32 * 32 * 4])?,
5495        )?;
5496        let mut runtime = application
5497            .window(
5498                WindowBuilder::new()
5499                    .title("Image")
5500                    .root(Image::new(handle).show_border(false)),
5501            )
5502            .build()?;
5503        let window_id = runtime.window_ids()[0];
5504
5505        let output = runtime.render(window_id)?;
5506        let mut image_draws = 0;
5507        let mut frame_strokes = 0;
5508        output
5509            .frame
5510            .scene
5511            .visit_commands(&mut |command| match command {
5512                SceneCommand::DrawImage { source, .. } if source.image == handle => {
5513                    image_draws += 1;
5514                }
5515                SceneCommand::StrokeRect { .. } | SceneCommand::StrokePath { .. } => {
5516                    frame_strokes += 1;
5517                }
5518                _ => {}
5519            });
5520
5521        assert_eq!(image_draws, 1);
5522        assert_eq!(frame_strokes, 0);
5523        Ok(())
5524    }
5525
5526    #[test]
5527    fn image_corner_radius_clips_bitmap_with_rounded_path() -> Result<()> {
5528        let handle = ImageHandle::new(9);
5529        let mut application = Application::new();
5530        application.register_image(
5531            handle,
5532            RegisteredImage::from_rgba8(32, 16, vec![255; 32 * 16 * 4])?,
5533        )?;
5534        let mut runtime = application
5535            .window(
5536                WindowBuilder::new().title("Rounded image").root(
5537                    Image::new(handle)
5538                        .fit(super::ImageFit::Cover)
5539                        .corner_radius(12.0),
5540                ),
5541            )
5542            .build()?;
5543        let window_id = runtime.window_ids()[0];
5544
5545        let output = runtime.render(window_id)?;
5546        assert!(
5547            output
5548                .frame
5549                .scene
5550                .commands()
5551                .iter()
5552                .any(|command| matches!(command, SceneCommand::PushClipPath { .. })),
5553            "rounded images should clip bitmap pixels to the rounded frame"
5554        );
5555        Ok(())
5556    }
5557
5558    #[test]
5559    fn color_swatch_click_invokes_callback() -> Result<()> {
5560        let presses = Rc::new(RefCell::new(Vec::new()));
5561        let on_press = Rc::clone(&presses);
5562        let color = Color::rgba(0.2, 0.4, 0.8, 1.0);
5563        let (mut runtime, window_id) = build_runtime(
5564            ColorSwatch::new("Accent", color)
5565                .on_press(move |color| on_press.borrow_mut().push(color)),
5566        );
5567
5568        let _ = runtime.render(window_id)?;
5569        runtime.handle_event(
5570            window_id,
5571            primary_pointer(PointerEventKind::Down, Point::new(16.0, 16.0), true),
5572        )?;
5573        runtime.handle_event(
5574            window_id,
5575            primary_pointer(PointerEventKind::Up, Point::new(16.0, 16.0), false),
5576        )?;
5577
5578        assert_eq!(presses.borrow().as_slice(), &[color]);
5579
5580        let output = runtime.render(window_id)?;
5581        let swatch = output
5582            .semantics
5583            .iter()
5584            .find(|node| node.role == SemanticsRole::ColorSwatch)
5585            .expect("color swatch semantics present");
5586        assert_eq!(
5587            swatch.value,
5588            Some(SemanticsValue::Text("#3366CCFF".to_string()))
5589        );
5590        Ok(())
5591    }
5592
5593    #[test]
5594    fn color_swatch_checkerboards_follow_the_rounded_color_shape() -> Result<()> {
5595        let theme = DefaultTheme::dark();
5596        let translucent = Color::rgba(0.16, 0.52, 0.88, 0.55);
5597        let (mut runtime, window_id) =
5598            build_runtime(ColorSwatch::new("Translucent accent", translucent).theme(theme));
5599        let output = runtime.render(window_id)?;
5600        let swatch = output
5601            .semantics
5602            .iter()
5603            .find(|node| node.role == SemanticsRole::ColorSwatch)
5604            .expect("standalone color swatch semantics present");
5605        let expected_inner = super::inset_rect(
5606            swatch.bounds,
5607            Insets::all(theme.metrics.color_swatch_inner_inset),
5608        );
5609        let clips = path_clip_bounds(&output);
5610        assert!(
5611            clips.iter().any(|clip| rects_close(*clip, expected_inner)),
5612            "standalone swatch checkerboard should be clipped to its rounded inner color shape; expected {expected_inner:?}, clips={clips:?}"
5613        );
5614
5615        let (mut runtime, window_id) = build_runtime(
5616            ColorPalette::new("Dark palette")
5617                .theme(theme)
5618                .swatch(ColorPaletteSwatch::new("Selected accent", translucent))
5619                .selected(0),
5620        );
5621        let output = runtime.render(window_id)?;
5622        let selected = output
5623            .semantics
5624            .iter()
5625            .find(|node| {
5626                node.role == SemanticsRole::ColorSwatch
5627                    && node.name.as_deref() == Some("Selected accent")
5628            })
5629            .expect("selected palette swatch semantics present");
5630        let expected_inner = super::inset_rect(
5631            selected.bounds,
5632            Insets::all(theme.metrics.color_palette_selected_swatch_inset),
5633        );
5634        let clips = path_clip_bounds(&output);
5635        assert!(
5636            clips.iter().any(|clip| rects_close(*clip, expected_inner)),
5637            "selected palette checkerboard should be clipped to its rounded color shape; expected {expected_inner:?}, clips={clips:?}"
5638        );
5639        Ok(())
5640    }
5641
5642    #[test]
5643    fn color_swatch_hover_and_press_use_theme_motion() -> Result<()> {
5644        let theme = DefaultTheme::default();
5645        let hover_duration = theme.motion.hover_duration();
5646        let press_duration = theme.motion.press_duration();
5647        let expected_hover = theme.palette.control_hover;
5648        let expected_press = super::mix_color(
5649            expected_hover,
5650            theme.palette.control_active,
5651            theme.interaction.pressed_blend,
5652        );
5653        let (mut runtime, window_id) =
5654            build_runtime(ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0)).theme(theme));
5655
5656        let output = runtime.render(window_id)?;
5657        let swatch = output
5658            .semantics
5659            .iter()
5660            .find(|node| node.role == SemanticsRole::ColorSwatch)
5661            .expect("color swatch semantics present");
5662        let position = rect_center(swatch.bounds);
5663
5664        runtime.handle_event(
5665            window_id,
5666            primary_pointer(PointerEventKind::Move, position, false),
5667        )?;
5668        runtime.tick(hover_duration * 0.5);
5669        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5670        let mid_hover = runtime.render(window_id)?;
5671        assert!(
5672            !solid_fill_colors(&mid_hover).contains(&expected_hover),
5673            "swatch hover fill should not snap to the settled hover color"
5674        );
5675
5676        runtime.tick(hover_duration);
5677        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5678        let settled_hover = runtime.render(window_id)?;
5679        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
5680
5681        runtime.handle_event(
5682            window_id,
5683            primary_pointer(PointerEventKind::Down, position, true),
5684        )?;
5685        runtime.tick(hover_duration + press_duration * 0.5);
5686        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5687        let mid_press = runtime.render(window_id)?;
5688        assert!(
5689            !solid_fill_colors(&mid_press).contains(&expected_press),
5690            "swatch press fill should not snap to the settled pressed color"
5691        );
5692
5693        runtime.tick(hover_duration + press_duration);
5694        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5695        let settled_press = runtime.render(window_id)?;
5696        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
5697
5698        Ok(())
5699    }
5700
5701    #[test]
5702    fn color_swatch_read_only_color_when_syncs_external_value() -> Result<()> {
5703        let color = Rc::new(RefCell::new(Color::rgba(0.08, 0.22, 0.78, 1.0)));
5704        let color_reader = Rc::clone(&color);
5705        let (mut runtime, window_id) = build_runtime(
5706            ColorSwatch::new("Current brush color", *color.borrow())
5707                .color_when(move || *color_reader.borrow())
5708                .read_only(true),
5709        );
5710
5711        let output = runtime.render(window_id)?;
5712        let swatch = output
5713            .semantics
5714            .iter()
5715            .find(|node| {
5716                node.role == SemanticsRole::ColorSwatch
5717                    && node.name.as_deref() == Some("Current brush color")
5718            })
5719            .expect("current color swatch semantics present");
5720        assert_eq!(
5721            swatch.value,
5722            Some(SemanticsValue::Text("#1438C7FF".to_string()))
5723        );
5724        assert!(swatch.actions.is_empty());
5725
5726        *color.borrow_mut() = Color::rgba(0.90, 0.32, 0.18, 1.0);
5727        runtime.handle_event(
5728            window_id,
5729            primary_pointer(PointerEventKind::Move, Point::new(8.0, 8.0), false),
5730        )?;
5731        let output = runtime.render(window_id)?;
5732        let swatch = output
5733            .semantics
5734            .iter()
5735            .find(|node| {
5736                node.role == SemanticsRole::ColorSwatch
5737                    && node.name.as_deref() == Some("Current brush color")
5738            })
5739            .expect("current color swatch semantics still present");
5740        assert_eq!(
5741            swatch.value,
5742            Some(SemanticsValue::Text("#E6522EFF".to_string()))
5743        );
5744        Ok(())
5745    }
5746
5747    #[test]
5748    fn color_palette_exposes_selected_swatch_semantics() -> Result<()> {
5749        let (mut runtime, window_id) = build_runtime(
5750            ColorPalette::new("Brush palette")
5751                .swatches([
5752                    ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
5753                    ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
5754                    ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
5755                ])
5756                .selected(1),
5757        );
5758        let output = runtime.render(window_id)?;
5759
5760        let palette = output
5761            .semantics
5762            .iter()
5763            .find(|node| {
5764                node.role == SemanticsRole::GenericContainer
5765                    && node.name.as_deref() == Some("Brush palette")
5766            })
5767            .expect("palette semantics present");
5768        assert_eq!(
5769            palette.value,
5770            Some(SemanticsValue::Text("Ocean #1438C7FF".to_string()))
5771        );
5772
5773        let selected = output
5774            .semantics
5775            .iter()
5776            .find(|node| {
5777                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Ocean")
5778            })
5779            .expect("selected swatch semantics present");
5780        assert!(selected.state.selected);
5781        assert_eq!(
5782            selected.value,
5783            Some(SemanticsValue::Text("#1438C7FF".to_string()))
5784        );
5785        Ok(())
5786    }
5787
5788    #[test]
5789    fn media_widget_defaults_follow_theme_density() -> Result<()> {
5790        let (mut compact_runtime, compact_window) = build_runtime(
5791            ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0))
5792                .theme(DefaultTheme::compact()),
5793        );
5794        let compact = compact_runtime.render(compact_window)?.frame.viewport;
5795
5796        let (mut touch_runtime, touch_window) = build_runtime(
5797            ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0))
5798                .theme(DefaultTheme::touch()),
5799        );
5800        let touch = touch_runtime.render(touch_window)?.frame.viewport;
5801
5802        assert_eq!(
5803            compact,
5804            Size::new(
5805                DefaultTheme::compact().metrics.color_swatch_width,
5806                DefaultTheme::compact().metrics.color_swatch_height,
5807            )
5808        );
5809        assert_eq!(
5810            touch,
5811            Size::new(
5812                DefaultTheme::touch().metrics.color_swatch_width,
5813                DefaultTheme::touch().metrics.color_swatch_height,
5814            )
5815        );
5816        assert!(touch.width > compact.width);
5817        assert!(touch.height > compact.height);
5818        Ok(())
5819    }
5820
5821    #[test]
5822    fn color_palette_defaults_and_overrides_are_density_aware() -> Result<()> {
5823        let swatches = [
5824            ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
5825            ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
5826        ];
5827        let (mut compact_runtime, compact_window) = build_runtime(
5828            ColorPalette::new("Brush palette")
5829                .theme(DefaultTheme::compact())
5830                .swatches(swatches.clone()),
5831        );
5832        let compact = compact_runtime.render(compact_window)?.frame.viewport;
5833
5834        let (mut touch_runtime, touch_window) = build_runtime(
5835            ColorPalette::new("Brush palette")
5836                .theme(DefaultTheme::touch())
5837                .swatches(swatches.clone()),
5838        );
5839        let touch = touch_runtime.render(touch_window)?.frame.viewport;
5840
5841        assert!(touch.width > compact.width);
5842        assert_eq!(
5843            compact.height,
5844            DefaultTheme::compact().metrics.color_palette_swatch_size
5845        );
5846
5847        let (mut override_runtime, override_window) = build_runtime(
5848            ColorPalette::new("Brush palette")
5849                .theme(DefaultTheme::touch())
5850                .swatches(swatches)
5851                .swatch_size(18.0)
5852                .gap(2.0),
5853        );
5854        let overridden = override_runtime.render(override_window)?.frame.viewport;
5855        assert_eq!(overridden, Size::new(38.0, 18.0));
5856        Ok(())
5857    }
5858
5859    #[test]
5860    fn color_palette_click_invokes_callback_and_selects_swatch() -> Result<()> {
5861        let changes = Rc::new(RefCell::new(Vec::new()));
5862        let changes_writer = Rc::clone(&changes);
5863        let (mut runtime, window_id) = build_runtime(
5864            ColorPalette::new("Brush palette")
5865                .swatches([
5866                    ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
5867                    ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
5868                    ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
5869                ])
5870                .selected(0)
5871                .on_change(move |index, name, color| {
5872                    changes_writer.borrow_mut().push((index, name, color));
5873                }),
5874        );
5875        let output = runtime.render(window_id)?;
5876        let mint = output
5877            .semantics
5878            .iter()
5879            .find(|node| {
5880                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Mint")
5881            })
5882            .expect("target swatch semantics present");
5883        let position = Point::new(
5884            mint.bounds.x() + mint.bounds.width() * 0.5,
5885            mint.bounds.y() + mint.bounds.height() * 0.5,
5886        );
5887
5888        runtime.handle_event(
5889            window_id,
5890            primary_pointer(PointerEventKind::Down, position, true),
5891        )?;
5892        runtime.handle_event(
5893            window_id,
5894            primary_pointer(PointerEventKind::Up, position, false),
5895        )?;
5896
5897        assert_eq!(
5898            changes.borrow().as_slice(),
5899            &[(2, "Mint".to_string(), Color::rgba(0.28, 0.78, 0.58, 1.0))]
5900        );
5901        let output = runtime.render(window_id)?;
5902        assert!(output.semantics.iter().any(|node| {
5903            node.role == SemanticsRole::ColorSwatch
5904                && node.name.as_deref() == Some("Mint")
5905                && node.state.selected
5906        }));
5907        Ok(())
5908    }
5909
5910    #[test]
5911    fn color_palette_hover_and_press_use_theme_motion() -> Result<()> {
5912        let theme = DefaultTheme::default();
5913        let hover_duration = theme.motion.hover_duration();
5914        let press_duration = theme.motion.press_duration();
5915        let expected_hover = super::mix_color(
5916            theme.palette.control,
5917            theme.palette.control_hover,
5918            theme.interaction.hover_blend,
5919        );
5920        let expected_press = super::mix_color(
5921            expected_hover,
5922            theme.palette.control_active,
5923            theme.interaction.pressed_blend,
5924        );
5925        let (mut runtime, window_id) =
5926            build_runtime(ColorPalette::new("Brush palette").theme(theme).swatches([
5927                ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
5928                ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
5929                ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
5930            ]));
5931        let output = runtime.render(window_id)?;
5932        let mint = output
5933            .semantics
5934            .iter()
5935            .find(|node| {
5936                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Mint")
5937            })
5938            .expect("target swatch semantics present");
5939        let position = rect_center(mint.bounds);
5940
5941        runtime.handle_event(
5942            window_id,
5943            primary_pointer(PointerEventKind::Move, position, false),
5944        )?;
5945        runtime.tick(hover_duration * 0.5);
5946        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5947        let mid_hover = runtime.render(window_id)?;
5948        assert!(
5949            !solid_fill_colors(&mid_hover).contains(&expected_hover),
5950            "palette swatch hover fill should not snap to the settled hover color"
5951        );
5952
5953        runtime.tick(hover_duration);
5954        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5955        let settled_hover = runtime.render(window_id)?;
5956        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
5957
5958        runtime.handle_event(
5959            window_id,
5960            primary_pointer(PointerEventKind::Down, position, true),
5961        )?;
5962        runtime.tick(hover_duration + press_duration * 0.5);
5963        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5964        let mid_press = runtime.render(window_id)?;
5965        assert!(
5966            !solid_fill_colors(&mid_press).contains(&expected_press),
5967            "palette swatch press fill should not snap to the settled pressed color"
5968        );
5969
5970        runtime.tick(hover_duration + press_duration);
5971        assert_eq!(handle_ready_events(&mut runtime)?, 0);
5972        let settled_press = runtime.render(window_id)?;
5973        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
5974
5975        Ok(())
5976    }
5977
5978    #[test]
5979    fn brush_preview_exposes_current_brush_semantics_and_paints_sample() -> Result<()> {
5980        let (mut runtime, window_id) = build_runtime(
5981            BrushPreview::new("Brush preview")
5982                .spec(BrushPreviewSpec::new(
5983                    Color::rgba(0.10, 0.30, 0.90, 1.0),
5984                    22.0,
5985                    0.75,
5986                    BrushPreviewShape::Square,
5987                ))
5988                .size(Size::new(220.0, 64.0)),
5989        );
5990
5991        let output = runtime.render(window_id)?;
5992        let preview = output
5993            .semantics
5994            .iter()
5995            .find(|node| {
5996                node.role == SemanticsRole::Image && node.name.as_deref() == Some("Brush preview")
5997            })
5998            .expect("brush preview semantics present");
5999        assert_eq!(
6000            preview.value,
6001            Some(SemanticsValue::Text(
6002                "Square brush, 22 px, 75% opacity".to_string(),
6003            ))
6004        );
6005
6006        let mut fill_count = 0;
6007        output.frame.scene.visit_commands(&mut |command| {
6008            if matches!(
6009                command,
6010                SceneCommand::FillRect { .. } | SceneCommand::FillPath { .. }
6011            ) {
6012                fill_count += 1;
6013            }
6014        });
6015        assert!(fill_count > 3);
6016
6017        let value_text = "Square brush, 22 px, 75% opacity";
6018        let actual_visual_center = text_visual_center_for(&output, value_text);
6019        let theme = DefaultTheme::default();
6020        let metrics = theme.metrics;
6021        let bounds = Rect::new(0.0, 0.0, 220.0, 64.0);
6022        let content = super::inset_rect(bounds, metrics.brush_preview_padding);
6023        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
6024        let sample = Rect::new(
6025            content.x() + swatch_width + metrics.brush_preview_swatch_gap,
6026            content.y(),
6027            (content.width() - swatch_width - metrics.brush_preview_swatch_gap).max(0.0),
6028            content.height(),
6029        );
6030        let text_height = metrics
6031            .brush_preview_text_height
6032            .max(theme.text.xs.line_height);
6033        let text_slot = Rect::new(
6034            sample.x(),
6035            sample.max_y() - text_height,
6036            sample.width(),
6037            text_height,
6038        );
6039        let slot_center = text_slot.y() + (text_slot.height() * 0.5);
6040
6041        assert!((actual_visual_center - slot_center).abs() < 0.75);
6042        Ok(())
6043    }
6044
6045    #[test]
6046    fn brush_preview_value_uses_text_token_and_preserves_slot_centering() -> Result<()> {
6047        let mut theme = DefaultTheme::default();
6048        theme.text.xs = ThemeTextToken {
6049            size: 28.0,
6050            line_height: 10.0,
6051        };
6052        theme.metrics.brush_preview_text_height = 44.0;
6053        theme.metrics.brush_preview_min_width = 420.0;
6054        theme.metrics.brush_preview_min_height = 96.0;
6055        let metrics = theme.metrics;
6056        let value_text = "Round brush, 8 px, 100% opacity";
6057
6058        let (mut runtime, window_id) = build_runtime(
6059            BrushPreview::new("Brush preview")
6060                .theme(theme)
6061                .spec(BrushPreviewSpec::new(
6062                    Color::rgba(0.10, 0.30, 0.90, 1.0),
6063                    8.0,
6064                    1.0,
6065                    BrushPreviewShape::Round,
6066                ))
6067                .size(Size::new(420.0, 96.0)),
6068        );
6069        let output = runtime.render(window_id)?;
6070        let text = text_run_for(&output, value_text);
6071        let layout = drawn_layout_for(&output, value_text);
6072        let actual_visual_center = text_visual_center_for(&output, value_text);
6073        let bounds = Rect::new(0.0, 0.0, 420.0, 96.0);
6074        let content = super::inset_rect(bounds, metrics.brush_preview_padding);
6075        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
6076        let sample = Rect::new(
6077            content.x() + swatch_width + metrics.brush_preview_swatch_gap,
6078            content.y(),
6079            (content.width() - swatch_width - metrics.brush_preview_swatch_gap).max(0.0),
6080            content.height(),
6081        );
6082        let text_height = metrics
6083            .brush_preview_text_height
6084            .max(theme.text.xs.line_height);
6085        let text_slot = Rect::new(
6086            sample.x(),
6087            sample.max_y() - text_height,
6088            sample.width(),
6089            text_height,
6090        );
6091        let slot_center = text_slot.y() + (text_slot.height() * 0.5);
6092
6093        assert_eq!(text.style.font_size, 28.0);
6094        assert_eq!(text.style.line_height, 10.0);
6095        assert!(text.rect.height() >= layout.measurement().height - 0.01);
6096        assert!(text.rect.height() > text.style.line_height);
6097        assert!((text.rect.x() - text_slot.x()).abs() < 0.75);
6098        assert!((actual_visual_center - slot_center).abs() < 0.75);
6099        Ok(())
6100    }
6101
6102    #[test]
6103    fn color_picker_pointer_drag_updates_semantics() -> Result<()> {
6104        let changes = Rc::new(RefCell::new(Vec::new()));
6105        let on_change = Rc::clone(&changes);
6106        let (mut runtime, window_id) = build_runtime(
6107            ColorPicker::new("Accent picker")
6108                .on_change(move |color| on_change.borrow_mut().push(color)),
6109        );
6110
6111        let initial = runtime.render(window_id)?;
6112        let map = initial
6113            .semantics
6114            .iter()
6115            .find(|node| node.name.as_deref() == Some("Saturation and value"))
6116            .expect("saturation/value semantics present")
6117            .bounds;
6118        let start = rect_center(map);
6119        let end = Point::new(map.x() + map.width() * 0.80, map.y() + map.height() * 0.35);
6120        runtime.handle_event(
6121            window_id,
6122            primary_pointer(PointerEventKind::Down, start, true),
6123        )?;
6124        runtime.handle_event(
6125            window_id,
6126            primary_pointer(PointerEventKind::Move, end, true),
6127        )?;
6128        runtime.handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))?;
6129
6130        let changed_color = *changes
6131            .borrow()
6132            .last()
6133            .expect("color picker emitted change");
6134        let output = runtime.render(window_id)?;
6135        let picker = output
6136            .semantics
6137            .iter()
6138            .find(|node| node.role == SemanticsRole::ColorPicker)
6139            .expect("color picker semantics present");
6140        assert_eq!(
6141            picker.value,
6142            Some(SemanticsValue::Text(format_color(changed_color)))
6143        );
6144        Ok(())
6145    }
6146
6147    #[test]
6148    fn simple_color_picker_hsl_mode_can_hide_alpha_slider() -> Result<()> {
6149        let (mut runtime, window_id) = build_runtime(
6150            SimpleColorPicker::from_color("Simple picker", Color::rgba(0.25, 0.65, 0.82, 0.75))
6151                .mode(SimpleColorPickerMode::Hsl)
6152                .show_alpha(false),
6153        );
6154
6155        let output = runtime.render(window_id)?;
6156        let picker = output
6157            .semantics
6158            .iter()
6159            .find(|node| {
6160                node.role == SemanticsRole::ColorPicker
6161                    && node.name.as_deref() == Some("Simple picker")
6162            })
6163            .expect("simple color picker semantics present");
6164        assert_eq!(
6165            picker.description.as_deref(),
6166            Some("HSL sliders; sRGB editing space; SDR range available")
6167        );
6168
6169        let child = |name: &str| {
6170            output.semantics.iter().find(|node| {
6171                node.parent == Some(picker.id)
6172                    && node.role == SemanticsRole::Slider
6173                    && node.name.as_deref() == Some(name)
6174            })
6175        };
6176        assert!(child("Hue").is_some());
6177        assert!(child("Saturation").is_some());
6178        assert!(child("Lightness").is_some());
6179        assert!(
6180            child("Alpha").is_none(),
6181            "hidden alpha should not expose an alpha slider"
6182        );
6183        Ok(())
6184    }
6185
6186    #[test]
6187    fn simple_color_picker_rgb_drag_updates_color_channels() -> Result<()> {
6188        let changes = Rc::new(RefCell::new(Vec::new()));
6189        let on_change = Rc::clone(&changes);
6190        let (mut runtime, window_id) = build_runtime(
6191            SimpleColorPicker::from_color(
6192                "Simple RGB picker",
6193                Color::new(ColorSpace::LinearSrgb, 0.2, 0.3, 0.4, 1.0),
6194            )
6195            .mode(SimpleColorPickerMode::Rgb)
6196            .on_change(move |color| on_change.borrow_mut().push(color)),
6197        );
6198
6199        let initial = runtime.render(window_id)?;
6200        let red = initial
6201            .semantics
6202            .iter()
6203            .find(|node| node.name.as_deref() == Some("Red"))
6204            .expect("red channel semantics present")
6205            .bounds;
6206        let start = Point::new(red.x() + red.width() * 0.20, red.y() + red.height() * 0.5);
6207        let end = Point::new(red.x() + red.width() * 0.80, red.y() + red.height() * 0.5);
6208        runtime.handle_event(
6209            window_id,
6210            primary_pointer(PointerEventKind::Down, start, true),
6211        )?;
6212        runtime.handle_event(
6213            window_id,
6214            primary_pointer(PointerEventKind::Move, end, true),
6215        )?;
6216        runtime.handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))?;
6217
6218        let changed_color = *changes
6219            .borrow()
6220            .last()
6221            .expect("simple RGB picker emitted change");
6222        assert!(
6223            changed_color.red > 9.0,
6224            "expected HDR red channel after RGB drag, got {}",
6225            changed_color.red
6226        );
6227        assert_eq!(changed_color.space, ColorSpace::LinearSrgb);
6228        Ok(())
6229    }
6230
6231    fn picker_slider(output: &sui_runtime::RenderOutput, name: &str) -> SemanticsNode {
6232        output
6233            .semantics
6234            .iter()
6235            .find(|node| node.role == SemanticsRole::Slider && node.name.as_deref() == Some(name))
6236            .unwrap_or_else(|| panic!("{name} slider semantics present"))
6237            .clone()
6238    }
6239
6240    fn drag_across(runtime: &mut Runtime, window_id: WindowId, from: Point, to: Point) {
6241        for (kind, position, pressed) in [
6242            (PointerEventKind::Down, from, true),
6243            (PointerEventKind::Move, to, true),
6244            (PointerEventKind::Up, to, false),
6245        ] {
6246            runtime
6247                .handle_event(window_id, primary_pointer(kind, position, pressed))
6248                .unwrap();
6249        }
6250    }
6251
6252    fn row_point(bounds: Rect, fraction: f32) -> Point {
6253        Point::new(
6254            bounds.x() + bounds.width() * fraction,
6255            bounds.y() + bounds.height() * 0.5,
6256        )
6257    }
6258
6259    /// The gradient track painted inside a slider row, and its stops.
6260    fn gradient_fill(output: &sui_runtime::RenderOutput, row: Rect) -> (Rect, Vec<GradientStop>) {
6261        output
6262            .frame
6263            .scene
6264            .commands()
6265            .iter()
6266            .find_map(|command| match command {
6267                SceneCommand::FillRect {
6268                    rect,
6269                    brush: Brush::LinearGradient { stops, .. },
6270                } if row.contains(Point::new(rect.x() + 0.5, rect.y() + 0.5)) => {
6271                    Some((*rect, stops.clone()))
6272                }
6273                _ => None,
6274            })
6275            .unwrap_or_else(|| panic!("a gradient track is painted in {row:?}"))
6276    }
6277
6278    /// The gradient track painted inside a slider row.
6279    fn gradient_track(output: &sui_runtime::RenderOutput, row: Rect) -> Rect {
6280        gradient_fill(output, row).0
6281    }
6282
6283    #[test]
6284    fn oklch_hue_track_sweeps_the_hue_wheel() -> Result<()> {
6285        let (mut runtime, window_id) = build_runtime(
6286            SimpleColorPicker::from_color(
6287                "Theme color",
6288                Oklch::new(0.7, 0.12, 40.0, 1.0).to_srgb(),
6289            )
6290            .mode(SimpleColorPickerMode::Oklch),
6291        );
6292        let output = runtime.render(window_id)?;
6293        let hue = picker_slider(&output, "Hue").bounds;
6294        let (_, stops) = gradient_fill(&output, hue);
6295        assert!(stops.len() >= 16, "{} stops", stops.len());
6296        assert_eq!(stops.first().map(|stop| stop.offset), Some(0.0));
6297        assert_eq!(stops.last().map(|stop| stop.offset), Some(1.0));
6298        assert!(stops.windows(2).all(|pair| pair[0].offset < pair[1].offset));
6299        let hues = stops
6300            .iter()
6301            .map(|stop| stop.color.to_oklch().hue)
6302            .collect::<Vec<_>>();
6303        let span = hues.iter().copied().fold(f32::MIN, f32::max)
6304            - hues.iter().copied().fold(f32::MAX, f32::min);
6305        assert!(span > 300.0, "the hue track sweeps the wheel: {hues:?}");
6306        Ok(())
6307    }
6308
6309    #[test]
6310    fn simple_color_picker_oklch_mode_exposes_perceptual_channels() -> Result<()> {
6311        let color = Oklch::new(0.62, 0.14, 250.0, 1.0).to_srgb();
6312        let expected = color.to_oklch();
6313        let (mut runtime, window_id) = build_runtime(
6314            SimpleColorPicker::from_color("Theme color", color).mode(SimpleColorPickerMode::Oklch),
6315        );
6316        let output = runtime.render(window_id)?;
6317        let picker = output
6318            .semantics
6319            .iter()
6320            .find(|node| node.role == SemanticsRole::ColorPicker)
6321            .expect("color picker semantics present");
6322        assert_eq!(
6323            picker.description.as_deref(),
6324            Some("OKLCH sliders; sRGB editing space; SDR range available")
6325        );
6326        let range = |name: &str| match picker_slider(&output, name).value {
6327            Some(SemanticsValue::Range { value, min, max }) => (value as f32, min, max),
6328            other => panic!("{name} has a range value, got {other:?}"),
6329        };
6330        let (lightness, _, lightness_max) = range("Lightness");
6331        let (chroma, _, chroma_max) = range("Chroma");
6332        let (hue, _, hue_max) = range("Hue");
6333        assert!((lightness - expected.lightness * 100.0).abs() < 0.01);
6334        assert_eq!(lightness_max, 100.0);
6335        assert!((chroma - expected.chroma).abs() < 1.0e-4);
6336        assert!((chroma_max - f64::from(OKLCH_MAX_CHROMA)).abs() < 1.0e-6);
6337        assert!((hue - expected.hue).abs() < 0.01);
6338        assert_eq!(hue_max, 360.0);
6339        picker_slider(&output, "Alpha");
6340        Ok(())
6341    }
6342
6343    #[test]
6344    fn simple_color_picker_oklch_lightness_drag_keeps_hue_and_chroma() -> Result<()> {
6345        let start = Oklch::new(0.55, 0.10, 150.0, 1.0);
6346        let changes = Rc::new(RefCell::new(Vec::new()));
6347        let on_change = Rc::clone(&changes);
6348        let (mut runtime, window_id) = build_runtime(
6349            SimpleColorPicker::from_color("Theme color", start.to_srgb())
6350                .mode(SimpleColorPickerMode::Oklch)
6351                .on_change(move |color| on_change.borrow_mut().push(color)),
6352        );
6353        let output = runtime.render(window_id)?;
6354        let lightness = gradient_track(&output, picker_slider(&output, "Lightness").bounds);
6355        drag_across(
6356            &mut runtime,
6357            window_id,
6358            row_point(lightness, 0.55),
6359            row_point(lightness, 0.75),
6360        );
6361
6362        let changed = changes
6363            .borrow()
6364            .last()
6365            .expect("the drag emits a color")
6366            .to_oklch();
6367        assert!(
6368            (changed.lightness - 0.75).abs() < 0.01,
6369            "lightness follows the track: {changed:?}"
6370        );
6371        assert!((changed.hue - start.hue).abs() < 1.0, "{changed:?}");
6372        assert!((changed.chroma - start.chroma).abs() < 0.005, "{changed:?}");
6373        Ok(())
6374    }
6375
6376    #[test]
6377    fn simple_color_picker_oklch_hue_survives_zero_chroma() -> Result<()> {
6378        let start = Oklch::new(0.6, 0.12, 30.0, 1.0);
6379        let changes = Rc::new(RefCell::new(Vec::new()));
6380        let on_change = Rc::clone(&changes);
6381        let (mut runtime, window_id) = build_runtime(
6382            SimpleColorPicker::from_color("Theme color", start.to_srgb())
6383                .mode(SimpleColorPickerMode::Oklch)
6384                .on_change(move |color| on_change.borrow_mut().push(color)),
6385        );
6386        let output = runtime.render(window_id)?;
6387        let chroma = gradient_track(&output, picker_slider(&output, "Chroma").bounds);
6388        drag_across(
6389            &mut runtime,
6390            window_id,
6391            row_point(chroma, 0.5),
6392            row_point(chroma, 0.0),
6393        );
6394        let gray = changes.borrow().last().copied().expect("a gray is emitted");
6395        assert!(gray.to_oklch().chroma < 0.001, "{:?}", gray.to_oklch());
6396        let _ = runtime.render(window_id)?;
6397
6398        drag_across(
6399            &mut runtime,
6400            window_id,
6401            row_point(chroma, 0.0),
6402            row_point(chroma, 0.4),
6403        );
6404        let restored = changes.borrow().last().expect("chroma returns").to_oklch();
6405        assert!(restored.chroma > 0.05, "{restored:?}");
6406        assert!(
6407            (restored.hue - start.hue).abs() < 1.0,
6408            "the hue is kept through gray: {restored:?}"
6409        );
6410        Ok(())
6411    }
6412
6413    #[test]
6414    fn simple_color_picker_oklch_fits_chroma_into_the_editing_gamut() -> Result<()> {
6415        let start = Oklch::new(0.7, 0.05, 145.0, 1.0);
6416        let changes = Rc::new(RefCell::new(Vec::new()));
6417        let on_change = Rc::clone(&changes);
6418        let (mut runtime, window_id) = build_runtime(
6419            SimpleColorPicker::from_color("Theme color", start.to_srgb())
6420                .mode(SimpleColorPickerMode::Oklch)
6421                .on_change(move |color| on_change.borrow_mut().push(color)),
6422        );
6423        let output = runtime.render(window_id)?;
6424        let chroma = gradient_track(&output, picker_slider(&output, "Chroma").bounds);
6425        drag_across(
6426            &mut runtime,
6427            window_id,
6428            row_point(chroma, 0.5),
6429            row_point(chroma, 1.0),
6430        );
6431
6432        let color = *changes.borrow().last().expect("the drag emits a color");
6433        assert_eq!(color.space, ColorSpace::Srgb);
6434        for channel in [color.red, color.green, color.blue] {
6435            assert!((0.0..=1.0).contains(&channel), "{color:?}");
6436        }
6437        let fitted = color.to_oklch();
6438        assert!(
6439            (fitted.chroma - start.max_srgb_chroma()).abs() < 0.01,
6440            "chroma stops at the sRGB edge: {fitted:?}"
6441        );
6442        assert!((fitted.lightness - start.lightness).abs() < 0.01);
6443
6444        let output = runtime.render(window_id)?;
6445        match picker_slider(&output, "Chroma").value {
6446            Some(SemanticsValue::Range { value, .. }) => assert!(
6447                (value - f64::from(OKLCH_MAX_CHROMA)).abs() < 1.0e-4,
6448                "the slider keeps the requested chroma: {value}"
6449            ),
6450            other => panic!("chroma has a range value, got {other:?}"),
6451        }
6452        Ok(())
6453    }
6454
6455    #[test]
6456    fn color_slider_label_and_value_sit_beside_the_track() -> Result<()> {
6457        let (mut runtime, window_id) = build_runtime(
6458            SimpleColorPicker::from_color("Theme color", Color::rgba(1.0, 0.25, 0.5, 1.0))
6459                .mode(SimpleColorPickerMode::Rgb),
6460        );
6461        let output = runtime.render(window_id)?;
6462        let track = output
6463            .frame
6464            .scene
6465            .commands()
6466            .iter()
6467            .find_map(|command| match command {
6468                SceneCommand::DrawShaderRect {
6469                    rect,
6470                    shader: WidgetShader::ColorPickerRgbChannelBar { channel: 0, .. },
6471                } => Some(*rect),
6472                _ => None,
6473            })
6474            .expect("the red track is painted");
6475        let marker_reach = 7.5;
6476        let label = text_run_for(&output, "R");
6477        let value = text_run_for(&output, "1.000");
6478        assert!(
6479            label.rect.max_x() <= track.x() - marker_reach,
6480            "label {:?} clears the track {track:?}",
6481            label.rect
6482        );
6483        assert!(
6484            value.rect.x() >= track.max_x() + marker_reach,
6485            "value {:?} clears the marker at the track end {track:?}",
6486            value.rect
6487        );
6488        Ok(())
6489    }
6490
6491    #[test]
6492    fn color_slider_drag_maps_across_the_track_not_the_row() -> Result<()> {
6493        let changes = Rc::new(RefCell::new(Vec::new()));
6494        let on_change = Rc::clone(&changes);
6495        let (mut runtime, window_id) = build_runtime(
6496            SimpleColorPicker::from_color("Theme color", Color::rgba(0.5, 0.5, 0.5, 1.0))
6497                .mode(SimpleColorPickerMode::Rgb)
6498                .on_change(move |color| on_change.borrow_mut().push(color)),
6499        );
6500        let output = runtime.render(window_id)?;
6501        let track = output
6502            .frame
6503            .scene
6504            .commands()
6505            .iter()
6506            .find_map(|command| match command {
6507                SceneCommand::DrawShaderRect {
6508                    rect,
6509                    shader: WidgetShader::ColorPickerRgbChannelBar { channel: 0, .. },
6510                } => Some(*rect),
6511                _ => None,
6512            })
6513            .expect("the red track is painted");
6514        drag_across(
6515            &mut runtime,
6516            window_id,
6517            row_point(track, 0.5),
6518            row_point(track, 0.25),
6519        );
6520        let red = changes.borrow().last().expect("the drag emits a color").red;
6521        assert!((red - 0.25).abs() < 0.01, "red {red}");
6522        Ok(())
6523    }
6524
6525    #[test]
6526    fn color_picker_focus_surface_uses_theme_motion() -> Result<()> {
6527        let theme = DefaultTheme::default();
6528        let focus_duration = theme.motion.focus_duration();
6529        let (mut runtime, window_id) = build_runtime(ColorPicker::new("Accent picker"));
6530        let output = runtime.render(window_id)?;
6531        let focus_target = output
6532            .semantics
6533            .iter()
6534            .find(|node| node.name.as_deref() == Some("Saturation and value"))
6535            .expect("color picker saturation/value semantics present")
6536            .bounds;
6537
6538        runtime.handle_event(
6539            window_id,
6540            primary_pointer(PointerEventKind::Down, rect_center(focus_target), true),
6541        )?;
6542        let _ = runtime.render(window_id)?;
6543
6544        runtime.tick(focus_duration * 0.5);
6545        assert_eq!(handle_ready_events(&mut runtime)?, 0);
6546        let mid = runtime.render(window_id)?;
6547        assert!(
6548            !solid_stroke_colors(&mid).contains(&theme.palette.focus_ring),
6549            "color picker focus ring should not snap to the settled focus color"
6550        );
6551
6552        runtime.tick(focus_duration);
6553        assert_eq!(handle_ready_events(&mut runtime)?, 0);
6554        let settled = runtime.render(window_id)?;
6555        assert!(
6556            solid_stroke_colors(&settled).contains(&theme.palette.focus_ring),
6557            "color picker focus ring should settle to the theme focus color"
6558        );
6559
6560        Ok(())
6561    }
6562
6563    #[test]
6564    fn color_picker_color_when_syncs_external_color() -> Result<()> {
6565        let color = Rc::new(RefCell::new(Color::rgba(0.08, 0.22, 0.78, 1.0)));
6566        let color_reader = Rc::clone(&color);
6567        let (mut runtime, window_id) = build_runtime(
6568            ColorPicker::from_color("Brush color", *color.borrow())
6569                .color_when(move || *color_reader.borrow()),
6570        );
6571
6572        let output = runtime.render(window_id)?;
6573        let picker = output
6574            .semantics
6575            .iter()
6576            .find(|node| node.role == SemanticsRole::ColorPicker)
6577            .expect("color picker semantics present");
6578        assert_eq!(
6579            picker.value,
6580            Some(SemanticsValue::Text("#1438C7FF".to_string()))
6581        );
6582
6583        *color.borrow_mut() = Color::rgba(0.90, 0.32, 0.18, 1.0);
6584        runtime.handle_event(
6585            window_id,
6586            primary_pointer(PointerEventKind::Move, Point::new(8.0, 8.0), false),
6587        )?;
6588        let output = runtime.render(window_id)?;
6589        let picker = output
6590            .semantics
6591            .iter()
6592            .find(|node| node.role == SemanticsRole::ColorPicker)
6593            .expect("color picker semantics still present");
6594        assert_eq!(
6595            picker.value,
6596            Some(SemanticsValue::Text("#E6522EFF".to_string()))
6597        );
6598        Ok(())
6599    }
6600
6601    #[test]
6602    fn color_picker_from_color_preserves_hdr_linear_color_space() {
6603        let picker = ColorPicker::from_color(
6604            "HDR accent",
6605            Color::new(ColorSpace::LinearSrgb, 2.0, 0.5, 0.25, 1.0),
6606        );
6607
6608        assert_eq!(picker.current_color().space, ColorSpace::LinearSrgb);
6609        assert!((picker.current_color().red - 2.0).abs() < f32::EPSILON);
6610        assert!((picker.current_color().green - 0.5).abs() < f32::EPSILON);
6611        assert!((picker.current_color().blue - 0.25).abs() < f32::EPSILON);
6612        assert!((picker.current_color().alpha - 1.0).abs() < f32::EPSILON);
6613    }
6614
6615    #[test]
6616    fn color_picker_semantics_describe_hdr_editing_mode() -> Result<()> {
6617        let (mut runtime, window_id) = build_runtime(ColorPicker::from_color(
6618            "HDR accent",
6619            Color::new(ColorSpace::LinearSrgb, 2.0, 0.5, 0.25, 1.0),
6620        ));
6621
6622        let output = runtime.render(window_id)?;
6623        let picker = output
6624            .semantics
6625            .iter()
6626            .find(|node| node.role == SemanticsRole::ColorPicker)
6627            .expect("color picker semantics present");
6628
6629        assert_eq!(
6630            picker.description.as_deref(),
6631            Some("BT709 Linear editing space; HDR range available")
6632        );
6633        Ok(())
6634    }
6635
6636    #[test]
6637    fn color_picker_semantics_expose_accessible_components() -> Result<()> {
6638        let (mut runtime, window_id) = build_runtime(ColorPicker::from_color(
6639            "Accent picker",
6640            Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
6641        ));
6642
6643        let output = runtime.render(window_id)?;
6644        let picker = output
6645            .semantics
6646            .iter()
6647            .find(|node| node.role == SemanticsRole::ColorPicker)
6648            .expect("color picker semantics present");
6649        let picker_id = picker.id;
6650
6651        let child = |role: SemanticsRole, name: &str| {
6652            output.semantics.iter().find(|node| {
6653                node.parent == Some(picker_id)
6654                    && node.role == role
6655                    && node.name.as_deref() == Some(name)
6656            })
6657        };
6658
6659        assert!(child(SemanticsRole::ColorSwatch, "Current color").is_some());
6660        assert!(child(SemanticsRole::ColorSwatch, "Previous color").is_some());
6661
6662        let range = child(SemanticsRole::ComboBox, "Color range")
6663            .expect("color range selector semantics present");
6664        assert_eq!(
6665            range.value,
6666            Some(SemanticsValue::Text("BT709 Linear".to_string()))
6667        );
6668        assert_eq!(range.state.expanded, Some(false));
6669
6670        for name in [
6671            "Saturation and value",
6672            "Hue",
6673            "Saturation",
6674            "Value",
6675            "Alpha",
6676            "Red",
6677            "Green",
6678            "Blue",
6679        ] {
6680            let slider = child(SemanticsRole::Slider, name)
6681                .unwrap_or_else(|| panic!("{name} slider semantics present"));
6682            assert!(
6683                matches!(slider.value, Some(SemanticsValue::Range { .. })),
6684                "{name} slider should expose a range value"
6685            );
6686        }
6687
6688        assert!(
6689            output.semantics.iter().any(|node| {
6690                node.parent == Some(picker_id)
6691                    && node.role == SemanticsRole::Text
6692                    && node
6693                        .name
6694                        .as_deref()
6695                        .is_some_and(|name| name.starts_with("HDR hex unavailable"))
6696            }),
6697            "HDR hex field semantics present"
6698        );
6699        Ok(())
6700    }
6701
6702    #[test]
6703    fn color_picker_synthetic_semantics_ids_are_javascript_safe_and_distinct() {
6704        let parent = WidgetId::new(402);
6705        let parts = [
6706            ColorPickerSemanticPart::CurrentColor,
6707            ColorPickerSemanticPart::PreviousColor,
6708            ColorPickerSemanticPart::ColorRange,
6709            ColorPickerSemanticPart::ColorRangeMenu,
6710            ColorPickerSemanticPart::ColorRangeOption(0),
6711            ColorPickerSemanticPart::ColorRangeOption(1),
6712            ColorPickerSemanticPart::ColorRangeOption(2),
6713            ColorPickerSemanticPart::ColorRangeOption(3),
6714            ColorPickerSemanticPart::SaturationValue,
6715            ColorPickerSemanticPart::Hue,
6716            ColorPickerSemanticPart::Saturation,
6717            ColorPickerSemanticPart::Value,
6718            ColorPickerSemanticPart::Alpha,
6719            ColorPickerSemanticPart::Red,
6720            ColorPickerSemanticPart::Green,
6721            ColorPickerSemanticPart::Blue,
6722            ColorPickerSemanticPart::Hex,
6723        ];
6724        let mut ids = BTreeSet::new();
6725        for part in parts {
6726            let id = color_picker_child_semantics_id(parent, part).get();
6727            assert!(id < (1_u64 << 53), "{id} should be JS-safe");
6728            assert!(ids.insert(id), "{id} should be unique");
6729        }
6730    }
6731
6732    #[test]
6733    fn color_picker_columns_are_compact() {
6734        let picker = ColorPicker::new("Accent picker");
6735        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
6736        let wheel = picker.color_wheel_rect(bounds);
6737        let map = picker.saturation_value_rect(bounds);
6738        let metrics = DefaultTheme::default().metrics;
6739
6740        assert_eq!(map.x() - wheel.max_x(), metrics.color_picker_panel_gap);
6741        assert_eq!(map.width(), metrics.color_picker_map_size);
6742        assert_eq!(map.y(), wheel.y());
6743    }
6744
6745    #[test]
6746    fn color_picker_compact_mode_uses_smaller_measurement() {
6747        let regular = ColorPicker::new("Accent picker")
6748            .theme(DefaultTheme::comfortable())
6749            .desired_size();
6750        let compact = ColorPicker::new("Accent picker")
6751            .compact(true)
6752            .show_alpha(false)
6753            .desired_size();
6754        let metrics = DefaultTheme::compact().metrics;
6755
6756        assert_eq!(
6757            compact.width,
6758            metrics.color_picker_wheel_size
6759                + metrics.color_picker_panel_gap
6760                + metrics.color_picker_right_panel_width
6761                + metrics.color_picker_content_inset * 2.0
6762        );
6763        assert!(compact.width < regular.width);
6764        assert!(compact.height < regular.height);
6765    }
6766
6767    #[test]
6768    fn color_picker_theme_density_changes_default_measurement() {
6769        let compact = ColorPicker::new("Accent picker")
6770            .theme(DefaultTheme::compact())
6771            .desired_size();
6772        let comfortable = ColorPicker::new("Accent picker")
6773            .theme(DefaultTheme::comfortable())
6774            .desired_size();
6775        let touch = ColorPicker::new("Accent picker")
6776            .theme(DefaultTheme::touch())
6777            .desired_size();
6778
6779        assert!(compact.width < comfortable.width);
6780        assert!(compact.height < comfortable.height);
6781        assert!(touch.width > comfortable.width);
6782        assert!(touch.height > comfortable.height);
6783    }
6784
6785    #[test]
6786    fn color_picker_appearance_overrides_semantic_theme_defaults() -> Result<()> {
6787        let appearance = ColorPickerColors {
6788            checkerboard_light: Some(Color::rgba(0.91, 0.86, 0.78, 1.0)),
6789            checkerboard_dark: Some(Color::rgba(0.66, 0.58, 0.48, 1.0)),
6790            chrome_border: Some(Color::rgba(0.20, 0.30, 0.42, 0.61)),
6791            plane_border: Some(Color::rgba(0.30, 0.20, 0.46, 0.62)),
6792            bar_border: Some(Color::rgba(0.42, 0.25, 0.18, 0.63)),
6793            marker_outer: Some(Color::rgba(0.98, 0.96, 0.90, 0.94)),
6794            marker_dark: Some(Color::rgba(0.05, 0.07, 0.10, 0.88)),
6795            marker_light: None,
6796            sdr_marker: Some(Color::rgba(0.95, 0.92, 0.84, 0.38)),
6797            hdr_divider: None,
6798        };
6799
6800        let (mut runtime, window_id) = build_runtime(
6801            ColorPicker::from_color("Accent picker", Color::rgba(0.84, 0.72, 0.18, 1.0))
6802                .colors(appearance),
6803        );
6804        let output = runtime.render(window_id)?;
6805        let fills = solid_fill_colors(&output);
6806        let strokes = solid_stroke_colors(&output);
6807
6808        assert!(fills.contains(&appearance.checkerboard_light.unwrap()));
6809        assert!(fills.contains(&appearance.checkerboard_dark.unwrap()));
6810        assert!(fills.contains(&appearance.sdr_marker.unwrap()));
6811        assert!(strokes.contains(&appearance.chrome_border.unwrap()));
6812        assert!(strokes.contains(&appearance.plane_border.unwrap()));
6813        assert!(strokes.contains(&appearance.bar_border.unwrap()));
6814        assert!(strokes.contains(&appearance.marker_outer.unwrap()));
6815        assert!(strokes.contains(&appearance.marker_dark.unwrap()));
6816        Ok(())
6817    }
6818
6819    #[test]
6820    fn color_picker_header_contains_encoding_selector() {
6821        let picker = ColorPicker::new("Accent picker");
6822        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
6823        let header = picker.header_rect(bounds);
6824        let encoding = picker.encoding_rect(bounds);
6825        let previous = picker.previous_swatch_rect(bounds);
6826        let map = picker.saturation_value_rect(bounds);
6827        let rgb = picker.rgb_row_rect(bounds, 0);
6828
6829        assert!(header.contains(encoding.origin));
6830        assert!(header.contains(Point::new(encoding.max_x(), encoding.max_y())));
6831        assert!(encoding.x() >= previous.max_x() + picker.panel_gap() - 0.01);
6832        assert!(encoding.max_x() <= header.max_x() + 0.01);
6833        assert!(rgb.y() > map.max_y());
6834    }
6835
6836    #[test]
6837    fn color_picker_encoding_chevron_is_centered_in_selector() -> Result<()> {
6838        let picker = ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80));
6839        let (mut runtime, window_id) = build_runtime(picker);
6840        let output = runtime.render(window_id)?;
6841        let bounds = Rect::new(
6842            0.0,
6843            0.0,
6844            output.frame.viewport.width,
6845            output.frame.viewport.height,
6846        );
6847        let layout_picker =
6848            ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80));
6849        let encoding = layout_picker.encoding_rect(bounds);
6850        let theme = DefaultTheme::default();
6851        let chevron =
6852            stroke_path_bounds_with_color_and_width(&output, theme.palette.placeholder, 1.4)
6853                .into_iter()
6854                .find(|rect| {
6855                    encoding.contains(Point::new(
6856                        rect.x() + rect.width() * 0.5,
6857                        rect.y() + rect.height() * 0.5,
6858                    )) && (rect.width() - 8.0).abs() < 0.75
6859                        && (rect.height() - 5.0).abs() < 0.75
6860                })
6861                .expect("encoding selector chevron stroke should render");
6862        let chevron_center_y = chevron.y() + chevron.height() * 0.5;
6863        let selector_center_y = encoding.y() + encoding.height() * 0.5;
6864
6865        assert!(
6866            (chevron_center_y - selector_center_y).abs() < 0.75,
6867            "encoding chevron center {chevron_center_y} did not match selector center {selector_center_y}; chevron={chevron:?}, selector={encoding:?}"
6868        );
6869        Ok(())
6870    }
6871
6872    #[test]
6873    fn color_picker_saturation_value_plane_uses_hdr_slider_curve() {
6874        let mut picker = ColorPicker::from_color(
6875            "Accent picker",
6876            Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
6877        );
6878        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
6879        let map = picker.saturation_value_rect(bounds);
6880
6881        picker.apply_position(
6882            bounds,
6883            ActiveChannel::SaturationValue,
6884            Point::new(map.x() + map.width() * 0.5, map.y() + map.height() * 0.25),
6885        );
6886
6887        assert!(
6888            picker.value > 3.0 && picker.value < 4.0,
6889            "75% HDR slider position should map logarithmically above 1.0, got {}",
6890            picker.value
6891        );
6892    }
6893
6894    #[test]
6895    fn color_picker_rgb_row_drag_updates_color_channels() -> Result<()> {
6896        let changes = Rc::new(RefCell::new(Vec::new()));
6897        let on_change = Rc::clone(&changes);
6898        let (mut runtime, window_id) = build_runtime(
6899            ColorPicker::from_color(
6900                "Accent picker",
6901                Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
6902            )
6903            .on_change(move |color| on_change.borrow_mut().push(color)),
6904        );
6905
6906        let initial = runtime.render(window_id)?;
6907        let red = initial
6908            .semantics
6909            .iter()
6910            .find(|node| node.name.as_deref() == Some("Red"))
6911            .expect("red channel semantics present")
6912            .bounds;
6913        let start = Point::new(red.x() + red.width() * 0.20, red.y() + red.height() * 0.5);
6914        let end = Point::new(red.x() + red.width() * 0.80, red.y() + red.height() * 0.5);
6915        runtime.handle_event(
6916            window_id,
6917            primary_pointer(PointerEventKind::Down, start, true),
6918        )?;
6919        runtime.handle_event(
6920            window_id,
6921            primary_pointer(PointerEventKind::Move, end, true),
6922        )?;
6923        runtime.handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))?;
6924
6925        let changed_color = *changes.borrow().last().expect("rgb row emitted change");
6926        assert!(
6927            changed_color.red > 8.0,
6928            "expected HDR red channel after RGB drag, got {}",
6929            changed_color.red
6930        );
6931        assert_eq!(changed_color.space, ColorSpace::LinearSrgb);
6932        Ok(())
6933    }
6934
6935    #[test]
6936    fn color_picker_numeric_rows_use_tabular_figures_and_end_alignment() -> Result<()> {
6937        let color = Color::rgba(0.25, 0.50, 0.75, 0.80);
6938        let (mut runtime, window_id) =
6939            build_runtime(ColorPicker::from_color("Accent picker", color));
6940        let output = runtime.render(window_id)?;
6941        let run = text_run_for(&output, "0.250");
6942        let bounds = Rect::new(
6943            0.0,
6944            0.0,
6945            output.frame.viewport.width,
6946            output.frame.viewport.height,
6947        );
6948        let picker = ColorPicker::from_color("Accent picker", color);
6949        let row = picker.rgb_row_rect(bounds, 0);
6950        let theme = DefaultTheme::default();
6951        let expected_right = row.max_x() - theme.spacing;
6952
6953        assert!(
6954            run.style
6955                .features
6956                .iter()
6957                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
6958        );
6959        assert!((run.rect.max_x() - expected_right).abs() < 1.0);
6960        assert!(run.rect.height() <= theme.text.xs.line_height + 0.01);
6961        Ok(())
6962    }
6963
6964    #[test]
6965    fn color_picker_numeric_rows_preserve_tall_measurements_and_row_center() -> Result<()> {
6966        let mut theme = DefaultTheme::default();
6967        theme.text.xs = ThemeTextToken {
6968            size: 28.0,
6969            line_height: 12.0,
6970        };
6971        theme.metrics.color_picker_row_height = 48.0;
6972        let color = Color::rgba(0.25, 0.50, 0.75, 0.80);
6973        let (mut runtime, window_id) =
6974            build_runtime(ColorPicker::from_color("Accent picker", color).theme(theme));
6975        let output = runtime.render(window_id)?;
6976        let label = text_run_for(&output, "R");
6977        let value = text_run_for(&output, "0.250");
6978        let layout = TextSystem::new()
6979            .shape_text_run(&value, &FontRegistry::new())
6980            .expect("color picker numeric value should shape");
6981        let bounds = Rect::new(
6982            0.0,
6983            0.0,
6984            output.frame.viewport.width,
6985            output.frame.viewport.height,
6986        );
6987        let picker = ColorPicker::from_color("Accent picker", color).theme(theme);
6988        let row = picker.rgb_row_rect(bounds, 0);
6989        let row_center = row.y() + row.height() * 0.5;
6990        let value_center = text_visual_center_for(&output, "0.250");
6991        // The value is wider than its slot, so it stays on one line and shows
6992        // its start, like any single line of text that overflows.
6993        let value_slot = super::ColorSliderRowSlots::new(row, &theme).value;
6994        assert_eq!(drawn_layout_for(&output, "0.250").lines().len(), 1);
6995        assert!(value.rect.width() > value_slot.width());
6996        assert!((value.rect.x() - value_slot.x()).abs() < 1.0);
6997        assert!(
6998            (value_center - row_center).abs() < 0.75,
6999            "color picker numeric value center {value_center} did not match row center {row_center}; value rect {:?}, row {:?}, measurement {:?}",
7000            value.rect,
7001            row,
7002            layout.measurement()
7003        );
7004        let label_center = text_visual_center_for(&output, "R");
7005        let label_layout = TextSystem::new()
7006            .shape_text_run(&label, &FontRegistry::new())
7007            .expect("color picker channel label should shape");
7008        assert!(
7009            (value_center - label_center).abs() < 0.75,
7010            "color picker numeric value center {value_center} and channel label center {label_center} should share a visual baseline; label rect {:?}, label measurement {:?}",
7011            label.rect,
7012            label_layout.measurement()
7013        );
7014        Ok(())
7015    }
7016
7017    #[test]
7018    fn color_picker_text_styles_follow_theme_xs_token() -> Result<()> {
7019        let mut theme = DefaultTheme::default();
7020        theme.text.xs = ThemeTextToken {
7021            size: 13.5,
7022            line_height: 31.0,
7023        };
7024        let (mut runtime, window_id) = build_runtime(
7025            ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80))
7026                .theme(theme),
7027        );
7028        let output = runtime.render(window_id)?;
7029        let label = text_run_for(&output, "R");
7030        let value = text_run_for(&output, "0.250");
7031
7032        assert_text_run_uses_token(&label, theme.text.xs);
7033        assert_text_run_uses_token(&value, theme.text.xs);
7034        assert!(
7035            value
7036                .style
7037                .features
7038                .iter()
7039                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
7040        );
7041        Ok(())
7042    }
7043
7044    #[test]
7045    fn color_picker_dropdown_and_fields_preserve_tall_text_measurements() -> Result<()> {
7046        let mut theme = DefaultTheme::default();
7047        theme.text.xs = ThemeTextToken {
7048            size: 28.0,
7049            line_height: 10.0,
7050        };
7051        theme.metrics.color_picker_top_bar_height = 56.0;
7052        theme.metrics.color_picker_field_height = 46.0;
7053        theme.metrics.color_picker_encoding_menu_row_height = 46.0;
7054        let color = Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0);
7055        let (mut runtime, window_id) =
7056            build_runtime(ColorPicker::from_color("Accent picker", color).theme(theme));
7057
7058        let initial = runtime.render(window_id)?;
7059        let color_range = initial
7060            .semantics
7061            .iter()
7062            .find(|node| node.name.as_deref() == Some("Color range"))
7063            .expect("color range semantics present")
7064            .bounds;
7065        let color_range_center = rect_center(color_range);
7066        runtime.handle_event(
7067            window_id,
7068            primary_pointer(PointerEventKind::Down, color_range_center, true),
7069        )?;
7070        runtime.handle_event(
7071            window_id,
7072            primary_pointer(PointerEventKind::Up, color_range_center, false),
7073        )?;
7074
7075        let output = runtime.render(window_id)?;
7076        let bounds = Rect::new(
7077            0.0,
7078            0.0,
7079            output.frame.viewport.width,
7080            output.frame.viewport.height,
7081        );
7082        let picker = ColorPicker::from_color("Accent picker", color).theme(theme);
7083        let selector = picker.encoding_rect(bounds);
7084        let menu_item = picker.encoding_option_rect(bounds, 0);
7085        let hex = picker.hex_rect(bounds);
7086        let selector_run = text_run_for(&output, "BT709 Linear");
7087        let menu_run = text_run_for(&output, "sRGB");
7088        let hex_run = text_run_for(&output, "HDR hex unavailable");
7089        assert_text_run_uses_token(&selector_run, theme.text.xs);
7090        assert_text_run_uses_token(&menu_run, theme.text.xs);
7091        assert_text_run_uses_token(&hex_run, theme.text.xs);
7092        assert_eq!(hex_run.style.color, theme.palette.placeholder);
7093        assert!(
7094            (text_visual_center_for(&output, "BT709 Linear") - rect_center(selector).y).abs()
7095                < 0.75
7096        );
7097        assert!((text_visual_center_for(&output, "sRGB") - rect_center(menu_item).y).abs() < 0.75);
7098        assert!(
7099            (text_visual_center_for(&output, "HDR hex unavailable") - rect_center(hex).y).abs()
7100                < 0.75
7101        );
7102        Ok(())
7103    }
7104
7105    #[test]
7106    fn color_picker_encoding_selector_uses_dropdown_options() -> Result<()> {
7107        let changes = Rc::new(RefCell::new(Vec::new()));
7108        let on_change = Rc::clone(&changes);
7109        let (mut runtime, window_id) = build_runtime(
7110            ColorPicker::from_color(
7111                "Accent picker",
7112                Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
7113            )
7114            .on_change(move |color| on_change.borrow_mut().push(color)),
7115        );
7116
7117        let _ = runtime.render(window_id)?;
7118        runtime.handle_event(
7119            window_id,
7120            primary_pointer(PointerEventKind::Down, Point::new(300.0, 40.0), true),
7121        )?;
7122        runtime.handle_event(
7123            window_id,
7124            primary_pointer(PointerEventKind::Up, Point::new(300.0, 40.0), false),
7125        )?;
7126        assert!(
7127            changes.borrow().is_empty(),
7128            "opening the encoding dropdown should not change color space"
7129        );
7130        let output = runtime.render(window_id)?;
7131        let picker = output
7132            .semantics
7133            .iter()
7134            .find(|node| node.role == SemanticsRole::ColorPicker)
7135            .expect("color picker semantics present after opening encoding dropdown");
7136        let range = output
7137            .semantics
7138            .iter()
7139            .find(|node| {
7140                node.parent == Some(picker.id)
7141                    && node.role == SemanticsRole::ComboBox
7142                    && node.name.as_deref() == Some("Color range")
7143            })
7144            .expect("color range selector semantics present after opening dropdown");
7145        assert_eq!(range.state.expanded, Some(true));
7146        assert!(
7147            output.semantics.iter().any(|node| {
7148                node.role == SemanticsRole::MenuItem
7149                    && node.name.as_deref() == Some("Display P3")
7150                    && node.actions.contains(&SemanticsAction::Activate)
7151            }),
7152            "open color range dropdown should expose Display P3 option"
7153        );
7154
7155        runtime.handle_event(
7156            window_id,
7157            primary_pointer(PointerEventKind::Down, Point::new(300.0, 129.0), true),
7158        )?;
7159        runtime.handle_event(
7160            window_id,
7161            primary_pointer(PointerEventKind::Up, Point::new(300.0, 129.0), false),
7162        )?;
7163
7164        let changed_color = *changes
7165            .borrow()
7166            .last()
7167            .expect("encoding selector emitted change");
7168        assert_eq!(changed_color.space, ColorSpace::DisplayP3);
7169
7170        let output = runtime.render(window_id)?;
7171        let picker = output
7172            .semantics
7173            .iter()
7174            .find(|node| node.role == SemanticsRole::ColorPicker)
7175            .expect("color picker semantics present after encoding change");
7176        assert_eq!(
7177            picker.description.as_deref(),
7178            Some("Display P3 editing space; HDR range available")
7179        );
7180        Ok(())
7181    }
7182}