Skip to main content

sui_widgets/
media.rs

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