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::{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}
499
500impl ColorSwatch {
501    pub fn new(name: impl Into<String>, color: Color) -> Self {
502        Self {
503            theme: Box::new(DefaultTheme::default()),
504            theme_reader: None,
505            name: name.into(),
506            color,
507            color_reader: None,
508            size: None,
509            hovered: false,
510            pressed: false,
511            hover_animation: AnimatedScalar::new(0.0),
512            press_animation: AnimatedScalar::new(0.0),
513            focus_animation: AnimatedScalar::new(0.0),
514            read_only: false,
515            on_press: None,
516        }
517    }
518
519    pub fn theme(mut self, theme: DefaultTheme) -> Self {
520        self.theme = Box::new(theme);
521        self.theme_reader = None;
522        self
523    }
524
525    pub fn theme_when<F>(mut self, theme: F) -> Self
526    where
527        F: Fn() -> DefaultTheme + 'static,
528    {
529        self.theme_reader = Some(Box::new(theme));
530        self
531    }
532
533    pub fn size(mut self, size: Size) -> Self {
534        self.size = Some(Size::new(size.width.max(24.0), size.height.max(24.0)));
535        self
536    }
537
538    pub fn color_when<F>(mut self, color: F) -> Self
539    where
540        F: Fn() -> Color + 'static,
541    {
542        self.color_reader = Some(Box::new(color));
543        self
544    }
545
546    pub fn read_only(mut self) -> Self {
547        self.read_only = true;
548        self
549    }
550
551    pub fn on_press<F>(mut self, on_press: F) -> Self
552    where
553        F: FnMut(Color) + 'static,
554    {
555        self.on_press = Some(Box::new(on_press));
556        self
557    }
558
559    fn current_color(&self) -> Color {
560        self.color_reader
561            .as_ref()
562            .map(|reader| reader())
563            .unwrap_or(self.color)
564    }
565
566    fn resolved_theme(&self) -> DefaultTheme {
567        self.theme_reader
568            .as_ref()
569            .map(|theme| theme())
570            .unwrap_or(*self.theme)
571    }
572
573    fn activate(&mut self) {
574        let color = self.current_color();
575        if let Some(on_press) = &mut self.on_press {
576            on_press(color);
577        }
578    }
579
580    fn resolved_size(&self, theme: &DefaultTheme) -> Size {
581        self.size.unwrap_or(Size::new(
582            theme.metrics.color_swatch_width,
583            theme.metrics.color_swatch_height,
584        ))
585    }
586
587    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
588        if self.hovered != hovered {
589            let theme = self.resolved_theme();
590            self.hovered = hovered;
591            set_hover_animation_target(
592                &mut self.hover_animation,
593                hovered as u8 as f32,
594                &theme,
595                ctx,
596            );
597            ctx.request_paint();
598            ctx.request_semantics();
599        }
600    }
601
602    fn set_pressed(&mut self, pressed: bool, ctx: &mut EventCtx) {
603        if self.pressed != pressed {
604            let theme = self.resolved_theme();
605            self.pressed = pressed;
606            set_press_animation_target(
607                &mut self.press_animation,
608                pressed as u8 as f32,
609                &theme,
610                ctx,
611            );
612            ctx.request_paint();
613            ctx.request_semantics();
614        }
615    }
616
617    fn advance_animations(&mut self, time: f64) -> bool {
618        self.hover_animation.advance(time)
619            | self.press_animation.advance(time)
620            | self.focus_animation.advance(time)
621    }
622}
623
624impl Widget for ColorSwatch {
625    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
626        if self.read_only {
627            if matches!(
628                event,
629                Event::Pointer(pointer)
630                    if matches!(
631                        pointer.kind,
632                        PointerEventKind::Move
633                            | PointerEventKind::Leave
634                            | PointerEventKind::Cancel
635                    )
636            ) {
637                ctx.request_paint();
638                ctx.request_semantics();
639            }
640            return;
641        }
642
643        match event {
644            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
645                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
646            }
647            Event::Pointer(pointer)
648                if pointer.kind == PointerEventKind::Down
649                    && pointer.button == Some(PointerButton::Primary)
650                    && ctx.bounds().contains(pointer.position) =>
651            {
652                self.set_pressed(true, ctx);
653                self.set_hovered(true, ctx);
654                ctx.request_focus();
655                ctx.request_pointer_capture(pointer.pointer_id);
656                ctx.set_handled();
657            }
658            Event::Pointer(pointer)
659                if pointer.kind == PointerEventKind::Up
660                    && pointer.button == Some(PointerButton::Primary) =>
661            {
662                let hovered = ctx.bounds().contains(pointer.position);
663                if self.pressed && hovered {
664                    self.activate();
665                }
666                self.set_pressed(false, ctx);
667                self.set_hovered(hovered, ctx);
668                ctx.release_pointer_capture(pointer.pointer_id);
669                ctx.set_handled();
670            }
671            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
672                self.set_hovered(false, ctx);
673            }
674            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
675                if self.pressed {
676                    self.set_pressed(false, ctx);
677                    self.set_hovered(false, ctx);
678                    ctx.release_pointer_capture(pointer.pointer_id);
679                }
680            }
681            Event::Keyboard(key)
682                if ctx.is_focused()
683                    && key.state == KeyState::Pressed
684                    && matches!(key.key.as_str(), "Enter" | " ") =>
685            {
686                self.activate();
687                ctx.request_paint();
688                ctx.request_semantics();
689                ctx.set_handled();
690            }
691            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
692                if self.advance_animations(*time) {
693                    ctx.request_animation_frame();
694                }
695                ctx.request_paint();
696            }
697            _ => {}
698        }
699    }
700
701    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
702        let theme = self.resolved_theme();
703        constraints.clamp(self.resolved_size(&theme))
704    }
705
706    fn paint(&self, ctx: &mut PaintCtx) {
707        let theme = self.resolved_theme();
708        let metrics = theme.metrics;
709        let palette = theme.palette;
710        let pressed_offset = self.press_animation.value * theme.interaction.pressed_offset;
711        let body = Rect::new(
712            ctx.bounds().x(),
713            ctx.bounds().y() + pressed_offset,
714            ctx.bounds().width(),
715            (ctx.bounds().height() - pressed_offset).max(0.0),
716        );
717        let outer_radius = metrics.corner_radius.min(body.height() * 0.5);
718        let inner_inset = metrics.color_swatch_inner_inset + pressed_offset * 0.5;
719        let inner_radius = (outer_radius - inner_inset).max(0.0);
720        let inner_body = inset_rect(body, Insets::all(inner_inset));
721        let color = self.current_color();
722
723        if self.focus_animation.value > 0.0 {
724            let focus_outset = metrics.focus_ring_outset;
725            ctx.stroke(
726                rounded_rect_path(
727                    ctx.bounds().inflate(focus_outset, focus_outset),
728                    outer_radius + focus_outset,
729                ),
730                palette.focus_ring.with_alpha(self.focus_animation.value),
731                StrokeStyle::new(metrics.focus_ring_width.max(1.0)),
732            );
733        }
734
735        if self.press_animation.value > 0.0 {
736            ctx.fill(
737                rounded_rect_path(ctx.bounds(), outer_radius),
738                mix_color(
739                    palette.control_hover,
740                    palette.control_active,
741                    theme.interaction.pressed_blend * self.press_animation.value,
742                ),
743            );
744        } else if self.hover_animation.value > 0.0 {
745            ctx.fill(
746                rounded_rect_path(ctx.bounds(), outer_radius),
747                palette
748                    .control_hover
749                    .with_alpha(self.hover_animation.value * palette.control_hover.alpha),
750            );
751        }
752
753        draw_rounded_checkerboard(
754            ctx,
755            inner_body,
756            inner_radius,
757            metrics.color_swatch_checker_size,
758            &theme,
759        );
760        ctx.fill(rounded_rect_path(inner_body, inner_radius), color);
761        ctx.stroke(
762            rounded_rect_path(body, outer_radius),
763            if ctx.is_focused() {
764                palette.border_focus
765            } else if self.hovered || self.hover_animation.value > 0.0 {
766                palette.border_hover
767            } else if self.read_only {
768                palette
769                    .border
770                    .with_alpha(theme.interaction.disabled_opacity)
771            } else {
772                palette.border
773            },
774            StrokeStyle::new(metrics.border_width.max(1.0)),
775        );
776    }
777
778    fn semantics(&self, ctx: &mut SemanticsCtx) {
779        let mut node =
780            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ColorSwatch, ctx.bounds());
781        node.name = Some(self.name.clone());
782        node.state.focused = ctx.is_focused();
783        node.value = Some(SemanticsValue::Text(format_color(self.current_color())));
784        if !self.read_only {
785            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
786        }
787        ctx.push(node);
788    }
789
790    fn accepts_focus(&self) -> bool {
791        !self.read_only
792    }
793
794    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
795        let theme = self.resolved_theme();
796        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
797        ctx.request_paint();
798        ctx.request_semantics();
799    }
800}
801
802#[derive(Debug, Clone, PartialEq)]
803pub struct ColorPaletteSwatch {
804    name: String,
805    color: Color,
806}
807
808impl ColorPaletteSwatch {
809    pub fn new(name: impl Into<String>, color: Color) -> Self {
810        Self {
811            name: name.into(),
812            color,
813        }
814    }
815
816    pub fn name(&self) -> &str {
817        &self.name
818    }
819
820    pub const fn color(&self) -> Color {
821        self.color
822    }
823}
824
825pub struct ColorPalette {
826    theme: Box<DefaultTheme>,
827    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
828    name: String,
829    swatches: Vec<ColorPaletteSwatch>,
830    selected: Option<usize>,
831    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
832    hovered: Option<usize>,
833    hover_visual: Option<usize>,
834    pressed: Option<usize>,
835    press_visual: Option<usize>,
836    hover_animation: AnimatedScalar,
837    press_animation: AnimatedScalar,
838    focus_animation: AnimatedScalar,
839    columns: usize,
840    swatch_size: Option<f32>,
841    gap: Option<f32>,
842    on_change: Option<Box<dyn FnMut(usize, String, Color)>>,
843    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String, Color)>>,
844}
845
846impl ColorPalette {
847    pub fn new(name: impl Into<String>) -> Self {
848        Self {
849            theme: Box::new(DefaultTheme::default()),
850            theme_reader: None,
851            name: name.into(),
852            swatches: Vec::new(),
853            selected: None,
854            selected_reader: None,
855            hovered: None,
856            hover_visual: None,
857            pressed: None,
858            press_visual: None,
859            hover_animation: AnimatedScalar::new(0.0),
860            press_animation: AnimatedScalar::new(0.0),
861            focus_animation: AnimatedScalar::new(0.0),
862            columns: 8,
863            swatch_size: None,
864            gap: None,
865            on_change: None,
866            on_change_with_ctx: None,
867        }
868    }
869
870    pub fn theme(mut self, theme: DefaultTheme) -> Self {
871        self.theme = Box::new(theme);
872        self.theme_reader = None;
873        self
874    }
875
876    pub fn theme_when<F>(mut self, theme: F) -> Self
877    where
878        F: Fn() -> DefaultTheme + 'static,
879    {
880        self.theme_reader = Some(Box::new(theme));
881        self
882    }
883
884    pub fn swatch(mut self, swatch: ColorPaletteSwatch) -> Self {
885        self.swatches.push(swatch);
886        self
887    }
888
889    pub fn swatches<I>(mut self, swatches: I) -> Self
890    where
891        I: IntoIterator<Item = ColorPaletteSwatch>,
892    {
893        self.swatches.extend(swatches);
894        self
895    }
896
897    pub fn selected(mut self, selected: usize) -> Self {
898        self.selected = Some(selected);
899        self.selected_reader = None;
900        self
901    }
902
903    pub fn selected_when<F>(mut self, selected: F) -> Self
904    where
905        F: Fn() -> Option<usize> + 'static,
906    {
907        self.selected_reader = Some(Box::new(selected));
908        self
909    }
910
911    pub fn columns(mut self, columns: usize) -> Self {
912        self.columns = columns.max(1);
913        self
914    }
915
916    pub fn swatch_size(mut self, size: f32) -> Self {
917        self.swatch_size = Some(size.max(18.0));
918        self
919    }
920
921    pub fn gap(mut self, gap: f32) -> Self {
922        self.gap = Some(gap.max(0.0));
923        self
924    }
925
926    pub fn on_change<F>(mut self, on_change: F) -> Self
927    where
928        F: FnMut(usize, String, Color) + 'static,
929    {
930        self.on_change = Some(Box::new(on_change));
931        self
932    }
933
934    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
935    where
936        F: FnMut(&mut EventCtx, usize, String, Color) + 'static,
937    {
938        self.on_change_with_ctx = Some(Box::new(on_change));
939        self
940    }
941
942    pub fn selected_index(&self) -> Option<usize> {
943        self.current_selected()
944    }
945
946    fn current_selected(&self) -> Option<usize> {
947        self.selected_reader
948            .as_ref()
949            .map(|selected| selected())
950            .unwrap_or(self.selected)
951            .filter(|index| *index < self.swatches.len())
952    }
953
954    fn resolved_theme(&self) -> DefaultTheme {
955        self.theme_reader
956            .as_ref()
957            .map(|theme| theme())
958            .unwrap_or(*self.theme)
959    }
960
961    fn grid_columns(&self) -> usize {
962        self.columns.max(1).min(self.swatches.len().max(1))
963    }
964
965    fn grid_rows(&self) -> usize {
966        if self.swatches.is_empty() {
967            1
968        } else {
969            self.swatches.len().div_ceil(self.grid_columns())
970        }
971    }
972
973    fn resolved_swatch_size(&self, theme: &DefaultTheme) -> f32 {
974        self.swatch_size
975            .unwrap_or(theme.metrics.color_palette_swatch_size)
976    }
977
978    fn resolved_gap(&self, theme: &DefaultTheme) -> f32 {
979        self.gap.unwrap_or(theme.metrics.color_palette_gap)
980    }
981
982    fn swatch_rect(&self, bounds: Rect, index: usize, theme: &DefaultTheme) -> Option<Rect> {
983        if index >= self.swatches.len() {
984            return None;
985        }
986
987        let swatch_size = self.resolved_swatch_size(theme);
988        let gap = self.resolved_gap(theme);
989        let columns = self.grid_columns();
990        let column = index % columns;
991        let row = index / columns;
992        let x = bounds.x() + column as f32 * (swatch_size + gap);
993        let y = bounds.y() + row as f32 * (swatch_size + gap);
994        let available_width = (bounds.max_x() - x).max(0.0);
995        let available_height = (bounds.max_y() - y).max(0.0);
996        let rect = Rect::new(
997            x,
998            y,
999            swatch_size.min(available_width),
1000            swatch_size.min(available_height),
1001        );
1002        (!rect.is_empty()).then_some(rect)
1003    }
1004
1005    fn swatch_at(&self, bounds: Rect, position: Point, theme: &DefaultTheme) -> Option<usize> {
1006        self.swatches.iter().enumerate().find_map(|(index, _)| {
1007            self.swatch_rect(bounds, index, theme)
1008                .filter(|rect| rect.contains(position))
1009                .map(|_| index)
1010        })
1011    }
1012
1013    fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
1014        if self.swatches.is_empty() {
1015            return;
1016        }
1017
1018        let index = index.min(self.swatches.len() - 1);
1019        self.selected = Some(index);
1020        let swatch = &self.swatches[index];
1021        let name = swatch.name.clone();
1022        let color = swatch.color;
1023        if let Some(on_change) = &mut self.on_change {
1024            on_change(index, name.clone(), color);
1025        }
1026        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
1027            on_change_with_ctx(ctx, index, name, color);
1028        }
1029    }
1030
1031    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
1032        if self.swatches.is_empty() {
1033            return;
1034        }
1035
1036        let current = self.current_selected().unwrap_or(0) as isize;
1037        let last = self.swatches.len() as isize - 1;
1038        let next = (current + delta).clamp(0, last) as usize;
1039        self.set_hovered(Some(next), ctx);
1040        self.activate(ctx, next);
1041    }
1042
1043    fn selected_value(&self) -> Option<String> {
1044        self.current_selected()
1045            .and_then(|index| self.swatches.get(index))
1046            .map(|swatch| format!("{} {}", swatch.name, format_color(swatch.color)))
1047    }
1048
1049    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
1050        if self.hovered == hovered {
1051            return;
1052        }
1053        let theme = self.resolved_theme();
1054        self.hovered = hovered;
1055        if let Some(index) = hovered {
1056            self.hover_visual = Some(index);
1057            self.hover_animation = AnimatedScalar::new(0.0);
1058            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
1059        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
1060            self.hover_visual = None;
1061        }
1062        ctx.request_paint();
1063        ctx.request_semantics();
1064    }
1065
1066    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
1067        if self.pressed == pressed {
1068            return;
1069        }
1070        let theme = self.resolved_theme();
1071        self.pressed = pressed;
1072        if let Some(index) = pressed {
1073            self.press_visual = Some(index);
1074            self.press_animation = AnimatedScalar::new(0.0);
1075            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
1076        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
1077            self.press_visual = None;
1078        }
1079        ctx.request_paint();
1080        ctx.request_semantics();
1081    }
1082
1083    fn hover_amount_for(&self, index: usize) -> f32 {
1084        if self.hover_visual == Some(index) {
1085            self.hover_animation.value
1086        } else {
1087            0.0
1088        }
1089    }
1090
1091    fn press_amount_for(&self, index: usize) -> f32 {
1092        if self.press_visual == Some(index) {
1093            self.press_animation.value
1094        } else {
1095            0.0
1096        }
1097    }
1098
1099    fn advance_animations(&mut self, time: f64) -> bool {
1100        let hover_animating = self.hover_animation.advance(time);
1101        if !hover_animating
1102            && self.hovered.is_none()
1103            && self.hover_animation.value <= AnimatedScalar::EPSILON
1104        {
1105            self.hover_visual = None;
1106        }
1107        let press_animating = self.press_animation.advance(time);
1108        if !press_animating
1109            && self.pressed.is_none()
1110            && self.press_animation.value <= AnimatedScalar::EPSILON
1111        {
1112            self.press_visual = None;
1113        }
1114        hover_animating | press_animating | self.focus_animation.advance(time)
1115    }
1116}
1117
1118impl Widget for ColorPalette {
1119    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1120        match event {
1121            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1122                let theme = self.resolved_theme();
1123                self.set_hovered(self.swatch_at(ctx.bounds(), pointer.position, &theme), ctx);
1124            }
1125            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
1126                self.set_hovered(None, ctx);
1127            }
1128            Event::Pointer(pointer)
1129                if pointer.kind == PointerEventKind::Down
1130                    && pointer.button == Some(PointerButton::Primary) =>
1131            {
1132                let theme = self.resolved_theme();
1133                let hovered = self.swatch_at(ctx.bounds(), pointer.position, &theme);
1134                self.set_hovered(hovered, ctx);
1135                self.set_pressed(hovered, ctx);
1136                if self.hovered.is_some() {
1137                    ctx.request_focus();
1138                    ctx.request_pointer_capture(pointer.pointer_id);
1139                    ctx.set_handled();
1140                }
1141            }
1142            Event::Pointer(pointer)
1143                if pointer.kind == PointerEventKind::Up
1144                    && pointer.button == Some(PointerButton::Primary) =>
1145            {
1146                let theme = self.resolved_theme();
1147                let hovered = self.swatch_at(ctx.bounds(), pointer.position, &theme);
1148                if let Some(index) = self
1149                    .pressed
1150                    .zip(hovered)
1151                    .filter(|(left, right)| left == right)
1152                    .map(|(index, _)| index)
1153                {
1154                    self.activate(ctx, index);
1155                }
1156                self.set_hovered(hovered, ctx);
1157                self.set_pressed(None, ctx);
1158                ctx.release_pointer_capture(pointer.pointer_id);
1159                ctx.set_handled();
1160            }
1161            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1162                if self.pressed.is_some() {
1163                    self.set_pressed(None, ctx);
1164                    self.set_hovered(None, ctx);
1165                    ctx.release_pointer_capture(pointer.pointer_id);
1166                    ctx.set_handled();
1167                }
1168            }
1169            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1170                let columns = self.grid_columns() as isize;
1171                match key.key.as_str() {
1172                    "ArrowLeft" => self.move_selection(-1, ctx),
1173                    "ArrowRight" => self.move_selection(1, ctx),
1174                    "ArrowUp" => self.move_selection(-columns, ctx),
1175                    "ArrowDown" => self.move_selection(columns, ctx),
1176                    "Home" => self.activate(ctx, 0),
1177                    "End" if !self.swatches.is_empty() => {
1178                        self.activate(ctx, self.swatches.len() - 1);
1179                    }
1180                    "Enter" | " " => {
1181                        if let Some(selected) = self.current_selected().or(Some(0)) {
1182                            self.activate(ctx, selected);
1183                        }
1184                    }
1185                    _ => return,
1186                }
1187                ctx.request_paint();
1188                ctx.request_semantics();
1189                ctx.set_handled();
1190            }
1191            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1192                if self.advance_animations(*time) {
1193                    ctx.request_animation_frame();
1194                }
1195                ctx.request_paint();
1196            }
1197            _ => {}
1198        }
1199    }
1200
1201    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1202        let theme = self.resolved_theme();
1203        let swatch_size = self.resolved_swatch_size(&theme);
1204        let gap = self.resolved_gap(&theme);
1205        let columns = self.grid_columns() as f32;
1206        let rows = self.grid_rows() as f32;
1207        constraints.clamp(Size::new(
1208            columns * swatch_size + (columns - 1.0).max(0.0) * gap,
1209            rows * swatch_size + (rows - 1.0).max(0.0) * gap,
1210        ))
1211    }
1212
1213    fn paint(&self, ctx: &mut PaintCtx) {
1214        let theme = self.resolved_theme();
1215        let palette = theme.palette;
1216        let metrics = theme.metrics;
1217        let interaction = theme.interaction;
1218        let swatch_size = self.resolved_swatch_size(&theme);
1219        let radius = metrics.corner_radius.min(swatch_size * 0.25);
1220        let selected = self.current_selected();
1221
1222        if self.focus_animation.value > 0.0 {
1223            let focus_outset = metrics.focus_ring_outset;
1224            ctx.stroke(
1225                rounded_rect_path(
1226                    ctx.bounds().inflate(focus_outset, focus_outset),
1227                    radius + focus_outset,
1228                ),
1229                palette.focus_ring.with_alpha(self.focus_animation.value),
1230                StrokeStyle::new(metrics.focus_ring_width.max(1.0)),
1231            );
1232        }
1233
1234        for (index, swatch) in self.swatches.iter().enumerate() {
1235            let Some(rect) = self.swatch_rect(ctx.bounds(), index, &theme) else {
1236                continue;
1237            };
1238            let selected = selected == Some(index);
1239            let hovered = self.hovered == Some(index);
1240            let hover_amount = self.hover_amount_for(index);
1241            let press_amount = self.press_amount_for(index);
1242            let pressed_offset = press_amount * interaction.pressed_offset;
1243            let body = Rect::new(
1244                rect.x(),
1245                rect.y() + pressed_offset,
1246                rect.width(),
1247                (rect.height() - pressed_offset).max(0.0),
1248            );
1249            let ring = if selected {
1250                palette.accent_border
1251            } else if hovered || hover_amount > 0.0 || press_amount > 0.0 {
1252                palette.border_hover
1253            } else {
1254                palette.border
1255            };
1256            let ring_width = if selected {
1257                metrics.border_width.max(1.0) + 1.0
1258            } else {
1259                metrics.border_width.max(1.0)
1260            };
1261            let fill_inset = if selected {
1262                metrics.color_palette_selected_swatch_inset
1263            } else {
1264                metrics.color_palette_swatch_inset
1265            } + pressed_offset * 0.5;
1266            let fill_rect = inset_rect(body, Insets::all(fill_inset));
1267
1268            let base_background = if selected {
1269                mix_color(palette.control, palette.accent, interaction.selected_blend)
1270            } else {
1271                palette.control
1272            };
1273            let hover_background = if hover_amount > 0.0 {
1274                mix_color(
1275                    base_background,
1276                    palette.control_hover,
1277                    interaction.hover_blend * hover_amount,
1278                )
1279            } else {
1280                base_background
1281            };
1282            let background = if press_amount > 0.0 {
1283                mix_color(
1284                    hover_background,
1285                    palette.control_active,
1286                    interaction.pressed_blend * press_amount,
1287                )
1288            } else {
1289                hover_background
1290            };
1291
1292            if selected {
1293                ctx.fill(rounded_rect_path(body, radius), background);
1294            } else if hover_amount > 0.0 || press_amount > 0.0 {
1295                ctx.fill(rounded_rect_path(rect, radius), background);
1296            }
1297            draw_rounded_checkerboard(
1298                ctx,
1299                fill_rect,
1300                (radius - fill_inset).max(0.0),
1301                metrics.color_palette_checker_size,
1302                &theme,
1303            );
1304            ctx.fill(
1305                rounded_rect_path(fill_rect, (radius - fill_inset).max(0.0)),
1306                swatch.color,
1307            );
1308            ctx.stroke(
1309                rounded_rect_path(body, radius),
1310                ring,
1311                StrokeStyle::new(ring_width),
1312            );
1313        }
1314    }
1315
1316    fn semantics(&self, ctx: &mut SemanticsCtx) {
1317        let mut node = SemanticsNode::new(
1318            ctx.widget_id(),
1319            SemanticsRole::GenericContainer,
1320            ctx.bounds(),
1321        );
1322        node.name = Some(self.name.clone());
1323        node.value = self.selected_value().map(SemanticsValue::Text);
1324        node.state.focused = ctx.is_focused();
1325        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
1326        ctx.push(node);
1327
1328        let selected = self.current_selected();
1329        let theme = self.resolved_theme();
1330        for (index, swatch) in self.swatches.iter().enumerate() {
1331            let Some(rect) = self.swatch_rect(ctx.bounds(), index, &theme) else {
1332                continue;
1333            };
1334            let mut node = SemanticsNode::new(
1335                color_palette_swatch_id(ctx.widget_id(), index),
1336                SemanticsRole::ColorSwatch,
1337                rect,
1338            );
1339            node.parent = Some(ctx.widget_id());
1340            node.name = Some(swatch.name.clone());
1341            node.value = Some(SemanticsValue::Text(format_color(swatch.color)));
1342            node.state.hovered = self.hovered == Some(index);
1343            node.state.selected = selected == Some(index);
1344            node.actions = vec![SemanticsAction::Activate];
1345            ctx.push(node);
1346        }
1347    }
1348
1349    fn accepts_focus(&self) -> bool {
1350        !self.swatches.is_empty()
1351    }
1352
1353    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1354        let theme = self.resolved_theme();
1355        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1356        ctx.request_paint();
1357        ctx.request_semantics();
1358    }
1359}
1360
1361fn color_palette_swatch_id(parent: WidgetId, index: usize) -> WidgetId {
1362    const TAG: u64 = 7_u64 << 50;
1363    const LOW_MASK: u64 = (1_u64 << 50) - 1;
1364
1365    WidgetId::new(
1366        TAG | (parent
1367            .get()
1368            .wrapping_mul(509)
1369            .wrapping_add(index as u64 + 1)
1370            & LOW_MASK),
1371    )
1372}
1373
1374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1375pub enum BrushPreviewShape {
1376    Round,
1377    Square,
1378}
1379
1380impl BrushPreviewShape {
1381    pub const fn label(self) -> &'static str {
1382        match self {
1383            Self::Round => "Round",
1384            Self::Square => "Square",
1385        }
1386    }
1387}
1388
1389#[derive(Debug, Clone, Copy, PartialEq)]
1390pub struct BrushPreviewSpec {
1391    pub color: Color,
1392    pub size: f32,
1393    pub opacity: f32,
1394    pub shape: BrushPreviewShape,
1395}
1396
1397impl BrushPreviewSpec {
1398    pub fn new(color: Color, size: f32, opacity: f32, shape: BrushPreviewShape) -> Self {
1399        Self {
1400            color,
1401            size: size.max(1.0),
1402            opacity: opacity.clamp(0.0, 1.0),
1403            shape,
1404        }
1405    }
1406}
1407
1408pub struct BrushPreview {
1409    theme: Box<DefaultTheme>,
1410    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1411    name: String,
1412    kind: String,
1413    spec: BrushPreviewSpec,
1414    spec_reader: Option<Box<dyn Fn() -> BrushPreviewSpec>>,
1415    size: Option<Size>,
1416}
1417
1418impl BrushPreview {
1419    pub fn new(name: impl Into<String>) -> Self {
1420        let default_theme = DefaultTheme::default();
1421        Self {
1422            theme: Box::new(DefaultTheme::default()),
1423            theme_reader: None,
1424            name: name.into(),
1425            kind: "brush".to_string(),
1426            spec: BrushPreviewSpec::new(
1427                default_theme.palette.accent,
1428                18.0,
1429                1.0,
1430                BrushPreviewShape::Round,
1431            ),
1432            spec_reader: None,
1433            size: None,
1434        }
1435    }
1436
1437    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1438        self.theme = Box::new(theme);
1439        self.theme_reader = None;
1440        self
1441    }
1442
1443    pub fn theme_when<F>(mut self, theme: F) -> Self
1444    where
1445        F: Fn() -> DefaultTheme + 'static,
1446    {
1447        self.theme_reader = Some(Box::new(theme));
1448        self
1449    }
1450
1451    pub fn spec(mut self, spec: BrushPreviewSpec) -> Self {
1452        self.spec = spec;
1453        self.spec_reader = None;
1454        self
1455    }
1456
1457    pub fn spec_when<F>(mut self, reader: F) -> Self
1458    where
1459        F: Fn() -> BrushPreviewSpec + 'static,
1460    {
1461        self.spec_reader = Some(Box::new(reader));
1462        self
1463    }
1464
1465    pub fn kind(mut self, kind: impl Into<String>) -> Self {
1466        self.kind = kind.into();
1467        self
1468    }
1469
1470    pub fn size(mut self, size: Size) -> Self {
1471        self.size = Some(Size::new(size.width.max(80.0), size.height.max(44.0)));
1472        self
1473    }
1474
1475    fn current_spec(&self) -> BrushPreviewSpec {
1476        self.spec_reader
1477            .as_ref()
1478            .map(|reader| reader())
1479            .unwrap_or(self.spec)
1480    }
1481
1482    fn resolved_theme(&self) -> DefaultTheme {
1483        self.theme_reader
1484            .as_ref()
1485            .map(|theme| theme())
1486            .unwrap_or(*self.theme)
1487    }
1488
1489    fn value_text(kind: &str, spec: BrushPreviewSpec) -> String {
1490        format!(
1491            "{} {}, {:.0} px, {:.0}% opacity",
1492            spec.shape.label(),
1493            kind,
1494            spec.size,
1495            spec.opacity * 100.0
1496        )
1497    }
1498
1499    fn resolved_size(&self, theme: &DefaultTheme) -> Size {
1500        self.size.unwrap_or(Size::new(
1501            theme.metrics.brush_preview_min_width,
1502            theme.metrics.brush_preview_min_height,
1503        ))
1504    }
1505}
1506
1507impl Widget for BrushPreview {
1508    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1509        let theme = self.resolved_theme();
1510        constraints.clamp(self.resolved_size(&theme))
1511    }
1512
1513    fn paint(&self, ctx: &mut PaintCtx) {
1514        let bounds = ctx.bounds();
1515        let theme = self.resolved_theme();
1516        let palette = theme.palette;
1517        let metrics = theme.metrics;
1518        let spec = self.current_spec();
1519        let content = inset_rect(bounds, metrics.brush_preview_padding);
1520        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
1521        let swatch = Rect::new(content.x(), content.y(), swatch_width, content.height());
1522        let sample = Rect::new(
1523            swatch.max_x() + metrics.brush_preview_swatch_gap,
1524            content.y(),
1525            (content.max_x() - swatch.max_x() - metrics.brush_preview_swatch_gap).max(0.0),
1526            content.height(),
1527        );
1528        let preview_color = spec
1529            .color
1530            .with_alpha((spec.color.alpha * spec.opacity).clamp(0.0, 1.0));
1531
1532        ctx.fill(
1533            rounded_rect_path(bounds, metrics.corner_radius),
1534            palette.surface_raised,
1535        );
1536        ctx.stroke(
1537            rounded_rect_path(bounds, metrics.corner_radius),
1538            palette.border,
1539            StrokeStyle::new(metrics.border_width.max(1.0)),
1540        );
1541        draw_checkerboard(ctx, swatch, metrics.brush_preview_checker_size, &theme);
1542        ctx.stroke(
1543            rounded_rect_path(swatch, metrics.indicator_corner_radius),
1544            palette.border.with_alpha(0.70),
1545            StrokeStyle::new(metrics.border_width.max(1.0)),
1546        );
1547        paint_brush_preview_mark(ctx, swatch, spec, preview_color);
1548
1549        let track = Rect::new(
1550            sample.x(),
1551            sample.y() + sample.height() * 0.44,
1552            sample.width(),
1553            sample.height() * 0.24,
1554        );
1555        draw_checkerboard(ctx, track, metrics.brush_preview_checker_size, &theme);
1556        paint_brush_preview_stroke(ctx, track, spec, preview_color);
1557
1558        let text_slot = Rect::new(
1559            sample.x(),
1560            sample.max_y() - metrics.brush_preview_text_height,
1561            sample.width(),
1562            metrics.brush_preview_text_height,
1563        );
1564        let value_text = Self::value_text(&self.kind, spec);
1565        let text_style = TextStyle {
1566            font_size: metrics.brush_preview_text_font_size,
1567            line_height: metrics.brush_preview_text_line_height,
1568            color: palette.text.with_alpha(0.72),
1569            ..theme.body_text_style()
1570        };
1571        ctx.push_clip_rect(text_slot);
1572        paint_aligned_text(
1573            ctx,
1574            text_slot,
1575            &value_text,
1576            &text_style,
1577            text_style.line_height,
1578            0.0,
1579        );
1580        ctx.pop_clip();
1581    }
1582
1583    fn semantics(&self, ctx: &mut SemanticsCtx) {
1584        let spec = self.current_spec();
1585        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Image, ctx.bounds());
1586        node.name = Some(self.name.clone());
1587        node.value = Some(SemanticsValue::Text(Self::value_text(&self.kind, spec)));
1588        ctx.push(node);
1589    }
1590}
1591
1592fn paint_brush_preview_mark(ctx: &mut PaintCtx, rect: Rect, spec: BrushPreviewSpec, color: Color) {
1593    let diameter = spec
1594        .size
1595        .min(rect.width().min(rect.height()) - 10.0)
1596        .max(6.0);
1597    let center = Point::new(
1598        rect.x() + rect.width() * 0.5,
1599        rect.y() + rect.height() * 0.5,
1600    );
1601    let mark = Rect::new(
1602        center.x - diameter * 0.5,
1603        center.y - diameter * 0.5,
1604        diameter,
1605        diameter,
1606    );
1607    match spec.shape {
1608        BrushPreviewShape::Round => ctx.fill(Path::circle(center, diameter * 0.5), color),
1609        BrushPreviewShape::Square => ctx.fill(rounded_rect_path(mark, 2.0), color),
1610    }
1611}
1612
1613fn paint_brush_preview_stroke(
1614    ctx: &mut PaintCtx,
1615    rect: Rect,
1616    spec: BrushPreviewSpec,
1617    color: Color,
1618) {
1619    let dot_count = 7;
1620    let diameter = (spec.size * 0.62).clamp(4.0, rect.height().max(4.0));
1621    for index in 0..dot_count {
1622        let t = if dot_count <= 1 {
1623            0.0
1624        } else {
1625            index as f32 / (dot_count - 1) as f32
1626        };
1627        let center = Point::new(
1628            rect.x() + diameter * 0.5 + t * (rect.width() - diameter).max(0.0),
1629            rect.y() + rect.height() * 0.5,
1630        );
1631        let alpha = 0.35 + t * 0.65;
1632        let color = color.with_alpha((color.alpha * alpha).clamp(0.0, 1.0));
1633        match spec.shape {
1634            BrushPreviewShape::Round => ctx.fill(Path::circle(center, diameter * 0.5), color),
1635            BrushPreviewShape::Square => ctx.fill(
1636                rounded_rect_path(
1637                    Rect::new(
1638                        center.x - diameter * 0.5,
1639                        center.y - diameter * 0.5,
1640                        diameter,
1641                        diameter,
1642                    ),
1643                    1.5,
1644                ),
1645                color,
1646            ),
1647        }
1648    }
1649}
1650
1651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1652enum ActiveChannel {
1653    ColorWheel,
1654    SaturationValue,
1655    Hue,
1656    Saturation,
1657    Value,
1658    Alpha,
1659    EncodingSelector,
1660    EncodingOption(usize),
1661    RgbRed,
1662    RgbGreen,
1663    RgbBlue,
1664}
1665
1666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1667enum ColorPickerSemanticPart {
1668    CurrentColor,
1669    PreviousColor,
1670    ColorRange,
1671    ColorRangeMenu,
1672    ColorRangeOption(usize),
1673    SaturationValue,
1674    Hue,
1675    Saturation,
1676    Value,
1677    Alpha,
1678    Red,
1679    Green,
1680    Blue,
1681    Hex,
1682}
1683
1684pub struct ColorPicker {
1685    theme: Box<DefaultTheme>,
1686    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1687    name: String,
1688    editing_space: ColorSpace,
1689    hue: f32,
1690    saturation: f32,
1691    value: f32,
1692    alpha: f32,
1693    previous_color: Color,
1694    show_alpha: bool,
1695    compact: bool,
1696    encoding_dropdown_open: bool,
1697    active: Option<ActiveChannel>,
1698    focus_animation: AnimatedScalar,
1699    color_reader: Option<Box<dyn Fn() -> Color>>,
1700    on_change: Option<Box<dyn FnMut(Color)>>,
1701}
1702
1703#[derive(Debug, Clone, Copy)]
1704struct ColorPickerResolvedState {
1705    color: Color,
1706    editing_space: ColorSpace,
1707    hue: f32,
1708    saturation: f32,
1709    value: f32,
1710    alpha: f32,
1711    hdr_capable: bool,
1712    max_channel_value: f32,
1713}
1714
1715impl ColorPicker {
1716    const MAX_HDR_VALUE: f32 = 12.0;
1717    const ENCODING_OPTIONS: [ColorSpace; 4] = [
1718        ColorSpace::Srgb,
1719        ColorSpace::LinearSrgb,
1720        ColorSpace::DisplayP3,
1721        ColorSpace::LinearDisplayP3,
1722    ];
1723
1724    pub fn new(name: impl Into<String>) -> Self {
1725        let theme = DefaultTheme::default();
1726        Self::from_color(name, theme.palette.accent)
1727    }
1728
1729    pub fn from_color(name: impl Into<String>, color: Color) -> Self {
1730        let (hue, saturation, value) = rgb_to_hsv(color);
1731        Self {
1732            theme: Box::new(DefaultTheme::default()),
1733            theme_reader: None,
1734            name: name.into(),
1735            editing_space: color.space,
1736            hue,
1737            saturation,
1738            value,
1739            alpha: color.alpha,
1740            previous_color: color,
1741            show_alpha: true,
1742            compact: false,
1743            encoding_dropdown_open: false,
1744            active: None,
1745            focus_animation: AnimatedScalar::new(0.0),
1746            color_reader: None,
1747            on_change: None,
1748        }
1749    }
1750
1751    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1752        self.theme = Box::new(theme);
1753        self.theme_reader = None;
1754        self
1755    }
1756
1757    pub fn theme_when<F>(mut self, theme: F) -> Self
1758    where
1759        F: Fn() -> DefaultTheme + 'static,
1760    {
1761        self.theme_reader = Some(Box::new(theme));
1762        self
1763    }
1764
1765    pub fn show_alpha(mut self, show_alpha: bool) -> Self {
1766        self.show_alpha = show_alpha;
1767        self
1768    }
1769
1770    pub fn compact(mut self, compact: bool) -> Self {
1771        self.compact = compact;
1772        self
1773    }
1774
1775    pub fn on_change<F>(mut self, on_change: F) -> Self
1776    where
1777        F: FnMut(Color) + 'static,
1778    {
1779        self.on_change = Some(Box::new(on_change));
1780        self
1781    }
1782
1783    pub fn color_when<F>(mut self, color: F) -> Self
1784    where
1785        F: Fn() -> Color + 'static,
1786    {
1787        self.color_reader = Some(Box::new(color));
1788        self
1789    }
1790
1791    pub fn color(&self) -> Color {
1792        hsv_to_color(
1793            self.editing_space,
1794            self.hue,
1795            self.saturation,
1796            self.value,
1797            self.alpha,
1798        )
1799    }
1800
1801    fn hdr_capable(&self) -> bool {
1802        color_space_hdr_capable(self.editing_space)
1803    }
1804
1805    fn max_channel_value(&self) -> f32 {
1806        if self.hdr_capable() {
1807            Self::MAX_HDR_VALUE
1808        } else {
1809            1.0
1810        }
1811    }
1812
1813    fn external_color(&self) -> Option<Color> {
1814        if self.active.is_none() && !self.encoding_dropdown_open {
1815            self.color_reader.as_ref().map(|reader| reader())
1816        } else {
1817            None
1818        }
1819    }
1820
1821    fn resolved_theme(&self) -> DefaultTheme {
1822        self.theme_reader
1823            .as_ref()
1824            .map(|theme| theme())
1825            .unwrap_or(*self.theme)
1826    }
1827
1828    fn layout_metrics_for(&self, theme: &DefaultTheme) -> ControlMetrics {
1829        if self.compact {
1830            ControlMetrics::from_tokens(theme.spacing, theme.radius, ThemeDensity::Compact)
1831        } else {
1832            theme.metrics
1833        }
1834    }
1835
1836    fn layout_metrics(&self) -> ControlMetrics {
1837        let theme = self.resolved_theme();
1838        self.layout_metrics_for(&theme)
1839    }
1840
1841    fn resolved_state(&self) -> ColorPickerResolvedState {
1842        if let Some(color) = self.external_color() {
1843            let (hue, saturation, value) = rgb_to_hsv(color);
1844            let hdr_capable = color_space_hdr_capable(color.space);
1845            return ColorPickerResolvedState {
1846                color,
1847                editing_space: color.space,
1848                hue,
1849                saturation,
1850                value,
1851                alpha: color.alpha,
1852                hdr_capable,
1853                max_channel_value: if hdr_capable {
1854                    Self::MAX_HDR_VALUE
1855                } else {
1856                    1.0
1857                },
1858            };
1859        }
1860
1861        ColorPickerResolvedState {
1862            color: self.color(),
1863            editing_space: self.editing_space,
1864            hue: self.hue,
1865            saturation: self.saturation,
1866            value: self.value,
1867            alpha: self.alpha,
1868            hdr_capable: self.hdr_capable(),
1869            max_channel_value: self.max_channel_value(),
1870        }
1871    }
1872
1873    fn sync_external_color(&mut self) -> bool {
1874        let Some(color) = self.external_color() else {
1875            return false;
1876        };
1877        if !colors_close(self.color(), color) {
1878            self.apply_color(color);
1879            return true;
1880        }
1881        false
1882    }
1883
1884    fn content_inset(&self) -> f32 {
1885        self.layout_metrics().color_picker_content_inset
1886    }
1887
1888    fn panel_gap(&self) -> f32 {
1889        self.layout_metrics().color_picker_panel_gap
1890    }
1891
1892    fn top_bar_height(&self) -> f32 {
1893        self.layout_metrics().color_picker_top_bar_height
1894    }
1895
1896    fn swatch_width(&self) -> f32 {
1897        self.layout_metrics().color_picker_swatch_width
1898    }
1899
1900    fn swatch_gap(&self) -> f32 {
1901        self.layout_metrics().color_picker_swatch_gap
1902    }
1903
1904    fn section_gap(&self) -> f32 {
1905        self.layout_metrics().color_picker_section_gap
1906    }
1907
1908    fn wheel_size(&self) -> f32 {
1909        self.layout_metrics().color_picker_wheel_size
1910    }
1911
1912    fn map_size(&self) -> f32 {
1913        self.layout_metrics().color_picker_map_size
1914    }
1915
1916    fn right_panel_width(&self) -> f32 {
1917        self.layout_metrics().color_picker_right_panel_width
1918    }
1919
1920    fn row_height(&self) -> f32 {
1921        self.layout_metrics().color_picker_row_height
1922    }
1923
1924    fn row_gap(&self) -> f32 {
1925        self.layout_metrics().color_picker_row_gap
1926    }
1927
1928    fn field_height(&self) -> f32 {
1929        self.layout_metrics().color_picker_field_height
1930    }
1931
1932    fn field_gap(&self) -> f32 {
1933        self.layout_metrics().color_picker_field_gap
1934    }
1935
1936    fn dropdown_gap(&self) -> f32 {
1937        self.layout_metrics().color_picker_dropdown_gap
1938    }
1939
1940    fn encoding_menu_row_height(&self) -> f32 {
1941        self.layout_metrics().color_picker_encoding_menu_row_height
1942    }
1943
1944    fn channel_slider_count(&self) -> usize {
1945        if self.show_alpha { 4 } else { 3 }
1946    }
1947
1948    fn desired_size(&self) -> Size {
1949        let inset = self.content_inset();
1950        let left_height = self.wheel_size()
1951            + self.section_gap()
1952            + self.channel_slider_count() as f32 * self.row_height()
1953            + self.channel_slider_count().saturating_sub(1) as f32 * self.row_gap();
1954        let right_height = self.map_size()
1955            + self.section_gap()
1956            + 3.0 * self.row_height()
1957            + 2.0 * self.row_gap()
1958            + self.field_gap()
1959            + self.field_height();
1960        Size::new(
1961            inset * 2.0 + self.wheel_size() + self.panel_gap() + self.right_panel_width(),
1962            inset * 2.0 + self.top_bar_height() + self.panel_gap() + left_height.max(right_height),
1963        )
1964    }
1965
1966    fn content_rect(&self, bounds: Rect) -> Rect {
1967        inset_rect(bounds, Insets::all(self.content_inset()))
1968    }
1969
1970    fn header_rect(&self, bounds: Rect) -> Rect {
1971        let content = self.content_rect(bounds);
1972        Rect::new(
1973            content.x(),
1974            content.y(),
1975            content.width(),
1976            self.top_bar_height(),
1977        )
1978    }
1979
1980    fn current_swatch_rect(&self, bounds: Rect) -> Rect {
1981        let header = self.header_rect(bounds);
1982        Rect::new(header.x(), header.y(), self.swatch_width(), header.height())
1983    }
1984
1985    fn previous_swatch_rect(&self, bounds: Rect) -> Rect {
1986        let current = self.current_swatch_rect(bounds);
1987        Rect::new(
1988            current.max_x() + self.swatch_gap(),
1989            current.y(),
1990            self.swatch_width(),
1991            current.height(),
1992        )
1993    }
1994
1995    fn left_column_rect(&self, bounds: Rect) -> Rect {
1996        let content = self.content_rect(bounds);
1997        let y = self.header_rect(bounds).max_y() + self.panel_gap();
1998        let width = self.wheel_size().min(content.width());
1999        Rect::new(content.x(), y, width, content.max_y() - y)
2000    }
2001
2002    fn right_column_rect(&self, bounds: Rect) -> Rect {
2003        let content = self.content_rect(bounds);
2004        let left = self.left_column_rect(bounds);
2005        Rect::new(
2006            left.max_x() + self.panel_gap(),
2007            left.y(),
2008            content.max_x() - (left.max_x() + self.panel_gap()),
2009            content.max_y() - left.y(),
2010        )
2011    }
2012
2013    fn color_wheel_rect(&self, bounds: Rect) -> Rect {
2014        let left = self.left_column_rect(bounds);
2015        Rect::new(left.x(), left.y(), self.wheel_size(), self.wheel_size())
2016    }
2017
2018    fn saturation_value_rect(&self, bounds: Rect) -> Rect {
2019        let right = self.right_column_rect(bounds);
2020        Rect::new(
2021            right.x(),
2022            right.y(),
2023            right.width().min(self.map_size()),
2024            self.map_size(),
2025        )
2026    }
2027
2028    fn left_slider_rect(&self, bounds: Rect, index: usize) -> Rect {
2029        let wheel = self.color_wheel_rect(bounds);
2030        let y = wheel.max_y()
2031            + self.section_gap()
2032            + index as f32 * (self.row_height() + self.row_gap());
2033        Rect::new(wheel.x(), y, wheel.width(), self.row_height())
2034    }
2035
2036    fn encoding_rect(&self, bounds: Rect) -> Rect {
2037        let header = self.header_rect(bounds);
2038        let selector_x = header.x()
2039            + self.swatch_width()
2040            + self.swatch_gap()
2041            + self.swatch_width()
2042            + self.panel_gap();
2043        Rect::new(
2044            selector_x,
2045            header.y() + ((header.height() - self.field_height()) * 0.5),
2046            (header.max_x() - selector_x).max(0.0),
2047            self.field_height(),
2048        )
2049    }
2050
2051    fn encoding_menu_rect(&self, bounds: Rect) -> Rect {
2052        let encoding = self.encoding_rect(bounds);
2053        Rect::new(
2054            encoding.x(),
2055            encoding.max_y() + self.dropdown_gap(),
2056            encoding.width(),
2057            self.encoding_menu_row_height() * Self::ENCODING_OPTIONS.len() as f32,
2058        )
2059    }
2060
2061    fn encoding_option_rect(&self, bounds: Rect, index: usize) -> Rect {
2062        let menu = self.encoding_menu_rect(bounds);
2063        Rect::new(
2064            menu.x(),
2065            menu.y() + index as f32 * self.encoding_menu_row_height(),
2066            menu.width(),
2067            self.encoding_menu_row_height(),
2068        )
2069    }
2070
2071    fn encoding_option_at(&self, bounds: Rect, position: Point) -> Option<usize> {
2072        if !self.encoding_dropdown_open || !self.encoding_menu_rect(bounds).contains(position) {
2073            return None;
2074        }
2075
2076        Self::ENCODING_OPTIONS
2077            .iter()
2078            .enumerate()
2079            .find_map(|(index, _)| {
2080                self.encoding_option_rect(bounds, index)
2081                    .contains(position)
2082                    .then_some(index)
2083            })
2084    }
2085
2086    fn rgb_row_rect(&self, bounds: Rect, index: usize) -> Rect {
2087        let map = self.saturation_value_rect(bounds);
2088        let y =
2089            map.max_y() + self.section_gap() + index as f32 * (self.row_height() + self.row_gap());
2090        Rect::new(map.x(), y, map.width(), self.row_height())
2091    }
2092
2093    fn hex_rect(&self, bounds: Rect) -> Rect {
2094        let last_row = self.rgb_row_rect(bounds, 2);
2095        Rect::new(
2096            last_row.x(),
2097            last_row.max_y() + self.field_gap(),
2098            last_row.width(),
2099            self.field_height(),
2100        )
2101    }
2102
2103    fn update_from_position(&mut self, bounds: Rect, channel: ActiveChannel, position: Point) {
2104        match channel {
2105            ActiveChannel::ColorWheel => {
2106                let rect = self.color_wheel_rect(bounds);
2107                let center = Point::new(
2108                    rect.x() + rect.width() * 0.5,
2109                    rect.y() + rect.height() * 0.5,
2110                );
2111                let dx = position.x - center.x;
2112                let dy = position.y - center.y;
2113                let angle = dy.atan2(dx);
2114                self.hue = ((angle / std::f32::consts::TAU) + 1.0).rem_euclid(1.0);
2115                self.emit_change();
2116            }
2117            ActiveChannel::SaturationValue => {
2118                let rect = self.saturation_value_rect(bounds);
2119                self.saturation = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2120                let t = (1.0 - ((position.y - rect.y()) / rect.height())).clamp(0.0, 1.0);
2121                self.value = if self.hdr_capable() {
2122                    hdr_slider_to_value(t)
2123                } else {
2124                    t
2125                };
2126                self.emit_change();
2127            }
2128            ActiveChannel::Hue => {
2129                let rect = self.left_slider_rect(bounds, 0);
2130                self.hue = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2131                self.emit_change();
2132            }
2133            ActiveChannel::Saturation => {
2134                let rect = self.left_slider_rect(bounds, 1);
2135                self.saturation = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2136                self.emit_change();
2137            }
2138            ActiveChannel::Value => {
2139                let rect = self.left_slider_rect(bounds, 2);
2140                let t = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2141                self.value = if self.hdr_capable() {
2142                    hdr_slider_to_value(t)
2143                } else {
2144                    t
2145                };
2146                self.emit_change();
2147            }
2148            ActiveChannel::Alpha => {
2149                let rect = self.left_slider_rect(bounds, 3);
2150                self.alpha = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2151                self.emit_change();
2152            }
2153            ActiveChannel::EncodingSelector | ActiveChannel::EncodingOption(_) => {}
2154            ActiveChannel::RgbRed => self.update_rgb_channel_from_position(bounds, 0, position),
2155            ActiveChannel::RgbGreen => self.update_rgb_channel_from_position(bounds, 1, position),
2156            ActiveChannel::RgbBlue => self.update_rgb_channel_from_position(bounds, 2, position),
2157        }
2158    }
2159
2160    fn emit_change(&mut self) {
2161        let color = self.color();
2162        if let Some(on_change) = &mut self.on_change {
2163            on_change(color);
2164        }
2165    }
2166
2167    fn apply_color(&mut self, color: Color) {
2168        self.editing_space = color.space;
2169        let (hue, saturation, value) = rgb_to_hsv(color);
2170        self.hue = hue;
2171        self.saturation = saturation;
2172        self.value = value;
2173        self.alpha = color.alpha;
2174    }
2175
2176    fn set_editing_space(&mut self, next_space: ColorSpace) {
2177        if self.editing_space == next_space {
2178            return;
2179        }
2180
2181        let current = self.color();
2182        self.apply_color(Color::new(
2183            next_space,
2184            current.red,
2185            current.green,
2186            current.blue,
2187            current.alpha,
2188        ));
2189        self.emit_change();
2190    }
2191
2192    fn update_rgb_channel_from_position(
2193        &mut self,
2194        bounds: Rect,
2195        channel_index: usize,
2196        position: Point,
2197    ) {
2198        let rect = self.rgb_row_rect(bounds, channel_index);
2199        let t = ((position.x - rect.x()) / rect.width()).clamp(0.0, 1.0);
2200        let mut channels = [self.color().red, self.color().green, self.color().blue];
2201        channels[channel_index] = self.max_channel_value() * t;
2202        self.apply_color(Color::new(
2203            self.editing_space,
2204            channels[0],
2205            channels[1],
2206            channels[2],
2207            self.alpha,
2208        ));
2209        self.emit_change();
2210    }
2211
2212    fn hit_channel(&self, bounds: Rect, position: Point) -> Option<ActiveChannel> {
2213        if point_in_wheel_ring(self.color_wheel_rect(bounds), position) {
2214            Some(ActiveChannel::ColorWheel)
2215        } else if self.saturation_value_rect(bounds).contains(position) {
2216            Some(ActiveChannel::SaturationValue)
2217        } else if self.left_slider_rect(bounds, 0).contains(position) {
2218            Some(ActiveChannel::Hue)
2219        } else if self.left_slider_rect(bounds, 1).contains(position) {
2220            Some(ActiveChannel::Saturation)
2221        } else if self.left_slider_rect(bounds, 2).contains(position) {
2222            Some(ActiveChannel::Value)
2223        } else if self.show_alpha && self.left_slider_rect(bounds, 3).contains(position) {
2224            Some(ActiveChannel::Alpha)
2225        } else if self.encoding_rect(bounds).contains(position) {
2226            Some(ActiveChannel::EncodingSelector)
2227        } else if self.rgb_row_rect(bounds, 0).contains(position) {
2228            Some(ActiveChannel::RgbRed)
2229        } else if self.rgb_row_rect(bounds, 1).contains(position) {
2230            Some(ActiveChannel::RgbGreen)
2231        } else if self.rgb_row_rect(bounds, 2).contains(position) {
2232            Some(ActiveChannel::RgbBlue)
2233        } else {
2234            None
2235        }
2236    }
2237
2238    fn color_semantics_text(&self, color: Color, hdr_capable: bool) -> String {
2239        if hdr_capable && is_hdr_color(color) {
2240            format!(
2241                "R {:.3} G {:.3} B {:.3} A {:.3}",
2242                color.red, color.green, color.blue, color.alpha
2243            )
2244        } else {
2245            format_color(color)
2246        }
2247    }
2248
2249    fn push_color_swatch_semantics(
2250        &self,
2251        ctx: &mut SemanticsCtx,
2252        part: ColorPickerSemanticPart,
2253        name: &'static str,
2254        bounds: Rect,
2255        color: Color,
2256        hdr_capable: bool,
2257    ) {
2258        let mut node = color_picker_child_semantics_node(
2259            ctx.widget_id(),
2260            part,
2261            SemanticsRole::ColorSwatch,
2262            bounds,
2263            name,
2264        );
2265        node.value = Some(SemanticsValue::Text(
2266            self.color_semantics_text(color, hdr_capable),
2267        ));
2268        ctx.push(node);
2269    }
2270
2271    fn push_slider_semantics(
2272        &self,
2273        ctx: &mut SemanticsCtx,
2274        part: ColorPickerSemanticPart,
2275        name: &'static str,
2276        bounds: Rect,
2277        value: f32,
2278        min: f32,
2279        max: f32,
2280    ) {
2281        let mut node = color_picker_child_semantics_node(
2282            ctx.widget_id(),
2283            part,
2284            SemanticsRole::Slider,
2285            bounds,
2286            name,
2287        );
2288        node.value = Some(SemanticsValue::Range {
2289            value: value as f64,
2290            min: min as f64,
2291            max: max as f64,
2292        });
2293        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2294        ctx.push(node);
2295    }
2296
2297    fn push_component_semantics(&self, ctx: &mut SemanticsCtx, resolved: ColorPickerResolvedState) {
2298        let bounds = ctx.bounds();
2299        let current = resolved.color;
2300        self.push_color_swatch_semantics(
2301            ctx,
2302            ColorPickerSemanticPart::CurrentColor,
2303            "Current color",
2304            self.current_swatch_rect(bounds),
2305            current,
2306            resolved.hdr_capable,
2307        );
2308        self.push_color_swatch_semantics(
2309            ctx,
2310            ColorPickerSemanticPart::PreviousColor,
2311            "Previous color",
2312            self.previous_swatch_rect(bounds),
2313            self.previous_color,
2314            color_space_hdr_capable(self.previous_color.space),
2315        );
2316
2317        let mut range = color_picker_child_semantics_node(
2318            ctx.widget_id(),
2319            ColorPickerSemanticPart::ColorRange,
2320            SemanticsRole::ComboBox,
2321            self.encoding_rect(bounds),
2322            "Color range",
2323        );
2324        range.value = Some(SemanticsValue::Text(
2325            editing_space_label(resolved.editing_space).to_string(),
2326        ));
2327        range.state.expanded = Some(self.encoding_dropdown_open);
2328        range.actions = vec![
2329            SemanticsAction::Focus,
2330            if self.encoding_dropdown_open {
2331                SemanticsAction::Collapse
2332            } else {
2333                SemanticsAction::Expand
2334            },
2335            SemanticsAction::SetValue,
2336        ];
2337        ctx.push(range);
2338
2339        let mut saturation_value = color_picker_child_semantics_node(
2340            ctx.widget_id(),
2341            ColorPickerSemanticPart::SaturationValue,
2342            SemanticsRole::Slider,
2343            self.saturation_value_rect(bounds),
2344            "Saturation and value",
2345        );
2346        saturation_value.description = Some(format!(
2347            "Saturation {:.1}%, value {:.3}",
2348            resolved.saturation * 100.0,
2349            resolved.value
2350        ));
2351        saturation_value.value = Some(SemanticsValue::Range {
2352            value: resolved.value as f64,
2353            min: 0.0,
2354            max: resolved.max_channel_value as f64,
2355        });
2356        saturation_value.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2357        ctx.push(saturation_value);
2358
2359        self.push_slider_semantics(
2360            ctx,
2361            ColorPickerSemanticPart::Hue,
2362            "Hue",
2363            self.left_slider_rect(bounds, 0),
2364            resolved.hue * 360.0,
2365            0.0,
2366            360.0,
2367        );
2368        self.push_slider_semantics(
2369            ctx,
2370            ColorPickerSemanticPart::Saturation,
2371            "Saturation",
2372            self.left_slider_rect(bounds, 1),
2373            resolved.saturation * 100.0,
2374            0.0,
2375            100.0,
2376        );
2377        self.push_slider_semantics(
2378            ctx,
2379            ColorPickerSemanticPart::Value,
2380            "Value",
2381            self.left_slider_rect(bounds, 2),
2382            resolved.value,
2383            0.0,
2384            resolved.max_channel_value,
2385        );
2386        if self.show_alpha {
2387            self.push_slider_semantics(
2388                ctx,
2389                ColorPickerSemanticPart::Alpha,
2390                "Alpha",
2391                self.left_slider_rect(bounds, 3),
2392                resolved.alpha * 100.0,
2393                0.0,
2394                100.0,
2395            );
2396        }
2397
2398        let rgb = current.to_array();
2399        for (index, (part, name)) in [
2400            (ColorPickerSemanticPart::Red, "Red"),
2401            (ColorPickerSemanticPart::Green, "Green"),
2402            (ColorPickerSemanticPart::Blue, "Blue"),
2403        ]
2404        .into_iter()
2405        .enumerate()
2406        {
2407            self.push_slider_semantics(
2408                ctx,
2409                part,
2410                name,
2411                self.rgb_row_rect(bounds, index),
2412                rgb[index],
2413                0.0,
2414                resolved.max_channel_value,
2415            );
2416        }
2417
2418        let hex_name = if resolved.hdr_capable && is_hdr_color(current) {
2419            "HDR hex unavailable".to_string()
2420        } else {
2421            format!("Hex color {}", format_color(current))
2422        };
2423        let hex = color_picker_child_semantics_node(
2424            ctx.widget_id(),
2425            ColorPickerSemanticPart::Hex,
2426            SemanticsRole::Text,
2427            self.hex_rect(bounds),
2428            hex_name,
2429        );
2430        ctx.push(hex);
2431
2432        if self.encoding_dropdown_open {
2433            let menu_id = color_picker_child_semantics_id(
2434                ctx.widget_id(),
2435                ColorPickerSemanticPart::ColorRangeMenu,
2436            );
2437            let mut menu = color_picker_child_semantics_node(
2438                ctx.widget_id(),
2439                ColorPickerSemanticPart::ColorRangeMenu,
2440                SemanticsRole::Menu,
2441                self.encoding_menu_rect(bounds),
2442                "Color range options",
2443            );
2444            menu.state.expanded = Some(true);
2445            ctx.push(menu);
2446
2447            for (index, space) in Self::ENCODING_OPTIONS.iter().copied().enumerate() {
2448                let mut item = color_picker_child_semantics_node_with_parent(
2449                    ctx.widget_id(),
2450                    menu_id,
2451                    ColorPickerSemanticPart::ColorRangeOption(index),
2452                    SemanticsRole::MenuItem,
2453                    self.encoding_option_rect(bounds, index),
2454                    editing_space_label(space),
2455                );
2456                item.state.selected = space == resolved.editing_space;
2457                item.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
2458                ctx.push(item);
2459            }
2460        }
2461    }
2462}
2463
2464fn color_picker_child_semantics_id(parent: WidgetId, part: ColorPickerSemanticPart) -> WidgetId {
2465    let slot = match part {
2466        ColorPickerSemanticPart::CurrentColor => 1,
2467        ColorPickerSemanticPart::PreviousColor => 2,
2468        ColorPickerSemanticPart::ColorRange => 3,
2469        ColorPickerSemanticPart::ColorRangeMenu => 4,
2470        ColorPickerSemanticPart::ColorRangeOption(index) => 32 + index as u64,
2471        ColorPickerSemanticPart::SaturationValue => 5,
2472        ColorPickerSemanticPart::Hue => 6,
2473        ColorPickerSemanticPart::Saturation => 7,
2474        ColorPickerSemanticPart::Value => 8,
2475        ColorPickerSemanticPart::Alpha => 9,
2476        ColorPickerSemanticPart::Red => 10,
2477        ColorPickerSemanticPart::Green => 11,
2478        ColorPickerSemanticPart::Blue => 12,
2479        ColorPickerSemanticPart::Hex => 13,
2480    };
2481    const TAG: u64 = 3_u64 << 51;
2482    const LOW_MASK: u64 = (1_u64 << 51) - 1;
2483    WidgetId::new(TAG | (parent.get().wrapping_mul(397).wrapping_add(slot) & LOW_MASK))
2484}
2485
2486fn color_picker_child_semantics_node(
2487    parent: WidgetId,
2488    part: ColorPickerSemanticPart,
2489    role: SemanticsRole,
2490    bounds: Rect,
2491    name: impl Into<String>,
2492) -> SemanticsNode {
2493    color_picker_child_semantics_node_with_parent(parent, parent, part, role, bounds, name)
2494}
2495
2496fn color_picker_child_semantics_node_with_parent(
2497    owner: WidgetId,
2498    parent: WidgetId,
2499    part: ColorPickerSemanticPart,
2500    role: SemanticsRole,
2501    bounds: Rect,
2502    name: impl Into<String>,
2503) -> SemanticsNode {
2504    let mut node = SemanticsNode::new(color_picker_child_semantics_id(owner, part), role, bounds);
2505    node.parent = Some(parent);
2506    node.name = Some(name.into());
2507    node
2508}
2509
2510impl Widget for ColorPicker {
2511    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2512        if self.sync_external_color() {
2513            ctx.request_paint();
2514            ctx.request_semantics();
2515        }
2516        match event {
2517            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2518                if let Some(active) = self.active {
2519                    self.update_from_position(ctx.bounds(), active, pointer.position);
2520                    ctx.request_paint();
2521                    ctx.request_semantics();
2522                    ctx.set_handled();
2523                }
2524            }
2525            Event::Pointer(pointer)
2526                if pointer.kind == PointerEventKind::Down
2527                    && pointer.button == Some(PointerButton::Primary) =>
2528            {
2529                if let Some(option) = self.encoding_option_at(ctx.bounds(), pointer.position) {
2530                    self.active = Some(ActiveChannel::EncodingOption(option));
2531                    ctx.request_focus();
2532                    ctx.request_pointer_capture(pointer.pointer_id);
2533                    ctx.request_paint();
2534                    ctx.request_semantics();
2535                    ctx.set_handled();
2536                    return;
2537                }
2538
2539                let active = self.hit_channel(ctx.bounds(), pointer.position);
2540                if let Some(active) = active {
2541                    self.active = Some(active);
2542                    if active == ActiveChannel::EncodingSelector {
2543                        self.encoding_dropdown_open = !self.encoding_dropdown_open;
2544                    } else {
2545                        self.encoding_dropdown_open = false;
2546                        self.update_from_position(ctx.bounds(), active, pointer.position);
2547                    }
2548                    ctx.request_focus();
2549                    ctx.request_pointer_capture(pointer.pointer_id);
2550                    ctx.request_paint();
2551                    ctx.request_semantics();
2552                    ctx.set_handled();
2553                } else if self.encoding_dropdown_open {
2554                    self.encoding_dropdown_open = false;
2555                    ctx.request_paint();
2556                    ctx.request_semantics();
2557                }
2558            }
2559            Event::Pointer(pointer)
2560                if pointer.kind == PointerEventKind::Up
2561                    && pointer.button == Some(PointerButton::Primary) =>
2562            {
2563                if let Some(active) = self.active.take() {
2564                    if let ActiveChannel::EncodingOption(index) = active {
2565                        if self
2566                            .encoding_option_rect(ctx.bounds(), index)
2567                            .contains(pointer.position)
2568                        {
2569                            self.set_editing_space(Self::ENCODING_OPTIONS[index]);
2570                        }
2571                        self.encoding_dropdown_open = false;
2572                    }
2573                    ctx.release_pointer_capture(pointer.pointer_id);
2574                    ctx.request_paint();
2575                    ctx.request_semantics();
2576                    ctx.set_handled();
2577                }
2578            }
2579            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2580                if self.active.take().is_some() {
2581                    self.encoding_dropdown_open = false;
2582                    ctx.release_pointer_capture(pointer.pointer_id);
2583                    ctx.request_paint();
2584                    ctx.request_semantics();
2585                    ctx.set_handled();
2586                }
2587            }
2588            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
2589                let saturation_step = if key.modifiers.shift { 0.1 } else { 0.02 };
2590                let value_step = if key.modifiers.shift { 0.5 } else { 0.1 };
2591                match key.key.as_str() {
2592                    "ArrowLeft" => {
2593                        self.saturation = (self.saturation - saturation_step).clamp(0.0, 1.0)
2594                    }
2595                    "ArrowRight" => {
2596                        self.saturation = (self.saturation + saturation_step).clamp(0.0, 1.0)
2597                    }
2598                    "ArrowUp" => {
2599                        self.value = (self.value + value_step).clamp(0.0, self.max_channel_value())
2600                    }
2601                    "ArrowDown" => {
2602                        self.value = (self.value - value_step).clamp(0.0, self.max_channel_value())
2603                    }
2604                    _ => return,
2605                }
2606                self.emit_change();
2607                ctx.request_paint();
2608                ctx.request_semantics();
2609                ctx.set_handled();
2610            }
2611            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
2612                let (changed, active) = advance_scalar(&mut self.focus_animation, *time);
2613                if changed {
2614                    ctx.request_paint();
2615                }
2616                if active {
2617                    ctx.request_animation_frame();
2618                }
2619            }
2620            _ => {}
2621        }
2622    }
2623
2624    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2625        self.sync_external_color();
2626        constraints.clamp(self.desired_size())
2627    }
2628
2629    fn paint(&self, ctx: &mut PaintCtx) {
2630        let theme = self.resolved_theme();
2631        let palette = theme.palette;
2632        let resolved = self.resolved_state();
2633        let current = resolved.color;
2634        let wheel = self.color_wheel_rect(ctx.bounds());
2635        let map = self.saturation_value_rect(ctx.bounds());
2636        let encoding = self.encoding_rect(ctx.bounds());
2637
2638        draw_surface(ctx, ctx.bounds(), &theme, self.focus_animation.value);
2639        paint_picker_header(
2640            ctx,
2641            self.current_swatch_rect(ctx.bounds()),
2642            self.previous_swatch_rect(ctx.bounds()),
2643            &theme,
2644            self.previous_color,
2645            current,
2646        );
2647        paint_dropdown(
2648            ctx,
2649            encoding,
2650            &theme,
2651            editing_space_label(resolved.editing_space),
2652        );
2653
2654        paint_color_wheel(ctx, wheel, &theme);
2655        paint_wheel_marker(ctx, wheel, resolved.hue, &theme);
2656
2657        paint_saturation_value_plane(
2658            ctx,
2659            map,
2660            resolved.editing_space,
2661            resolved.hue,
2662            resolved.max_channel_value,
2663            &theme,
2664        );
2665        let marker = Point::new(
2666            map.x() + resolved.saturation * map.width(),
2667            map.y()
2668                + (1.0
2669                    - if resolved.hdr_capable {
2670                        hdr_value_to_slider(resolved.value)
2671                    } else {
2672                        resolved.value.clamp(0.0, 1.0)
2673                    })
2674                    * map.height(),
2675        );
2676        paint_marker(ctx, marker, contrast_color(current, &theme), &theme);
2677
2678        let rows = [
2679            ("H", format!("{:.2}", resolved.hue * 360.0)),
2680            ("S", format!("{:.2}", resolved.saturation * 100.0)),
2681            ("V", format!("{:.3}", resolved.value)),
2682            ("A", format!("{:.1}", resolved.alpha * 100.0)),
2683        ];
2684        for (index, (label, value_text)) in rows.into_iter().enumerate() {
2685            if index == 3 && !self.show_alpha {
2686                continue;
2687            }
2688            let rect = self.left_slider_rect(ctx.bounds(), index);
2689            match index {
2690                0 => paint_hue_bar(ctx, rect, &theme),
2691                1 => paint_saturation_bar(
2692                    ctx,
2693                    rect,
2694                    resolved.editing_space,
2695                    resolved.hue,
2696                    resolved.value.max(1.0),
2697                    &theme,
2698                ),
2699                2 => paint_value_bar(
2700                    ctx,
2701                    rect,
2702                    resolved.editing_space,
2703                    resolved.hue,
2704                    resolved.saturation,
2705                    resolved.hdr_capable,
2706                    &theme,
2707                ),
2708                _ => {
2709                    draw_checkerboard(ctx, rect, theme.metrics.color_swatch_checker_size, &theme);
2710                    paint_alpha_bar(ctx, rect, current, &theme);
2711                }
2712            }
2713            paint_labeled_row_text(ctx, rect, label, &value_text, &theme, palette.placeholder);
2714            let marker_x = match index {
2715                0 => rect.x() + resolved.hue * rect.width(),
2716                1 => rect.x() + resolved.saturation * rect.width(),
2717                2 => {
2718                    rect.x()
2719                        + if resolved.hdr_capable {
2720                            hdr_value_to_slider(resolved.value) * rect.width()
2721                        } else {
2722                            resolved.value.clamp(0.0, 1.0) * rect.width()
2723                        }
2724                }
2725                _ => rect.x() + resolved.alpha * rect.width(),
2726            };
2727            paint_marker(
2728                ctx,
2729                Point::new(marker_x, rect.y() + rect.height() * 0.5),
2730                palette.border_focus,
2731                &theme,
2732            );
2733        }
2734
2735        let rgb = current.to_array();
2736        let channel_labels = ["R", "G", "B"];
2737        for (index, label) in channel_labels.into_iter().enumerate() {
2738            let rect = self.rgb_row_rect(ctx.bounds(), index);
2739            paint_rgb_channel_bar(
2740                ctx,
2741                rect,
2742                current,
2743                index,
2744                resolved.max_channel_value,
2745                &theme,
2746            );
2747            paint_labeled_row_text(
2748                ctx,
2749                rect,
2750                label,
2751                &format!("{:.3}", rgb[index]),
2752                &theme,
2753                palette.placeholder,
2754            );
2755            let marker_x =
2756                rect.x() + (rgb[index] / resolved.max_channel_value).clamp(0.0, 1.0) * rect.width();
2757            paint_marker(
2758                ctx,
2759                Point::new(marker_x, rect.y() + rect.height() * 0.5),
2760                palette.border_focus,
2761                &theme,
2762            );
2763        }
2764
2765        if resolved.hdr_capable && is_hdr_color(current) {
2766            paint_disabled_field(
2767                ctx,
2768                self.hex_rect(ctx.bounds()),
2769                &theme,
2770                "HDR hex unavailable",
2771            );
2772        } else {
2773            paint_hex_field(
2774                ctx,
2775                self.hex_rect(ctx.bounds()),
2776                &theme,
2777                &format_color(current),
2778            );
2779        }
2780
2781        if self.encoding_dropdown_open {
2782            paint_encoding_menu(
2783                ctx,
2784                self.encoding_menu_rect(ctx.bounds()),
2785                &theme,
2786                resolved.editing_space,
2787                self.encoding_menu_row_height(),
2788            );
2789        }
2790    }
2791
2792    fn semantics(&self, ctx: &mut SemanticsCtx) {
2793        let resolved = self.resolved_state();
2794        let current = resolved.color;
2795        let mut node =
2796            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ColorPicker, ctx.bounds());
2797        node.name = Some(self.name.clone());
2798        node.description = Some(format!(
2799            "{} editing space; {} range available",
2800            editing_space_label(resolved.editing_space),
2801            if resolved.hdr_capable { "HDR" } else { "SDR" }
2802        ));
2803        node.state.focused = ctx.is_focused();
2804        node.value = Some(SemanticsValue::Text(
2805            self.color_semantics_text(current, resolved.hdr_capable),
2806        ));
2807        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2808        ctx.push(node);
2809        self.push_component_semantics(ctx, resolved);
2810    }
2811
2812    fn accepts_focus(&self) -> bool {
2813        true
2814    }
2815
2816    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2817        let theme = self.resolved_theme();
2818        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2819        ctx.request_paint();
2820        ctx.request_semantics();
2821    }
2822}
2823
2824fn paint_picker_header(
2825    ctx: &mut PaintCtx,
2826    current_rect: Rect,
2827    previous_rect: Rect,
2828    theme: &DefaultTheme,
2829    previous: Color,
2830    current: Color,
2831) {
2832    let palette = theme.palette;
2833    let metrics = theme.metrics;
2834    let radius = metrics.indicator_corner_radius;
2835    draw_checkerboard(ctx, current_rect, metrics.color_swatch_checker_size, theme);
2836    draw_checkerboard(ctx, previous_rect, metrics.color_swatch_checker_size, theme);
2837    ctx.fill(rounded_rect_path(current_rect, radius), current);
2838    ctx.fill(rounded_rect_path(previous_rect, radius), previous);
2839    ctx.stroke(
2840        rounded_rect_path(current_rect, radius),
2841        palette.border_focus,
2842        StrokeStyle::new(metrics.border_width.max(1.0)),
2843    );
2844    ctx.stroke(
2845        rounded_rect_path(previous_rect, radius),
2846        palette.border,
2847        StrokeStyle::new(metrics.border_width.max(1.0)),
2848    );
2849}
2850
2851fn paint_color_wheel(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
2852    let center = Point::new(
2853        rect.x() + rect.width() * 0.5,
2854        rect.y() + rect.height() * 0.5,
2855    );
2856    let outer = rect.width().min(rect.height()) * 0.5;
2857    let inner = outer * 0.55;
2858    ctx.draw_shader_rect(rect, WidgetShader::ColorWheel);
2859    ctx.stroke(
2860        Path::circle(center, outer - 1.0),
2861        theme.surfaces.color_picker_chrome_border,
2862        StrokeStyle::new(1.0),
2863    );
2864    ctx.stroke(
2865        Path::circle(center, inner),
2866        theme.surfaces.color_picker_chrome_border,
2867        StrokeStyle::new(1.0),
2868    );
2869}
2870
2871fn paint_wheel_marker(ctx: &mut PaintCtx, rect: Rect, hue: f32, theme: &DefaultTheme) {
2872    let center = Point::new(
2873        rect.x() + rect.width() * 0.5,
2874        rect.y() + rect.height() * 0.5,
2875    );
2876    let outer = rect.width().min(rect.height()) * 0.5;
2877    let inner = outer * 0.55;
2878    let radius = (outer + inner) * 0.5;
2879    let angle = hue * std::f32::consts::TAU;
2880    let point = Point::new(
2881        center.x + angle.cos() * radius,
2882        center.y + angle.sin() * radius,
2883    );
2884    paint_marker(ctx, point, theme.surfaces.color_picker_marker_dark, theme);
2885}
2886
2887fn paint_saturation_value_plane(
2888    ctx: &mut PaintCtx,
2889    rect: Rect,
2890    space: ColorSpace,
2891    hue: f32,
2892    max_value: f32,
2893    theme: &DefaultTheme,
2894) {
2895    ctx.draw_shader_rect(
2896        rect,
2897        WidgetShader::ColorPickerSaturationValuePlane {
2898            color_space: space,
2899            hue,
2900            max_value,
2901        },
2902    );
2903    ctx.stroke_rect(
2904        rect,
2905        theme.surfaces.color_picker_plane_border,
2906        StrokeStyle::new(1.0),
2907    );
2908    let sdr_marker = Rect::new(
2909        rect.x(),
2910        rect.y()
2911            + rect.height()
2912                * (1.0
2913                    - if max_value <= 1.0001 {
2914                        1.0
2915                    } else {
2916                        hdr_value_to_slider(1.0)
2917                    }),
2918        rect.width(),
2919        1.0,
2920    );
2921    ctx.fill_rect(sdr_marker, theme.surfaces.color_picker_sdr_marker);
2922}
2923
2924fn paint_hue_bar(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
2925    ctx.draw_shader_rect(rect, WidgetShader::ColorPickerHueBar);
2926    paint_bar_border(ctx, rect, theme);
2927}
2928
2929fn paint_saturation_bar(
2930    ctx: &mut PaintCtx,
2931    rect: Rect,
2932    space: ColorSpace,
2933    hue: f32,
2934    value: f32,
2935    theme: &DefaultTheme,
2936) {
2937    ctx.draw_shader_rect(
2938        rect,
2939        WidgetShader::ColorPickerSaturationBar {
2940            color_space: space,
2941            hue,
2942            value,
2943        },
2944    );
2945    paint_bar_border(ctx, rect, theme);
2946}
2947
2948fn paint_bar_border(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme) {
2949    ctx.stroke_rect(
2950        rect,
2951        theme.surfaces.color_picker_bar_border,
2952        StrokeStyle::new(1.0),
2953    );
2954}
2955
2956fn paint_value_bar(
2957    ctx: &mut PaintCtx,
2958    rect: Rect,
2959    space: ColorSpace,
2960    hue: f32,
2961    saturation: f32,
2962    hdr_capable: bool,
2963    theme: &DefaultTheme,
2964) {
2965    ctx.draw_shader_rect(
2966        rect,
2967        WidgetShader::ColorPickerValueBar {
2968            color_space: space,
2969            hue,
2970            saturation,
2971            max_value: if hdr_capable {
2972                ColorPicker::MAX_HDR_VALUE
2973            } else {
2974                1.0
2975            },
2976        },
2977    );
2978    paint_bar_border(ctx, rect, theme);
2979    if hdr_capable {
2980        let divider_x = rect.x() + rect.width() * 0.5;
2981        ctx.fill_rect(
2982            Rect::new(divider_x, rect.y(), 1.0, rect.height()),
2983            theme.surfaces.color_picker_hdr_divider,
2984        );
2985    }
2986}
2987
2988fn paint_alpha_bar(ctx: &mut PaintCtx, rect: Rect, color: Color, theme: &DefaultTheme) {
2989    ctx.draw_shader_rect(rect, WidgetShader::ColorPickerAlphaBar { color });
2990    paint_bar_border(ctx, rect, theme);
2991}
2992
2993fn paint_rgb_channel_bar(
2994    ctx: &mut PaintCtx,
2995    rect: Rect,
2996    current: Color,
2997    channel_index: usize,
2998    max_value: f32,
2999    theme: &DefaultTheme,
3000) {
3001    ctx.draw_shader_rect(
3002        rect,
3003        WidgetShader::ColorPickerRgbChannelBar {
3004            color: current,
3005            channel: channel_index as u32,
3006            max_value,
3007        },
3008    );
3009    paint_bar_border(ctx, rect, theme);
3010}
3011
3012fn paint_labeled_row_text(
3013    ctx: &mut PaintCtx,
3014    rect: Rect,
3015    label: &str,
3016    value_text: &str,
3017    theme: &DefaultTheme,
3018    value_color: Color,
3019) {
3020    let text = theme.text.xs;
3021    let paint_line_height = text.line_height.min(rect.height()).max(1.0);
3022    let label_width = (theme.metrics.icon_size + theme.spacing * 2.0).max(20.0);
3023    let value_width = (rect.width() * 0.36).clamp(56.0, 96.0);
3024    let label_style = text_token_style(theme, text, theme.palette.accent_text);
3025    let value_style = numeric_text_style(text_token_style(theme, text, value_color));
3026    let label_slot = Rect::new(
3027        rect.x() + theme.spacing * 1.5,
3028        rect.y(),
3029        label_width,
3030        rect.height(),
3031    );
3032    let value_slot = Rect::new(
3033        rect.max_x() - value_width - theme.spacing,
3034        rect.y(),
3035        value_width,
3036        rect.height(),
3037    );
3038    ctx.push_clip_rect(label_slot);
3039    paint_aligned_text(ctx, label_slot, label, &label_style, paint_line_height, 0.0);
3040    ctx.pop_clip();
3041    ctx.push_clip_rect(value_slot);
3042    paint_aligned_text(
3043        ctx,
3044        value_slot,
3045        value_text,
3046        &value_style,
3047        paint_line_height,
3048        1.0,
3049    );
3050    ctx.pop_clip();
3051}
3052
3053fn paint_dropdown(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, label: &str) {
3054    let metrics = theme.metrics;
3055    let radius = metrics.corner_radius;
3056    let text = theme.text.xs;
3057    let paint_line_height = text.line_height.min(rect.height()).max(1.0);
3058    let padding = metrics.text_input_padding;
3059    let style = text_token_style(theme, text, theme.palette.text);
3060    let text_slot = Rect::new(
3061        rect.x() + padding.left.max(theme.spacing * 2.0),
3062        rect.y(),
3063        rect.width() - padding.left.max(theme.spacing * 2.0) - metrics.icon_size - theme.spacing,
3064        rect.height(),
3065    );
3066    ctx.fill(rounded_rect_path(rect, radius), theme.palette.control);
3067    ctx.stroke(
3068        rounded_rect_path(rect, radius),
3069        theme.palette.border_focus,
3070        StrokeStyle::new(metrics.border_width.max(1.0)),
3071    );
3072    ctx.push_clip_rect(text_slot);
3073    paint_aligned_text(ctx, text_slot, label, &style, paint_line_height, 0.0);
3074    ctx.pop_clip();
3075    ctx.stroke(
3076        dropdown_chevron_path(rect),
3077        theme.palette.placeholder,
3078        StrokeStyle::new(1.4),
3079    );
3080}
3081
3082fn paint_encoding_menu(
3083    ctx: &mut PaintCtx,
3084    rect: Rect,
3085    theme: &DefaultTheme,
3086    selected: ColorSpace,
3087    row_height: f32,
3088) {
3089    let metrics = theme.metrics;
3090    let radius = metrics.corner_radius;
3091    let text = theme.text.xs;
3092    let paint_line_height = text.line_height.min(row_height).max(1.0);
3093    ctx.fill(
3094        rounded_rect_path(rect, radius),
3095        theme.palette.surface_raised,
3096    );
3097    ctx.stroke(
3098        rounded_rect_path(rect, radius),
3099        theme.palette.border_focus,
3100        StrokeStyle::new(metrics.border_width.max(1.0)),
3101    );
3102
3103    for (index, space) in ColorPicker::ENCODING_OPTIONS.iter().copied().enumerate() {
3104        let row = Rect::new(
3105            rect.x(),
3106            rect.y() + index as f32 * row_height,
3107            rect.width(),
3108            row_height,
3109        );
3110        if space == selected {
3111            let selected_rect = inset_rect(row, metrics.menu_item_padding);
3112            ctx.fill(
3113                rounded_rect_path(
3114                    selected_rect,
3115                    (radius - metrics.menu_item_padding.top).max(0.0),
3116                ),
3117                mix_color(
3118                    theme.palette.control,
3119                    theme.palette.accent,
3120                    theme.interaction.selected_blend,
3121                ),
3122            );
3123            ctx.fill_rect(
3124                Rect::new(
3125                    selected_rect.x(),
3126                    selected_rect.y() + theme.spacing,
3127                    theme.interaction.active_indicator_thickness,
3128                    (selected_rect.height() - theme.spacing * 2.0).max(0.0),
3129                ),
3130                theme.palette.border_focus,
3131            );
3132        }
3133        let label = editing_space_label(space);
3134        let style = text_token_style(
3135            theme,
3136            text,
3137            if space == selected {
3138                theme.palette.accent_text
3139            } else {
3140                theme.palette.text
3141            },
3142        );
3143        let text_slot = Rect::new(
3144            row.x() + metrics.menu_item_padding.left + theme.spacing * 1.5,
3145            row.y(),
3146            row.width()
3147                - metrics.menu_item_padding.left
3148                - metrics.menu_item_padding.right
3149                - theme.spacing * 2.0,
3150            row.height(),
3151        );
3152        ctx.push_clip_rect(text_slot);
3153        paint_aligned_text(ctx, text_slot, label, &style, paint_line_height, 0.0);
3154        ctx.pop_clip();
3155    }
3156}
3157
3158fn dropdown_chevron_path(rect: Rect) -> Path {
3159    let center = Point::new(rect.max_x() - 14.0, rect.y() + rect.height() * 0.5);
3160    let half_width = 4.0;
3161    let half_height = 2.5;
3162    let mut path = PathBuilder::new();
3163    path.move_to(Point::new(center.x - half_width, center.y - half_height));
3164    path.line_to(Point::new(center.x, center.y + half_height));
3165    path.line_to(Point::new(center.x + half_width, center.y - half_height));
3166    path.build()
3167}
3168
3169fn paint_hex_field(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, value: &str) {
3170    let metrics = theme.metrics;
3171    let text = theme.text.xs;
3172    let paint_line_height = text.line_height.min(rect.height()).max(1.0);
3173    let padding = metrics.text_input_padding;
3174    let style = text_token_style(theme, text, theme.palette.text);
3175    let text_slot = Rect::new(
3176        rect.x() + padding.left.max(theme.spacing * 2.0),
3177        rect.y(),
3178        rect.width() - (padding.left + padding.right).max(theme.spacing * 4.0),
3179        rect.height(),
3180    );
3181    ctx.fill(
3182        rounded_rect_path(rect, metrics.corner_radius),
3183        theme.palette.control,
3184    );
3185    ctx.stroke(
3186        rounded_rect_path(rect, metrics.corner_radius),
3187        theme.palette.border,
3188        StrokeStyle::new(metrics.border_width.max(1.0)),
3189    );
3190    ctx.push_clip_rect(text_slot);
3191    paint_aligned_text(ctx, text_slot, value, &style, paint_line_height, 0.0);
3192    ctx.pop_clip();
3193}
3194
3195fn paint_disabled_field(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, value: &str) {
3196    let metrics = theme.metrics;
3197    let text = theme.text.xs;
3198    let paint_line_height = text.line_height.min(rect.height()).max(1.0);
3199    let padding = metrics.text_input_padding;
3200    let style = text_token_style(theme, text, theme.palette.placeholder);
3201    let text_slot = Rect::new(
3202        rect.x() + padding.left.max(theme.spacing * 2.0),
3203        rect.y(),
3204        rect.width() - (padding.left + padding.right).max(theme.spacing * 4.0),
3205        rect.height(),
3206    );
3207    ctx.fill(
3208        rounded_rect_path(rect, metrics.corner_radius),
3209        mix_color(theme.palette.control, theme.palette.surface, 0.5)
3210            .with_alpha(theme.interaction.disabled_opacity),
3211    );
3212    ctx.stroke(
3213        rounded_rect_path(rect, metrics.corner_radius),
3214        theme.palette.border,
3215        StrokeStyle::new(metrics.border_width.max(1.0)),
3216    );
3217    ctx.push_clip_rect(text_slot);
3218    paint_aligned_text(ctx, text_slot, value, &style, paint_line_height, 0.0);
3219    ctx.pop_clip();
3220}
3221
3222fn point_in_wheel_ring(rect: Rect, position: Point) -> bool {
3223    let center = Point::new(
3224        rect.x() + rect.width() * 0.5,
3225        rect.y() + rect.height() * 0.5,
3226    );
3227    let dx = position.x - center.x;
3228    let dy = position.y - center.y;
3229    let distance = (dx * dx + dy * dy).sqrt();
3230    let outer = rect.width().min(rect.height()) * 0.5;
3231    let inner = outer * 0.55;
3232    distance >= inner && distance <= outer
3233}
3234
3235fn editing_space_label(space: ColorSpace) -> &'static str {
3236    match space {
3237        ColorSpace::Srgb => "sRGB",
3238        ColorSpace::LinearSrgb => "BT709 Linear",
3239        ColorSpace::DisplayP3 => "Display P3",
3240        ColorSpace::LinearDisplayP3 => "Display P3 Linear",
3241    }
3242}
3243
3244fn hdr_value_to_slider(value: f32) -> f32 {
3245    let value = value.clamp(0.0, ColorPicker::MAX_HDR_VALUE);
3246    if value <= 1.0 {
3247        value * 0.5
3248    } else {
3249        0.5 + (value.ln() / ColorPicker::MAX_HDR_VALUE.ln()) * 0.5
3250    }
3251}
3252
3253fn hdr_slider_to_value(t: f32) -> f32 {
3254    let t = t.clamp(0.0, 1.0);
3255    if t <= 0.5 {
3256        t / 0.5
3257    } else {
3258        ColorPicker::MAX_HDR_VALUE.powf((t - 0.5) / 0.5)
3259    }
3260}
3261
3262fn is_hdr_color(color: Color) -> bool {
3263    color.red > 1.0 || color.green > 1.0 || color.blue > 1.0
3264}
3265
3266fn mix_color(from: Color, to: Color, amount: f32) -> Color {
3267    crate::animation::Interpolate::interpolate(from, to, amount)
3268}
3269
3270type AnimatedScalar = MotionScalar;
3271
3272fn set_animation_target(
3273    animation: &mut AnimatedScalar,
3274    target: f32,
3275    duration: f64,
3276    easing: crate::Easing,
3277    ctx: &mut EventCtx,
3278) -> bool {
3279    animation.set_target_event(target, duration, easing, ctx)
3280}
3281
3282fn set_hover_animation_target(
3283    animation: &mut AnimatedScalar,
3284    target: f32,
3285    theme: &DefaultTheme,
3286    ctx: &mut EventCtx,
3287) -> bool {
3288    set_animation_target(
3289        animation,
3290        target,
3291        theme.motion.hover_duration(),
3292        theme.motion.hover_easing(),
3293        ctx,
3294    )
3295}
3296
3297fn set_press_animation_target(
3298    animation: &mut AnimatedScalar,
3299    target: f32,
3300    theme: &DefaultTheme,
3301    ctx: &mut EventCtx,
3302) -> bool {
3303    set_animation_target(
3304        animation,
3305        target,
3306        theme.motion.press_duration(),
3307        theme.motion.press_easing(),
3308        ctx,
3309    )
3310}
3311
3312fn set_focus_animation_target(
3313    animation: &mut AnimatedScalar,
3314    target: f32,
3315    theme: &DefaultTheme,
3316    ctx: &mut EventCtx,
3317) -> bool {
3318    set_animation_target(
3319        animation,
3320        target,
3321        theme.motion.focus_duration(),
3322        theme.motion.focus_easing(),
3323        ctx,
3324    )
3325}
3326
3327fn advance_scalar(animation: &mut AnimatedScalar, time: f64) -> (bool, bool) {
3328    let previous = animation.value;
3329    let active = animation.advance(time);
3330    (animation.changed_since(previous), active)
3331}
3332
3333fn fit_rect(bounds: Rect, source: Size, fit: ImageFit) -> Rect {
3334    if bounds.is_empty() || source.is_empty() {
3335        return bounds;
3336    }
3337
3338    let scale_x = bounds.width() / source.width.max(1.0);
3339    let scale_y = bounds.height() / source.height.max(1.0);
3340    let scale = match fit {
3341        ImageFit::Fill => None,
3342        ImageFit::Contain => Some(scale_x.min(scale_y)),
3343        ImageFit::Cover => Some(scale_x.max(scale_y)),
3344        ImageFit::None => Some(1.0),
3345    };
3346
3347    let size = if let Some(scale) = scale {
3348        Size::new(source.width * scale, source.height * scale)
3349    } else {
3350        bounds.size
3351    };
3352    Rect::new(
3353        bounds.x() + ((bounds.width() - size.width) * 0.5),
3354        bounds.y() + ((bounds.height() - size.height) * 0.5),
3355        size.width,
3356        size.height,
3357    )
3358}
3359
3360fn paint_marker(ctx: &mut PaintCtx, center: Point, color: Color, theme: &DefaultTheme) {
3361    ctx.stroke(
3362        Path::circle(center, 6.5),
3363        theme.surfaces.color_picker_marker_outer,
3364        StrokeStyle::new(2.0),
3365    );
3366    ctx.stroke(Path::circle(center, 5.0), color, StrokeStyle::new(1.5));
3367}
3368
3369fn draw_surface(ctx: &mut PaintCtx, rect: Rect, theme: &DefaultTheme, focus_progress: f32) {
3370    let focus_progress = focus_progress.clamp(0.0, 1.0);
3371    ctx.fill(
3372        rounded_rect_path(rect, theme.metrics.corner_radius),
3373        theme.palette.surface,
3374    );
3375    ctx.stroke(
3376        rounded_rect_path(rect, theme.metrics.corner_radius),
3377        mix_color(
3378            theme.palette.border,
3379            theme.palette.border_focus,
3380            focus_progress,
3381        ),
3382        StrokeStyle::new(theme.metrics.border_width.max(1.0)),
3383    );
3384    if focus_progress > AnimatedScalar::EPSILON {
3385        let outset = theme.metrics.focus_ring_outset;
3386        ctx.stroke(
3387            rounded_rect_path(
3388                rect.inflate(outset, outset),
3389                theme.metrics.corner_radius + outset,
3390            ),
3391            theme
3392                .palette
3393                .focus_ring
3394                .with_alpha(theme.palette.focus_ring.alpha * focus_progress),
3395            StrokeStyle::new(theme.metrics.focus_ring_width.max(1.0)),
3396        );
3397    }
3398}
3399
3400fn draw_checkerboard(ctx: &mut PaintCtx, rect: Rect, cell_size: f32, theme: &DefaultTheme) {
3401    let light = theme.surfaces.checkerboard_light;
3402    let dark = theme.surfaces.checkerboard_dark;
3403    let cell_size = cell_size.max(2.0);
3404    let cols = (rect.width() / cell_size).ceil() as usize;
3405    let rows = (rect.height() / cell_size).ceil() as usize;
3406    ctx.push_clip_rect(rect);
3407    for row in 0..rows {
3408        for col in 0..cols {
3409            let cell = Rect::new(
3410                rect.x() + col as f32 * cell_size,
3411                rect.y() + row as f32 * cell_size,
3412                cell_size,
3413                cell_size,
3414            );
3415            ctx.fill_rect(cell, if (row + col) % 2 == 0 { light } else { dark });
3416        }
3417    }
3418    ctx.pop_clip();
3419}
3420
3421fn draw_rounded_checkerboard(
3422    ctx: &mut PaintCtx,
3423    rect: Rect,
3424    radius: f32,
3425    cell_size: f32,
3426    theme: &DefaultTheme,
3427) {
3428    ctx.push_clip(rounded_rect_path(rect, radius));
3429    draw_checkerboard(ctx, rect, cell_size, theme);
3430    ctx.pop_clip();
3431}
3432
3433fn format_color(color: Color) -> String {
3434    format!(
3435        "#{:02X}{:02X}{:02X}{:02X}",
3436        (color.red.clamp(0.0, 1.0) * 255.0).round() as u8,
3437        (color.green.clamp(0.0, 1.0) * 255.0).round() as u8,
3438        (color.blue.clamp(0.0, 1.0) * 255.0).round() as u8,
3439        (color.alpha.clamp(0.0, 1.0) * 255.0).round() as u8,
3440    )
3441}
3442
3443fn color_space_hdr_capable(space: ColorSpace) -> bool {
3444    space.is_linear() || matches!(space, ColorSpace::DisplayP3)
3445}
3446
3447fn colors_close(left: Color, right: Color) -> bool {
3448    left.space == right.space
3449        && (left.red - right.red).abs() < 0.0001
3450        && (left.green - right.green).abs() < 0.0001
3451        && (left.blue - right.blue).abs() < 0.0001
3452        && (left.alpha - right.alpha).abs() < 0.0001
3453}
3454
3455fn contrast_color(color: Color, theme: &DefaultTheme) -> Color {
3456    if perceived_luminance(color) > 0.55 {
3457        theme.surfaces.color_picker_marker_dark
3458    } else {
3459        theme.surfaces.color_picker_marker_light
3460    }
3461}
3462
3463fn perceived_luminance(color: Color) -> f32 {
3464    (0.299 * color.red) + (0.587 * color.green) + (0.114 * color.blue)
3465}
3466
3467fn hsv_to_color(space: ColorSpace, hue: f32, saturation: f32, value: f32, alpha: f32) -> Color {
3468    let hue = hue.rem_euclid(1.0) * 6.0;
3469    let sector = hue.floor();
3470    let fraction = hue - sector;
3471    let p = value * (1.0 - saturation);
3472    let q = value * (1.0 - fraction * saturation);
3473    let t = value * (1.0 - (1.0 - fraction) * saturation);
3474    let (red, green, blue) = match sector as i32 {
3475        0 => (value, t, p),
3476        1 => (q, value, p),
3477        2 => (p, value, t),
3478        3 => (p, q, value),
3479        4 => (t, p, value),
3480        _ => (value, p, q),
3481    };
3482    Color::new(space, red, green, blue, alpha)
3483}
3484
3485#[cfg(test)]
3486fn hsv_to_rgb(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color {
3487    hsv_to_color(ColorSpace::Srgb, hue, saturation, value, alpha)
3488}
3489
3490fn rgb_to_hsv(color: Color) -> (f32, f32, f32) {
3491    let max = color.red.max(color.green).max(color.blue);
3492    let min = color.red.min(color.green).min(color.blue);
3493    let delta = max - min;
3494    let hue = if delta <= f32::EPSILON {
3495        0.0
3496    } else if (max - color.red).abs() <= f32::EPSILON {
3497        (((color.green - color.blue) / delta).rem_euclid(6.0)) / 6.0
3498    } else if (max - color.green).abs() <= f32::EPSILON {
3499        (((color.blue - color.red) / delta) + 2.0) / 6.0
3500    } else {
3501        (((color.red - color.green) / delta) + 4.0) / 6.0
3502    };
3503    let saturation = if max <= f32::EPSILON {
3504        0.0
3505    } else {
3506        delta / max
3507    };
3508    (hue, saturation, max)
3509}
3510
3511fn rounded_rect_path(rect: Rect, radius: f32) -> Path {
3512    let mut builder = PathBuilder::new();
3513    builder.push_rounded_rect(rect, radius);
3514    builder.build()
3515}
3516
3517fn inset_rect(rect: Rect, padding: Insets) -> Rect {
3518    Rect::new(
3519        rect.x() + padding.left,
3520        rect.y() + padding.top,
3521        (rect.width() - padding.left - padding.right).max(0.0),
3522        (rect.height() - padding.top - padding.bottom).max(0.0),
3523    )
3524}
3525
3526fn numeric_text_style(mut style: TextStyle) -> TextStyle {
3527    style.features.enable(FontFeature::TABULAR_FIGURES);
3528    style
3529}
3530
3531fn text_token_style(theme: &DefaultTheme, token: ThemeTextToken, color: Color) -> TextStyle {
3532    TextStyle {
3533        font_size: token.size.max(1.0),
3534        line_height: token.line_height.max(1.0),
3535        color,
3536        ..theme.body_text_style()
3537    }
3538}
3539
3540#[cfg(test)]
3541mod tests {
3542    use std::{cell::RefCell, collections::BTreeSet, rc::Rc};
3543
3544    use super::{
3545        ActiveChannel, BrushPreview, BrushPreviewShape, BrushPreviewSpec, ColorPalette,
3546        ColorPaletteSwatch, ColorPicker, ColorPickerSemanticPart, ColorSwatch, Image, SignalMeter,
3547        color_picker_child_semantics_id, format_color, hsv_to_rgb, rgb_to_hsv,
3548        signal_meter_bar_layout,
3549    };
3550    use crate::{DefaultTheme, SemanticTone, ThemeTextToken};
3551    use sui_core::{
3552        Color, ColorSpace, Event, ImageHandle, Point, PointerButton, PointerButtons, PointerEvent,
3553        PointerEventKind, Rect, Result, SemanticsAction, SemanticsRole, SemanticsValue, Size,
3554        Vector, WidgetId,
3555    };
3556    use sui_layout::Padding as Insets;
3557    use sui_runtime::{Application, Runtime, Widget, WindowBuilder};
3558    use sui_scene::{Brush, RegisteredImage, SceneCommand};
3559    use sui_text::{FontFeature, FontRegistry, TextSystem};
3560
3561    fn build_runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
3562    where
3563        W: Widget + 'static,
3564    {
3565        let runtime = Application::new()
3566            .window(WindowBuilder::new().title("Media widgets").root(root))
3567            .build()
3568            .unwrap();
3569        let window_id = runtime.window_ids()[0];
3570        (runtime, window_id)
3571    }
3572
3573    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
3574        let mut buttons = PointerButtons::NONE;
3575        if pressed {
3576            buttons.insert(PointerButton::Primary);
3577        }
3578
3579        Event::Pointer(PointerEvent {
3580            pointer_id: 1,
3581            kind,
3582            position,
3583            delta: Vector::ZERO,
3584            scroll_delta: None,
3585            button: Some(PointerButton::Primary),
3586            buttons,
3587            modifiers: sui_core::Modifiers::NONE,
3588            pointer_kind: sui_core::PointerKind::Mouse,
3589            is_primary: true,
3590        })
3591    }
3592
3593    fn handle_ready_events(runtime: &mut Runtime) -> Result<usize> {
3594        let ready = runtime.drain_ready_events();
3595        let count = ready.len();
3596        for (window_id, event) in ready {
3597            runtime.handle_event(window_id, event)?;
3598        }
3599        Ok(count)
3600    }
3601
3602    fn solid_fill_colors(output: &sui_runtime::RenderOutput) -> Vec<Color> {
3603        let mut colors = Vec::new();
3604        output.frame.scene.visit_commands(&mut |command| {
3605            if let SceneCommand::FillRect {
3606                brush: Brush::Solid(color),
3607                ..
3608            }
3609            | SceneCommand::FillPath {
3610                brush: Brush::Solid(color),
3611                ..
3612            } = command
3613            {
3614                colors.push(*color);
3615            }
3616        });
3617        colors
3618    }
3619
3620    fn solid_stroke_colors(output: &sui_runtime::RenderOutput) -> Vec<Color> {
3621        let mut colors = Vec::new();
3622        output.frame.scene.visit_commands(&mut |command| {
3623            if let SceneCommand::StrokeRect {
3624                brush: Brush::Solid(color),
3625                ..
3626            }
3627            | SceneCommand::StrokePath {
3628                brush: Brush::Solid(color),
3629                ..
3630            } = command
3631            {
3632                colors.push(*color);
3633            }
3634        });
3635        colors
3636    }
3637
3638    fn path_clip_bounds(output: &sui_runtime::RenderOutput) -> Vec<Rect> {
3639        output
3640            .frame
3641            .scene
3642            .commands()
3643            .iter()
3644            .filter_map(|command| match command {
3645                SceneCommand::PushClipPath { path } => Some(path.bounds()),
3646                _ => None,
3647            })
3648            .collect()
3649    }
3650
3651    fn rects_close(left: Rect, right: Rect) -> bool {
3652        (left.x() - right.x()).abs() < 0.001
3653            && (left.y() - right.y()).abs() < 0.001
3654            && (left.width() - right.width()).abs() < 0.001
3655            && (left.height() - right.height()).abs() < 0.001
3656    }
3657
3658    fn stroke_path_bounds_with_color_and_width(
3659        output: &sui_runtime::RenderOutput,
3660        color: Color,
3661        width: f32,
3662    ) -> Vec<Rect> {
3663        let mut bounds = Vec::new();
3664        output.frame.scene.visit_commands(&mut |command| {
3665            if let SceneCommand::StrokePath {
3666                path,
3667                brush: Brush::Solid(stroke_color),
3668                stroke,
3669            } = command
3670                && *stroke_color == color
3671                && (stroke.width - width).abs() < 0.01
3672            {
3673                bounds.push(path.bounds());
3674            }
3675        });
3676        bounds
3677    }
3678
3679    fn text_run_for(output: &sui_runtime::RenderOutput, text: &str) -> sui_text::TextRun {
3680        output
3681            .frame
3682            .scene
3683            .commands()
3684            .iter()
3685            .find_map(|command| match command {
3686                SceneCommand::DrawText(run) if run.text == text => Some(run.clone()),
3687                SceneCommand::DrawShapedText(run) => run
3688                    .resolve(output.frame.text_layout_registry.as_ref())
3689                    .filter(|layout| layout.text() == text)
3690                    .map(|layout| {
3691                        let mut style = layout.style().clone();
3692                        if let Some(color) = run.color_override {
3693                            style.color = color;
3694                        }
3695                        sui_text::TextRun {
3696                            rect: shaped_text_run_rect(run.origin, layout),
3697                            text: layout.text().to_string(),
3698                            style,
3699                        }
3700                    }),
3701                _ => None,
3702            })
3703            .expect("text draw command present")
3704    }
3705
3706    fn shaped_text_run_rect(origin: Point, layout: &sui_text::TextLayout) -> Rect {
3707        let measurement = layout.measurement();
3708        let bounds = measurement.bounds;
3709        let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
3710            bounds.width()
3711        } else {
3712            measurement.width
3713        };
3714        Rect::new(
3715            origin.x + bounds.x(),
3716            origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
3717            width,
3718            layout.style().line_height.max(measurement.height),
3719        )
3720    }
3721
3722    fn text_visual_center_for(output: &sui_runtime::RenderOutput, text: &str) -> f32 {
3723        output
3724            .frame
3725            .scene
3726            .commands()
3727            .iter()
3728            .find_map(|command| match command {
3729                SceneCommand::DrawText(run) if run.text == text => {
3730                    let layout = TextSystem::new()
3731                        .shape_text_run(run, &FontRegistry::new())
3732                        .expect("text run should shape");
3733                    let line = layout
3734                        .lines()
3735                        .first()
3736                        .expect("text run should contain one line");
3737                    Some(run.rect.y() + line.baseline + optical_visual_center(layout.measurement()))
3738                }
3739                SceneCommand::DrawShapedText(run) => {
3740                    let layout = run.resolve(output.frame.text_layout_registry.as_ref())?;
3741                    if layout.text() != text {
3742                        return None;
3743                    }
3744                    let line = layout
3745                        .lines()
3746                        .first()
3747                        .expect("shaped text should contain one line");
3748                    Some(run.origin.y + line.baseline + optical_visual_center(layout.measurement()))
3749                }
3750                _ => None,
3751            })
3752            .expect("text draw command present")
3753    }
3754
3755    fn rect_center(rect: Rect) -> Point {
3756        Point::new(
3757            rect.x() + rect.width() * 0.5,
3758            rect.y() + rect.height() * 0.5,
3759        )
3760    }
3761
3762    fn optical_visual_center(measurement: sui_text::TextMeasurement) -> f32 {
3763        let top = -measurement.cap_height.unwrap_or(measurement.ascent);
3764        let bottom = measurement.descent * 0.5;
3765        (top + bottom) * 0.5
3766    }
3767
3768    fn assert_text_run_uses_token(run: &sui_text::TextRun, token: ThemeTextToken) {
3769        assert_eq!(run.style.font_size, token.size);
3770        assert_eq!(run.style.line_height, token.line_height);
3771    }
3772
3773    #[test]
3774    fn hsv_round_trip_stays_close() {
3775        let color = Color::rgba(0.25, 0.65, 0.82, 0.75);
3776        let (hue, saturation, value) = rgb_to_hsv(color);
3777        let round_trip = hsv_to_rgb(hue, saturation, value, color.alpha);
3778
3779        assert!((round_trip.red - color.red).abs() < 0.02);
3780        assert!((round_trip.green - color.green).abs() < 0.02);
3781        assert!((round_trip.blue - color.blue).abs() < 0.02);
3782        assert!((round_trip.alpha - color.alpha).abs() < f32::EPSILON);
3783    }
3784
3785    #[test]
3786    fn image_uses_registered_image_size_and_semantics() -> Result<()> {
3787        let handle = ImageHandle::new(7);
3788        let mut application = Application::new();
3789        application.register_image(
3790            handle,
3791            RegisteredImage::from_rgba8(32, 16, vec![255; 32 * 16 * 4])?,
3792        )?;
3793        let mut runtime = application
3794            .window(
3795                WindowBuilder::new()
3796                    .title("Image")
3797                    .root(Image::new(handle).label("Preview")),
3798            )
3799            .build()?;
3800        let window_id = runtime.window_ids()[0];
3801
3802        let output = runtime.render(window_id)?;
3803        assert_eq!(output.frame.viewport, Size::new(32.0, 16.0));
3804        let image = output
3805            .semantics
3806            .iter()
3807            .find(|node| node.role == SemanticsRole::Image)
3808            .expect("image semantics present");
3809        assert_eq!(image.name.as_deref(), Some("Preview"));
3810        Ok(())
3811    }
3812
3813    #[test]
3814    fn signal_meter_paints_tone_bars_and_semantics() -> Result<()> {
3815        let theme = DefaultTheme::default();
3816        let tone = theme.semantic_tone_color(SemanticTone::Success);
3817        let (mut runtime, window_id) = build_runtime(
3818            SignalMeter::new("Audio input signal")
3819                .description("Microphone activity")
3820                .active(true)
3821                .tone(SemanticTone::Success)
3822                .bars(10)
3823                .size(Size::new(120.0, 18.0))
3824                .theme(theme),
3825        );
3826
3827        let output = runtime.render(window_id)?;
3828        let fills = solid_fill_colors(&output);
3829        assert!(
3830            fills.iter().filter(|color| **color == tone).count() >= 10,
3831            "active signal meter should paint tone-colored bars"
3832        );
3833        let meter = output
3834            .semantics
3835            .iter()
3836            .find(|node| {
3837                node.role == SemanticsRole::GenericContainer
3838                    && node.name.as_deref() == Some("Audio input signal")
3839            })
3840            .expect("signal meter semantics should be present");
3841        assert_eq!(meter.description.as_deref(), Some("Microphone activity"));
3842        assert_eq!(
3843            meter.value.as_ref(),
3844            Some(&SemanticsValue::Text("active".to_string()))
3845        );
3846        Ok(())
3847    }
3848
3849    #[test]
3850    fn signal_meter_level_lights_reached_bars_and_publishes_range() -> Result<()> {
3851        let theme = DefaultTheme::default();
3852        let tone = theme.semantic_tone_color(SemanticTone::Success);
3853        let (mut runtime, window_id) = build_runtime(
3854            SignalMeter::new("Microphone level")
3855                .description("Current microphone input level")
3856                .active(true)
3857                .level_when(|| 0.5)
3858                .tone(SemanticTone::Success)
3859                .bars(10)
3860                .size(Size::new(120.0, 18.0))
3861                .theme(theme),
3862        );
3863
3864        let output = runtime.render(window_id)?;
3865        let fills = solid_fill_colors(&output);
3866        assert_eq!(
3867            fills.iter().filter(|color| **color == tone).count(),
3868            5,
3869            "a half-level signal should light half of the meter bars"
3870        );
3871        let meter = output
3872            .semantics
3873            .iter()
3874            .find(|node| {
3875                node.role == SemanticsRole::ProgressBar
3876                    && node.name.as_deref() == Some("Microphone level")
3877            })
3878            .expect("signal meter semantics should be present");
3879        assert_eq!(
3880            meter.value.as_ref(),
3881            Some(&SemanticsValue::Range {
3882                value: 0.5,
3883                min: 0.0,
3884                max: 1.0,
3885            })
3886        );
3887        Ok(())
3888    }
3889
3890    #[test]
3891    fn signal_meter_level_sanitizes_to_the_normalized_range() {
3892        assert_eq!(
3893            SignalMeter::new("Low").level(-0.25).resolved_level(),
3894            Some(0.0)
3895        );
3896        assert_eq!(
3897            SignalMeter::new("High").level(1.25).resolved_level(),
3898            Some(1.0)
3899        );
3900        assert_eq!(
3901            SignalMeter::new("Invalid")
3902                .level(f32::INFINITY)
3903                .resolved_level(),
3904            Some(0.0)
3905        );
3906    }
3907
3908    #[test]
3909    fn signal_meter_bar_layout_stays_inside_narrow_bounds() {
3910        for width in [0.0_f32, 0.5, 5.0, 10.0, 27.0, 120.0] {
3911            let (bars, gap, bar_width) = signal_meter_bar_layout(width, 18, 3.0);
3912            let painted_width = bar_width * bars as f32 + gap * bars.saturating_sub(1) as f32;
3913            assert!(bars >= 1);
3914            assert!(bar_width >= 0.0);
3915            assert!(painted_width <= width.max(0.0) + f32::EPSILON * 8.0);
3916        }
3917        assert_eq!(signal_meter_bar_layout(10.0, 18, 3.0), (10, 0.0, 1.0));
3918    }
3919
3920    #[test]
3921    fn image_without_border_omits_frame_stroke() -> Result<()> {
3922        let handle = ImageHandle::new(8);
3923        let mut application = Application::new();
3924        application.register_image(
3925            handle,
3926            RegisteredImage::from_rgba8(32, 32, vec![255; 32 * 32 * 4])?,
3927        )?;
3928        let mut runtime = application
3929            .window(
3930                WindowBuilder::new()
3931                    .title("Image")
3932                    .root(Image::new(handle).without_border()),
3933            )
3934            .build()?;
3935        let window_id = runtime.window_ids()[0];
3936
3937        let output = runtime.render(window_id)?;
3938        let mut image_draws = 0;
3939        let mut frame_strokes = 0;
3940        output
3941            .frame
3942            .scene
3943            .visit_commands(&mut |command| match command {
3944                SceneCommand::DrawImage { source, .. } if source.image == handle => {
3945                    image_draws += 1;
3946                }
3947                SceneCommand::StrokeRect { .. } | SceneCommand::StrokePath { .. } => {
3948                    frame_strokes += 1;
3949                }
3950                _ => {}
3951            });
3952
3953        assert_eq!(image_draws, 1);
3954        assert_eq!(frame_strokes, 0);
3955        Ok(())
3956    }
3957
3958    #[test]
3959    fn image_corner_radius_clips_bitmap_with_rounded_path() -> Result<()> {
3960        let handle = ImageHandle::new(9);
3961        let mut application = Application::new();
3962        application.register_image(
3963            handle,
3964            RegisteredImage::from_rgba8(32, 16, vec![255; 32 * 16 * 4])?,
3965        )?;
3966        let mut runtime = application
3967            .window(
3968                WindowBuilder::new().title("Rounded image").root(
3969                    Image::new(handle)
3970                        .fit(super::ImageFit::Cover)
3971                        .corner_radius(12.0),
3972                ),
3973            )
3974            .build()?;
3975        let window_id = runtime.window_ids()[0];
3976
3977        let output = runtime.render(window_id)?;
3978        assert!(
3979            output
3980                .frame
3981                .scene
3982                .commands()
3983                .iter()
3984                .any(|command| matches!(command, SceneCommand::PushClipPath { .. })),
3985            "rounded images should clip bitmap pixels to the rounded frame"
3986        );
3987        Ok(())
3988    }
3989
3990    #[test]
3991    fn color_swatch_click_invokes_callback() -> Result<()> {
3992        let presses = Rc::new(RefCell::new(Vec::new()));
3993        let on_press = Rc::clone(&presses);
3994        let color = Color::rgba(0.2, 0.4, 0.8, 1.0);
3995        let (mut runtime, window_id) = build_runtime(
3996            ColorSwatch::new("Accent", color)
3997                .on_press(move |color| on_press.borrow_mut().push(color)),
3998        );
3999
4000        let _ = runtime.render(window_id)?;
4001        runtime.handle_event(
4002            window_id,
4003            primary_pointer(PointerEventKind::Down, Point::new(16.0, 16.0), true),
4004        )?;
4005        runtime.handle_event(
4006            window_id,
4007            primary_pointer(PointerEventKind::Up, Point::new(16.0, 16.0), false),
4008        )?;
4009
4010        assert_eq!(presses.borrow().as_slice(), &[color]);
4011
4012        let output = runtime.render(window_id)?;
4013        let swatch = output
4014            .semantics
4015            .iter()
4016            .find(|node| node.role == SemanticsRole::ColorSwatch)
4017            .expect("color swatch semantics present");
4018        assert_eq!(
4019            swatch.value,
4020            Some(SemanticsValue::Text("#3366CCFF".to_string()))
4021        );
4022        Ok(())
4023    }
4024
4025    #[test]
4026    fn color_swatch_checkerboards_follow_the_rounded_color_shape() -> Result<()> {
4027        let theme = DefaultTheme::dark();
4028        let translucent = Color::rgba(0.16, 0.52, 0.88, 0.55);
4029        let (mut runtime, window_id) =
4030            build_runtime(ColorSwatch::new("Translucent accent", translucent).theme(theme));
4031        let output = runtime.render(window_id)?;
4032        let swatch = output
4033            .semantics
4034            .iter()
4035            .find(|node| node.role == SemanticsRole::ColorSwatch)
4036            .expect("standalone color swatch semantics present");
4037        let expected_inner = super::inset_rect(
4038            swatch.bounds,
4039            Insets::all(theme.metrics.color_swatch_inner_inset),
4040        );
4041        let clips = path_clip_bounds(&output);
4042        assert!(
4043            clips.iter().any(|clip| rects_close(*clip, expected_inner)),
4044            "standalone swatch checkerboard should be clipped to its rounded inner color shape; expected {expected_inner:?}, clips={clips:?}"
4045        );
4046
4047        let (mut runtime, window_id) = build_runtime(
4048            ColorPalette::new("Dark palette")
4049                .theme(theme)
4050                .swatch(ColorPaletteSwatch::new("Selected accent", translucent))
4051                .selected(0),
4052        );
4053        let output = runtime.render(window_id)?;
4054        let selected = output
4055            .semantics
4056            .iter()
4057            .find(|node| {
4058                node.role == SemanticsRole::ColorSwatch
4059                    && node.name.as_deref() == Some("Selected accent")
4060            })
4061            .expect("selected palette swatch semantics present");
4062        let expected_inner = super::inset_rect(
4063            selected.bounds,
4064            Insets::all(theme.metrics.color_palette_selected_swatch_inset),
4065        );
4066        let clips = path_clip_bounds(&output);
4067        assert!(
4068            clips.iter().any(|clip| rects_close(*clip, expected_inner)),
4069            "selected palette checkerboard should be clipped to its rounded color shape; expected {expected_inner:?}, clips={clips:?}"
4070        );
4071        Ok(())
4072    }
4073
4074    #[test]
4075    fn color_swatch_hover_and_press_use_theme_motion() -> Result<()> {
4076        let theme = DefaultTheme::default();
4077        let hover_duration = theme.motion.hover_duration();
4078        let press_duration = theme.motion.press_duration();
4079        let expected_hover = theme.palette.control_hover;
4080        let expected_press = super::mix_color(
4081            expected_hover,
4082            theme.palette.control_active,
4083            theme.interaction.pressed_blend,
4084        );
4085        let (mut runtime, window_id) =
4086            build_runtime(ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0)).theme(theme));
4087
4088        let output = runtime.render(window_id)?;
4089        let swatch = output
4090            .semantics
4091            .iter()
4092            .find(|node| node.role == SemanticsRole::ColorSwatch)
4093            .expect("color swatch semantics present");
4094        let position = rect_center(swatch.bounds);
4095
4096        runtime.handle_event(
4097            window_id,
4098            primary_pointer(PointerEventKind::Move, position, false),
4099        )?;
4100        runtime.tick(hover_duration * 0.5);
4101        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4102        let mid_hover = runtime.render(window_id)?;
4103        assert!(
4104            !solid_fill_colors(&mid_hover).contains(&expected_hover),
4105            "swatch hover fill should not snap to the settled hover color"
4106        );
4107
4108        runtime.tick(hover_duration);
4109        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4110        let settled_hover = runtime.render(window_id)?;
4111        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
4112
4113        runtime.handle_event(
4114            window_id,
4115            primary_pointer(PointerEventKind::Down, position, true),
4116        )?;
4117        runtime.tick(hover_duration + press_duration * 0.5);
4118        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4119        let mid_press = runtime.render(window_id)?;
4120        assert!(
4121            !solid_fill_colors(&mid_press).contains(&expected_press),
4122            "swatch press fill should not snap to the settled pressed color"
4123        );
4124
4125        runtime.tick(hover_duration + press_duration);
4126        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4127        let settled_press = runtime.render(window_id)?;
4128        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
4129
4130        Ok(())
4131    }
4132
4133    #[test]
4134    fn color_swatch_read_only_color_when_syncs_external_value() -> Result<()> {
4135        let color = Rc::new(RefCell::new(Color::rgba(0.08, 0.22, 0.78, 1.0)));
4136        let color_reader = Rc::clone(&color);
4137        let (mut runtime, window_id) = build_runtime(
4138            ColorSwatch::new("Current brush color", *color.borrow())
4139                .color_when(move || *color_reader.borrow())
4140                .read_only(),
4141        );
4142
4143        let output = runtime.render(window_id)?;
4144        let swatch = output
4145            .semantics
4146            .iter()
4147            .find(|node| {
4148                node.role == SemanticsRole::ColorSwatch
4149                    && node.name.as_deref() == Some("Current brush color")
4150            })
4151            .expect("current color swatch semantics present");
4152        assert_eq!(
4153            swatch.value,
4154            Some(SemanticsValue::Text("#1438C7FF".to_string()))
4155        );
4156        assert!(swatch.actions.is_empty());
4157
4158        *color.borrow_mut() = Color::rgba(0.90, 0.32, 0.18, 1.0);
4159        runtime.handle_event(
4160            window_id,
4161            primary_pointer(PointerEventKind::Move, Point::new(8.0, 8.0), false),
4162        )?;
4163        let output = runtime.render(window_id)?;
4164        let swatch = output
4165            .semantics
4166            .iter()
4167            .find(|node| {
4168                node.role == SemanticsRole::ColorSwatch
4169                    && node.name.as_deref() == Some("Current brush color")
4170            })
4171            .expect("current color swatch semantics still present");
4172        assert_eq!(
4173            swatch.value,
4174            Some(SemanticsValue::Text("#E6522EFF".to_string()))
4175        );
4176        Ok(())
4177    }
4178
4179    #[test]
4180    fn color_palette_exposes_selected_swatch_semantics() -> Result<()> {
4181        let (mut runtime, window_id) = build_runtime(
4182            ColorPalette::new("Brush palette")
4183                .swatches([
4184                    ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
4185                    ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
4186                    ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
4187                ])
4188                .selected(1),
4189        );
4190        let output = runtime.render(window_id)?;
4191
4192        let palette = output
4193            .semantics
4194            .iter()
4195            .find(|node| {
4196                node.role == SemanticsRole::GenericContainer
4197                    && node.name.as_deref() == Some("Brush palette")
4198            })
4199            .expect("palette semantics present");
4200        assert_eq!(
4201            palette.value,
4202            Some(SemanticsValue::Text("Ocean #1438C7FF".to_string()))
4203        );
4204
4205        let selected = output
4206            .semantics
4207            .iter()
4208            .find(|node| {
4209                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Ocean")
4210            })
4211            .expect("selected swatch semantics present");
4212        assert!(selected.state.selected);
4213        assert_eq!(
4214            selected.value,
4215            Some(SemanticsValue::Text("#1438C7FF".to_string()))
4216        );
4217        Ok(())
4218    }
4219
4220    #[test]
4221    fn media_widget_defaults_follow_theme_density() -> Result<()> {
4222        let (mut compact_runtime, compact_window) = build_runtime(
4223            ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0))
4224                .theme(DefaultTheme::compact()),
4225        );
4226        let compact = compact_runtime.render(compact_window)?.frame.viewport;
4227
4228        let (mut touch_runtime, touch_window) = build_runtime(
4229            ColorSwatch::new("Accent", Color::rgba(0.2, 0.4, 0.8, 1.0))
4230                .theme(DefaultTheme::touch()),
4231        );
4232        let touch = touch_runtime.render(touch_window)?.frame.viewport;
4233
4234        assert_eq!(
4235            compact,
4236            Size::new(
4237                DefaultTheme::compact().metrics.color_swatch_width,
4238                DefaultTheme::compact().metrics.color_swatch_height,
4239            )
4240        );
4241        assert_eq!(
4242            touch,
4243            Size::new(
4244                DefaultTheme::touch().metrics.color_swatch_width,
4245                DefaultTheme::touch().metrics.color_swatch_height,
4246            )
4247        );
4248        assert!(touch.width > compact.width);
4249        assert!(touch.height > compact.height);
4250        Ok(())
4251    }
4252
4253    #[test]
4254    fn color_palette_defaults_and_overrides_are_density_aware() -> Result<()> {
4255        let swatches = [
4256            ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
4257            ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
4258        ];
4259        let (mut compact_runtime, compact_window) = build_runtime(
4260            ColorPalette::new("Brush palette")
4261                .theme(DefaultTheme::compact())
4262                .swatches(swatches.clone()),
4263        );
4264        let compact = compact_runtime.render(compact_window)?.frame.viewport;
4265
4266        let (mut touch_runtime, touch_window) = build_runtime(
4267            ColorPalette::new("Brush palette")
4268                .theme(DefaultTheme::touch())
4269                .swatches(swatches.clone()),
4270        );
4271        let touch = touch_runtime.render(touch_window)?.frame.viewport;
4272
4273        assert!(touch.width > compact.width);
4274        assert_eq!(
4275            compact.height,
4276            DefaultTheme::compact().metrics.color_palette_swatch_size
4277        );
4278
4279        let (mut override_runtime, override_window) = build_runtime(
4280            ColorPalette::new("Brush palette")
4281                .theme(DefaultTheme::touch())
4282                .swatches(swatches)
4283                .swatch_size(18.0)
4284                .gap(2.0),
4285        );
4286        let overridden = override_runtime.render(override_window)?.frame.viewport;
4287        assert_eq!(overridden, Size::new(38.0, 18.0));
4288        Ok(())
4289    }
4290
4291    #[test]
4292    fn color_palette_click_invokes_callback_and_selects_swatch() -> Result<()> {
4293        let changes = Rc::new(RefCell::new(Vec::new()));
4294        let changes_writer = Rc::clone(&changes);
4295        let (mut runtime, window_id) = build_runtime(
4296            ColorPalette::new("Brush palette")
4297                .swatches([
4298                    ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
4299                    ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
4300                    ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
4301                ])
4302                .selected(0)
4303                .on_change(move |index, name, color| {
4304                    changes_writer.borrow_mut().push((index, name, color));
4305                }),
4306        );
4307        let output = runtime.render(window_id)?;
4308        let mint = output
4309            .semantics
4310            .iter()
4311            .find(|node| {
4312                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Mint")
4313            })
4314            .expect("target swatch semantics present");
4315        let position = Point::new(
4316            mint.bounds.x() + mint.bounds.width() * 0.5,
4317            mint.bounds.y() + mint.bounds.height() * 0.5,
4318        );
4319
4320        runtime.handle_event(
4321            window_id,
4322            primary_pointer(PointerEventKind::Down, position, true),
4323        )?;
4324        runtime.handle_event(
4325            window_id,
4326            primary_pointer(PointerEventKind::Up, position, false),
4327        )?;
4328
4329        assert_eq!(
4330            changes.borrow().as_slice(),
4331            &[(2, "Mint".to_string(), Color::rgba(0.28, 0.78, 0.58, 1.0))]
4332        );
4333        let output = runtime.render(window_id)?;
4334        assert!(output.semantics.iter().any(|node| {
4335            node.role == SemanticsRole::ColorSwatch
4336                && node.name.as_deref() == Some("Mint")
4337                && node.state.selected
4338        }));
4339        Ok(())
4340    }
4341
4342    #[test]
4343    fn color_palette_hover_and_press_use_theme_motion() -> Result<()> {
4344        let theme = DefaultTheme::default();
4345        let hover_duration = theme.motion.hover_duration();
4346        let press_duration = theme.motion.press_duration();
4347        let expected_hover = super::mix_color(
4348            theme.palette.control,
4349            theme.palette.control_hover,
4350            theme.interaction.hover_blend,
4351        );
4352        let expected_press = super::mix_color(
4353            expected_hover,
4354            theme.palette.control_active,
4355            theme.interaction.pressed_blend,
4356        );
4357        let (mut runtime, window_id) =
4358            build_runtime(ColorPalette::new("Brush palette").theme(theme).swatches([
4359                ColorPaletteSwatch::new("Ink", Color::rgba(0.08, 0.10, 0.15, 1.0)),
4360                ColorPaletteSwatch::new("Ocean", Color::rgba(0.08, 0.22, 0.78, 1.0)),
4361                ColorPaletteSwatch::new("Mint", Color::rgba(0.28, 0.78, 0.58, 1.0)),
4362            ]));
4363        let output = runtime.render(window_id)?;
4364        let mint = output
4365            .semantics
4366            .iter()
4367            .find(|node| {
4368                node.role == SemanticsRole::ColorSwatch && node.name.as_deref() == Some("Mint")
4369            })
4370            .expect("target swatch semantics present");
4371        let position = rect_center(mint.bounds);
4372
4373        runtime.handle_event(
4374            window_id,
4375            primary_pointer(PointerEventKind::Move, position, false),
4376        )?;
4377        runtime.tick(hover_duration * 0.5);
4378        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4379        let mid_hover = runtime.render(window_id)?;
4380        assert!(
4381            !solid_fill_colors(&mid_hover).contains(&expected_hover),
4382            "palette swatch hover fill should not snap to the settled hover color"
4383        );
4384
4385        runtime.tick(hover_duration);
4386        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4387        let settled_hover = runtime.render(window_id)?;
4388        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
4389
4390        runtime.handle_event(
4391            window_id,
4392            primary_pointer(PointerEventKind::Down, position, true),
4393        )?;
4394        runtime.tick(hover_duration + press_duration * 0.5);
4395        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4396        let mid_press = runtime.render(window_id)?;
4397        assert!(
4398            !solid_fill_colors(&mid_press).contains(&expected_press),
4399            "palette swatch press fill should not snap to the settled pressed color"
4400        );
4401
4402        runtime.tick(hover_duration + press_duration);
4403        assert_eq!(handle_ready_events(&mut runtime)?, 1);
4404        let settled_press = runtime.render(window_id)?;
4405        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
4406
4407        Ok(())
4408    }
4409
4410    #[test]
4411    fn brush_preview_exposes_current_brush_semantics_and_paints_sample() -> Result<()> {
4412        let (mut runtime, window_id) = build_runtime(
4413            BrushPreview::new("Brush preview")
4414                .spec(BrushPreviewSpec::new(
4415                    Color::rgba(0.10, 0.30, 0.90, 1.0),
4416                    22.0,
4417                    0.75,
4418                    BrushPreviewShape::Square,
4419                ))
4420                .size(Size::new(220.0, 64.0)),
4421        );
4422
4423        let output = runtime.render(window_id)?;
4424        let preview = output
4425            .semantics
4426            .iter()
4427            .find(|node| {
4428                node.role == SemanticsRole::Image && node.name.as_deref() == Some("Brush preview")
4429            })
4430            .expect("brush preview semantics present");
4431        assert_eq!(
4432            preview.value,
4433            Some(SemanticsValue::Text(
4434                "Square brush, 22 px, 75% opacity".to_string(),
4435            ))
4436        );
4437
4438        let mut fill_count = 0;
4439        output.frame.scene.visit_commands(&mut |command| {
4440            if matches!(
4441                command,
4442                SceneCommand::FillRect { .. } | SceneCommand::FillPath { .. }
4443            ) {
4444                fill_count += 1;
4445            }
4446        });
4447        assert!(fill_count > 3);
4448
4449        let value_text = "Square brush, 22 px, 75% opacity";
4450        let text = text_run_for(&output, value_text);
4451        let layout = TextSystem::new()
4452            .shape_text_run(&text, &FontRegistry::new())
4453            .expect("brush preview value should shape");
4454        let line = layout
4455            .lines()
4456            .first()
4457            .expect("brush preview value should contain one line");
4458        let actual_visual_center =
4459            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
4460        let theme = DefaultTheme::default();
4461        let metrics = theme.metrics;
4462        let bounds = Rect::new(0.0, 0.0, 220.0, 64.0);
4463        let content = super::inset_rect(bounds, metrics.brush_preview_padding);
4464        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
4465        let sample = Rect::new(
4466            content.x() + swatch_width + metrics.brush_preview_swatch_gap,
4467            content.y(),
4468            (content.width() - swatch_width - metrics.brush_preview_swatch_gap).max(0.0),
4469            content.height(),
4470        );
4471        let text_slot = Rect::new(
4472            sample.x(),
4473            sample.max_y() - metrics.brush_preview_text_height,
4474            sample.width(),
4475            metrics.brush_preview_text_height,
4476        );
4477        let slot_center = text_slot.y() + (text_slot.height() * 0.5);
4478
4479        assert!((actual_visual_center - slot_center).abs() < 0.75);
4480        Ok(())
4481    }
4482
4483    #[test]
4484    fn brush_preview_value_preserves_tall_measurement_and_slot_centering() -> Result<()> {
4485        let mut theme = DefaultTheme::default();
4486        theme.metrics.brush_preview_text_font_size = 28.0;
4487        theme.metrics.brush_preview_text_line_height = 10.0;
4488        theme.metrics.brush_preview_text_height = 44.0;
4489        theme.metrics.brush_preview_min_width = 420.0;
4490        theme.metrics.brush_preview_min_height = 96.0;
4491        let metrics = theme.metrics;
4492        let value_text = "Round brush, 8 px, 100% opacity";
4493
4494        let (mut runtime, window_id) = build_runtime(
4495            BrushPreview::new("Brush preview")
4496                .theme(theme)
4497                .spec(BrushPreviewSpec::new(
4498                    Color::rgba(0.10, 0.30, 0.90, 1.0),
4499                    8.0,
4500                    1.0,
4501                    BrushPreviewShape::Round,
4502                ))
4503                .size(Size::new(420.0, 96.0)),
4504        );
4505        let output = runtime.render(window_id)?;
4506        let text = text_run_for(&output, value_text);
4507        let layout = TextSystem::new()
4508            .shape_text_run(&text, &FontRegistry::new())
4509            .expect("brush preview value should shape");
4510        let line = layout
4511            .lines()
4512            .first()
4513            .expect("brush preview value should contain one line");
4514        let actual_visual_center =
4515            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
4516        let bounds = Rect::new(0.0, 0.0, 420.0, 96.0);
4517        let content = super::inset_rect(bounds, metrics.brush_preview_padding);
4518        let swatch_width = metrics.brush_preview_swatch_width.min(content.width());
4519        let sample = Rect::new(
4520            content.x() + swatch_width + metrics.brush_preview_swatch_gap,
4521            content.y(),
4522            (content.width() - swatch_width - metrics.brush_preview_swatch_gap).max(0.0),
4523            content.height(),
4524        );
4525        let text_slot = Rect::new(
4526            sample.x(),
4527            sample.max_y() - metrics.brush_preview_text_height,
4528            sample.width(),
4529            metrics.brush_preview_text_height,
4530        );
4531        let slot_center = text_slot.y() + (text_slot.height() * 0.5);
4532
4533        assert_eq!(text.style.font_size, 28.0);
4534        assert_eq!(text.style.line_height, 10.0);
4535        assert!(text.rect.height() >= layout.measurement().height - 0.01);
4536        assert!(text.rect.height() > text.style.line_height);
4537        assert!((text.rect.x() - text_slot.x()).abs() < 0.75);
4538        assert!((actual_visual_center - slot_center).abs() < 0.75);
4539        Ok(())
4540    }
4541
4542    #[test]
4543    fn color_picker_pointer_drag_updates_semantics() -> Result<()> {
4544        let changes = Rc::new(RefCell::new(Vec::new()));
4545        let on_change = Rc::clone(&changes);
4546        let (mut runtime, window_id) = build_runtime(
4547            ColorPicker::new("Accent picker")
4548                .on_change(move |color| on_change.borrow_mut().push(color)),
4549        );
4550
4551        let initial = runtime.render(window_id)?;
4552        let map = initial
4553            .semantics
4554            .iter()
4555            .find(|node| node.name.as_deref() == Some("Saturation and value"))
4556            .expect("saturation/value semantics present")
4557            .bounds;
4558        let start = rect_center(map);
4559        let end = Point::new(map.x() + map.width() * 0.80, map.y() + map.height() * 0.35);
4560        runtime.handle_event(
4561            window_id,
4562            primary_pointer(PointerEventKind::Down, start, true),
4563        )?;
4564        runtime.handle_event(
4565            window_id,
4566            primary_pointer(PointerEventKind::Move, end, true),
4567        )?;
4568        runtime.handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))?;
4569
4570        let changed_color = *changes
4571            .borrow()
4572            .last()
4573            .expect("color picker emitted change");
4574        let output = runtime.render(window_id)?;
4575        let picker = output
4576            .semantics
4577            .iter()
4578            .find(|node| node.role == SemanticsRole::ColorPicker)
4579            .expect("color picker semantics present");
4580        assert_eq!(
4581            picker.value,
4582            Some(SemanticsValue::Text(format_color(changed_color)))
4583        );
4584        Ok(())
4585    }
4586
4587    #[test]
4588    fn color_picker_focus_surface_uses_theme_motion() -> Result<()> {
4589        let theme = DefaultTheme::default();
4590        let focus_duration = theme.motion.focus_duration();
4591        let (mut runtime, window_id) = build_runtime(ColorPicker::new("Accent picker"));
4592        let output = runtime.render(window_id)?;
4593        let focus_target = output
4594            .semantics
4595            .iter()
4596            .find(|node| node.name.as_deref() == Some("Saturation and value"))
4597            .expect("color picker saturation/value semantics present")
4598            .bounds;
4599
4600        runtime.handle_event(
4601            window_id,
4602            primary_pointer(PointerEventKind::Down, rect_center(focus_target), true),
4603        )?;
4604        let _ = runtime.render(window_id)?;
4605
4606        runtime.tick(focus_duration * 0.5);
4607        assert!(handle_ready_events(&mut runtime)? >= 1);
4608        let mid = runtime.render(window_id)?;
4609        assert!(
4610            !solid_stroke_colors(&mid).contains(&theme.palette.focus_ring),
4611            "color picker focus ring should not snap to the settled focus color"
4612        );
4613
4614        runtime.tick(focus_duration);
4615        assert!(handle_ready_events(&mut runtime)? >= 1);
4616        let settled = runtime.render(window_id)?;
4617        assert!(
4618            solid_stroke_colors(&settled).contains(&theme.palette.focus_ring),
4619            "color picker focus ring should settle to the theme focus color"
4620        );
4621
4622        Ok(())
4623    }
4624
4625    #[test]
4626    fn color_picker_color_when_syncs_external_color() -> Result<()> {
4627        let color = Rc::new(RefCell::new(Color::rgba(0.08, 0.22, 0.78, 1.0)));
4628        let color_reader = Rc::clone(&color);
4629        let (mut runtime, window_id) = build_runtime(
4630            ColorPicker::from_color("Brush color", *color.borrow())
4631                .color_when(move || *color_reader.borrow()),
4632        );
4633
4634        let output = runtime.render(window_id)?;
4635        let picker = output
4636            .semantics
4637            .iter()
4638            .find(|node| node.role == SemanticsRole::ColorPicker)
4639            .expect("color picker semantics present");
4640        assert_eq!(
4641            picker.value,
4642            Some(SemanticsValue::Text("#1438C7FF".to_string()))
4643        );
4644
4645        *color.borrow_mut() = Color::rgba(0.90, 0.32, 0.18, 1.0);
4646        runtime.handle_event(
4647            window_id,
4648            primary_pointer(PointerEventKind::Move, Point::new(8.0, 8.0), false),
4649        )?;
4650        let output = runtime.render(window_id)?;
4651        let picker = output
4652            .semantics
4653            .iter()
4654            .find(|node| node.role == SemanticsRole::ColorPicker)
4655            .expect("color picker semantics still present");
4656        assert_eq!(
4657            picker.value,
4658            Some(SemanticsValue::Text("#E6522EFF".to_string()))
4659        );
4660        Ok(())
4661    }
4662
4663    #[test]
4664    fn color_picker_from_color_preserves_hdr_linear_color_space() {
4665        let picker = ColorPicker::from_color(
4666            "HDR accent",
4667            Color::new(ColorSpace::LinearSrgb, 2.0, 0.5, 0.25, 1.0),
4668        );
4669
4670        assert_eq!(picker.color().space, ColorSpace::LinearSrgb);
4671        assert!((picker.color().red - 2.0).abs() < f32::EPSILON);
4672        assert!((picker.color().green - 0.5).abs() < f32::EPSILON);
4673        assert!((picker.color().blue - 0.25).abs() < f32::EPSILON);
4674        assert!((picker.color().alpha - 1.0).abs() < f32::EPSILON);
4675    }
4676
4677    #[test]
4678    fn color_picker_semantics_describe_hdr_editing_mode() -> Result<()> {
4679        let (mut runtime, window_id) = build_runtime(ColorPicker::from_color(
4680            "HDR accent",
4681            Color::new(ColorSpace::LinearSrgb, 2.0, 0.5, 0.25, 1.0),
4682        ));
4683
4684        let output = runtime.render(window_id)?;
4685        let picker = output
4686            .semantics
4687            .iter()
4688            .find(|node| node.role == SemanticsRole::ColorPicker)
4689            .expect("color picker semantics present");
4690
4691        assert_eq!(
4692            picker.description.as_deref(),
4693            Some("BT709 Linear editing space; HDR range available")
4694        );
4695        Ok(())
4696    }
4697
4698    #[test]
4699    fn color_picker_semantics_expose_accessible_components() -> Result<()> {
4700        let (mut runtime, window_id) = build_runtime(ColorPicker::from_color(
4701            "Accent picker",
4702            Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
4703        ));
4704
4705        let output = runtime.render(window_id)?;
4706        let picker = output
4707            .semantics
4708            .iter()
4709            .find(|node| node.role == SemanticsRole::ColorPicker)
4710            .expect("color picker semantics present");
4711        let picker_id = picker.id;
4712
4713        let child = |role: SemanticsRole, name: &str| {
4714            output.semantics.iter().find(|node| {
4715                node.parent == Some(picker_id)
4716                    && node.role == role
4717                    && node.name.as_deref() == Some(name)
4718            })
4719        };
4720
4721        assert!(child(SemanticsRole::ColorSwatch, "Current color").is_some());
4722        assert!(child(SemanticsRole::ColorSwatch, "Previous color").is_some());
4723
4724        let range = child(SemanticsRole::ComboBox, "Color range")
4725            .expect("color range selector semantics present");
4726        assert_eq!(
4727            range.value,
4728            Some(SemanticsValue::Text("BT709 Linear".to_string()))
4729        );
4730        assert_eq!(range.state.expanded, Some(false));
4731
4732        for name in [
4733            "Saturation and value",
4734            "Hue",
4735            "Saturation",
4736            "Value",
4737            "Alpha",
4738            "Red",
4739            "Green",
4740            "Blue",
4741        ] {
4742            let slider = child(SemanticsRole::Slider, name)
4743                .unwrap_or_else(|| panic!("{name} slider semantics present"));
4744            assert!(
4745                matches!(slider.value, Some(SemanticsValue::Range { .. })),
4746                "{name} slider should expose a range value"
4747            );
4748        }
4749
4750        assert!(
4751            output.semantics.iter().any(|node| {
4752                node.parent == Some(picker_id)
4753                    && node.role == SemanticsRole::Text
4754                    && node
4755                        .name
4756                        .as_deref()
4757                        .is_some_and(|name| name.starts_with("HDR hex unavailable"))
4758            }),
4759            "HDR hex field semantics present"
4760        );
4761        Ok(())
4762    }
4763
4764    #[test]
4765    fn color_picker_synthetic_semantics_ids_are_javascript_safe_and_distinct() {
4766        let parent = WidgetId::new(402);
4767        let parts = [
4768            ColorPickerSemanticPart::CurrentColor,
4769            ColorPickerSemanticPart::PreviousColor,
4770            ColorPickerSemanticPart::ColorRange,
4771            ColorPickerSemanticPart::ColorRangeMenu,
4772            ColorPickerSemanticPart::ColorRangeOption(0),
4773            ColorPickerSemanticPart::ColorRangeOption(1),
4774            ColorPickerSemanticPart::ColorRangeOption(2),
4775            ColorPickerSemanticPart::ColorRangeOption(3),
4776            ColorPickerSemanticPart::SaturationValue,
4777            ColorPickerSemanticPart::Hue,
4778            ColorPickerSemanticPart::Saturation,
4779            ColorPickerSemanticPart::Value,
4780            ColorPickerSemanticPart::Alpha,
4781            ColorPickerSemanticPart::Red,
4782            ColorPickerSemanticPart::Green,
4783            ColorPickerSemanticPart::Blue,
4784            ColorPickerSemanticPart::Hex,
4785        ];
4786        let mut ids = BTreeSet::new();
4787        for part in parts {
4788            let id = color_picker_child_semantics_id(parent, part).get();
4789            assert!(id < (1_u64 << 53), "{id} should be JS-safe");
4790            assert!(ids.insert(id), "{id} should be unique");
4791        }
4792    }
4793
4794    #[test]
4795    fn color_picker_columns_are_compact() {
4796        let picker = ColorPicker::new("Accent picker");
4797        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
4798        let wheel = picker.color_wheel_rect(bounds);
4799        let map = picker.saturation_value_rect(bounds);
4800        let metrics = DefaultTheme::default().metrics;
4801
4802        assert_eq!(map.x() - wheel.max_x(), metrics.color_picker_panel_gap);
4803        assert_eq!(map.width(), metrics.color_picker_map_size);
4804        assert_eq!(map.y(), wheel.y());
4805    }
4806
4807    #[test]
4808    fn color_picker_compact_mode_uses_smaller_measurement() {
4809        let regular = ColorPicker::new("Accent picker")
4810            .theme(DefaultTheme::comfortable())
4811            .desired_size();
4812        let compact = ColorPicker::new("Accent picker")
4813            .compact(true)
4814            .show_alpha(false)
4815            .desired_size();
4816        let metrics = DefaultTheme::compact().metrics;
4817
4818        assert_eq!(
4819            compact.width,
4820            metrics.color_picker_wheel_size
4821                + metrics.color_picker_panel_gap
4822                + metrics.color_picker_right_panel_width
4823                + metrics.color_picker_content_inset * 2.0
4824        );
4825        assert!(compact.width < regular.width);
4826        assert!(compact.height < regular.height);
4827    }
4828
4829    #[test]
4830    fn color_picker_theme_density_changes_default_measurement() {
4831        let compact = ColorPicker::new("Accent picker")
4832            .theme(DefaultTheme::compact())
4833            .desired_size();
4834        let comfortable = ColorPicker::new("Accent picker")
4835            .theme(DefaultTheme::comfortable())
4836            .desired_size();
4837        let touch = ColorPicker::new("Accent picker")
4838            .theme(DefaultTheme::touch())
4839            .desired_size();
4840
4841        assert!(compact.width < comfortable.width);
4842        assert!(compact.height < comfortable.height);
4843        assert!(touch.width > comfortable.width);
4844        assert!(touch.height > comfortable.height);
4845    }
4846
4847    #[test]
4848    fn color_picker_chrome_uses_theme_surface_tokens() -> Result<()> {
4849        let mut theme = DefaultTheme::default();
4850        theme.surfaces.checkerboard_light = Color::rgba(0.91, 0.86, 0.78, 1.0);
4851        theme.surfaces.checkerboard_dark = Color::rgba(0.66, 0.58, 0.48, 1.0);
4852        theme.surfaces.color_picker_chrome_border = Color::rgba(0.20, 0.30, 0.42, 0.61);
4853        theme.surfaces.color_picker_plane_border = Color::rgba(0.30, 0.20, 0.46, 0.62);
4854        theme.surfaces.color_picker_bar_border = Color::rgba(0.42, 0.25, 0.18, 0.63);
4855        theme.surfaces.color_picker_marker_outer = Color::rgba(0.98, 0.96, 0.90, 0.94);
4856        theme.surfaces.color_picker_marker_dark = Color::rgba(0.05, 0.07, 0.10, 0.88);
4857        theme.surfaces.color_picker_sdr_marker = Color::rgba(0.95, 0.92, 0.84, 0.38);
4858
4859        let (mut runtime, window_id) = build_runtime(
4860            ColorPicker::from_color("Accent picker", Color::rgba(0.84, 0.72, 0.18, 1.0))
4861                .theme(theme),
4862        );
4863        let output = runtime.render(window_id)?;
4864        let fills = solid_fill_colors(&output);
4865        let strokes = solid_stroke_colors(&output);
4866
4867        assert!(fills.contains(&theme.surfaces.checkerboard_light));
4868        assert!(fills.contains(&theme.surfaces.checkerboard_dark));
4869        assert!(fills.contains(&theme.surfaces.color_picker_sdr_marker));
4870        assert!(strokes.contains(&theme.surfaces.color_picker_chrome_border));
4871        assert!(strokes.contains(&theme.surfaces.color_picker_plane_border));
4872        assert!(strokes.contains(&theme.surfaces.color_picker_bar_border));
4873        assert!(strokes.contains(&theme.surfaces.color_picker_marker_outer));
4874        assert!(strokes.contains(&theme.surfaces.color_picker_marker_dark));
4875        Ok(())
4876    }
4877
4878    #[test]
4879    fn color_picker_header_contains_encoding_selector() {
4880        let picker = ColorPicker::new("Accent picker");
4881        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
4882        let header = picker.header_rect(bounds);
4883        let encoding = picker.encoding_rect(bounds);
4884        let previous = picker.previous_swatch_rect(bounds);
4885        let map = picker.saturation_value_rect(bounds);
4886        let rgb = picker.rgb_row_rect(bounds, 0);
4887
4888        assert!(header.contains(encoding.origin));
4889        assert!(header.contains(Point::new(encoding.max_x(), encoding.max_y())));
4890        assert!(encoding.x() >= previous.max_x() + picker.panel_gap() - 0.01);
4891        assert!(encoding.max_x() <= header.max_x() + 0.01);
4892        assert!(rgb.y() > map.max_y());
4893    }
4894
4895    #[test]
4896    fn color_picker_encoding_chevron_is_centered_in_selector() -> Result<()> {
4897        let picker = ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80));
4898        let (mut runtime, window_id) = build_runtime(picker);
4899        let output = runtime.render(window_id)?;
4900        let bounds = Rect::new(
4901            0.0,
4902            0.0,
4903            output.frame.viewport.width,
4904            output.frame.viewport.height,
4905        );
4906        let layout_picker =
4907            ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80));
4908        let encoding = layout_picker.encoding_rect(bounds);
4909        let theme = DefaultTheme::default();
4910        let chevron =
4911            stroke_path_bounds_with_color_and_width(&output, theme.palette.placeholder, 1.4)
4912                .into_iter()
4913                .find(|rect| {
4914                    encoding.contains(Point::new(
4915                        rect.x() + rect.width() * 0.5,
4916                        rect.y() + rect.height() * 0.5,
4917                    )) && (rect.width() - 8.0).abs() < 0.75
4918                        && (rect.height() - 5.0).abs() < 0.75
4919                })
4920                .expect("encoding selector chevron stroke should render");
4921        let chevron_center_y = chevron.y() + chevron.height() * 0.5;
4922        let selector_center_y = encoding.y() + encoding.height() * 0.5;
4923
4924        assert!(
4925            (chevron_center_y - selector_center_y).abs() < 0.75,
4926            "encoding chevron center {chevron_center_y} did not match selector center {selector_center_y}; chevron={chevron:?}, selector={encoding:?}"
4927        );
4928        Ok(())
4929    }
4930
4931    #[test]
4932    fn color_picker_saturation_value_plane_uses_hdr_slider_curve() {
4933        let mut picker = ColorPicker::from_color(
4934            "Accent picker",
4935            Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
4936        );
4937        let bounds = Rect::new(0.0, 0.0, 434.0, 448.0);
4938        let map = picker.saturation_value_rect(bounds);
4939
4940        picker.update_from_position(
4941            bounds,
4942            ActiveChannel::SaturationValue,
4943            Point::new(map.x() + map.width() * 0.5, map.y() + map.height() * 0.25),
4944        );
4945
4946        assert!(
4947            picker.value > 3.0 && picker.value < 4.0,
4948            "75% HDR slider position should map logarithmically above 1.0, got {}",
4949            picker.value
4950        );
4951    }
4952
4953    #[test]
4954    fn color_picker_rgb_row_drag_updates_color_channels() -> Result<()> {
4955        let changes = Rc::new(RefCell::new(Vec::new()));
4956        let on_change = Rc::clone(&changes);
4957        let (mut runtime, window_id) = build_runtime(
4958            ColorPicker::from_color(
4959                "Accent picker",
4960                Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
4961            )
4962            .on_change(move |color| on_change.borrow_mut().push(color)),
4963        );
4964
4965        let initial = runtime.render(window_id)?;
4966        let red = initial
4967            .semantics
4968            .iter()
4969            .find(|node| node.name.as_deref() == Some("Red"))
4970            .expect("red channel semantics present")
4971            .bounds;
4972        let start = Point::new(red.x() + red.width() * 0.20, red.y() + red.height() * 0.5);
4973        let end = Point::new(red.x() + red.width() * 0.80, red.y() + red.height() * 0.5);
4974        runtime.handle_event(
4975            window_id,
4976            primary_pointer(PointerEventKind::Down, start, true),
4977        )?;
4978        runtime.handle_event(
4979            window_id,
4980            primary_pointer(PointerEventKind::Move, end, true),
4981        )?;
4982        runtime.handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))?;
4983
4984        let changed_color = *changes.borrow().last().expect("rgb row emitted change");
4985        assert!(
4986            changed_color.red > 8.0,
4987            "expected HDR red channel after RGB drag, got {}",
4988            changed_color.red
4989        );
4990        assert_eq!(changed_color.space, ColorSpace::LinearSrgb);
4991        Ok(())
4992    }
4993
4994    #[test]
4995    fn color_picker_numeric_rows_use_tabular_figures_and_end_alignment() -> Result<()> {
4996        let color = Color::rgba(0.25, 0.50, 0.75, 0.80);
4997        let (mut runtime, window_id) =
4998            build_runtime(ColorPicker::from_color("Accent picker", color));
4999        let output = runtime.render(window_id)?;
5000        let run = text_run_for(&output, "0.250");
5001        let bounds = Rect::new(
5002            0.0,
5003            0.0,
5004            output.frame.viewport.width,
5005            output.frame.viewport.height,
5006        );
5007        let picker = ColorPicker::from_color("Accent picker", color);
5008        let row = picker.rgb_row_rect(bounds, 0);
5009        let theme = DefaultTheme::default();
5010        let expected_right = row.max_x() - theme.spacing;
5011
5012        assert!(
5013            run.style
5014                .features
5015                .iter()
5016                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
5017        );
5018        assert!((run.rect.max_x() - expected_right).abs() < 1.0);
5019        assert!(run.rect.height() <= theme.text.xs.line_height + 0.01);
5020        Ok(())
5021    }
5022
5023    #[test]
5024    fn color_picker_numeric_rows_preserve_tall_measurements_and_row_center() -> Result<()> {
5025        let mut theme = DefaultTheme::default();
5026        theme.text.xs = ThemeTextToken {
5027            size: 28.0,
5028            line_height: 12.0,
5029        };
5030        theme.metrics.color_picker_row_height = 48.0;
5031        let color = Color::rgba(0.25, 0.50, 0.75, 0.80);
5032        let (mut runtime, window_id) =
5033            build_runtime(ColorPicker::from_color("Accent picker", color).theme(theme));
5034        let output = runtime.render(window_id)?;
5035        let label = text_run_for(&output, "R");
5036        let value = text_run_for(&output, "0.250");
5037        let layout = TextSystem::new()
5038            .shape_text_run(&value, &FontRegistry::new())
5039            .expect("color picker numeric value should shape");
5040        let bounds = Rect::new(
5041            0.0,
5042            0.0,
5043            output.frame.viewport.width,
5044            output.frame.viewport.height,
5045        );
5046        let picker = ColorPicker::from_color("Accent picker", color).theme(theme);
5047        let row = picker.rgb_row_rect(bounds, 0);
5048        let expected_right = row.max_x() - theme.spacing;
5049        let row_center = row.y() + row.height() * 0.5;
5050        let value_center = text_visual_center_for(&output, "0.250");
5051
5052        assert!((value.rect.max_x() - expected_right).abs() < 1.0);
5053        assert!(
5054            (value_center - row_center).abs() < 0.75,
5055            "color picker numeric value center {value_center} did not match row center {row_center}; value rect {:?}, row {:?}, measurement {:?}",
5056            value.rect,
5057            row,
5058            layout.measurement()
5059        );
5060        let label_center = text_visual_center_for(&output, "R");
5061        let label_layout = TextSystem::new()
5062            .shape_text_run(&label, &FontRegistry::new())
5063            .expect("color picker channel label should shape");
5064        assert!(
5065            (value_center - label_center).abs() < 0.75,
5066            "color picker numeric value center {value_center} and channel label center {label_center} should share a visual baseline; label rect {:?}, label measurement {:?}",
5067            label.rect,
5068            label_layout.measurement()
5069        );
5070        Ok(())
5071    }
5072
5073    #[test]
5074    fn color_picker_text_styles_follow_theme_xs_token() -> Result<()> {
5075        let mut theme = DefaultTheme::default();
5076        theme.text.xs = ThemeTextToken {
5077            size: 13.5,
5078            line_height: 31.0,
5079        };
5080        let (mut runtime, window_id) = build_runtime(
5081            ColorPicker::from_color("Accent picker", Color::rgba(0.25, 0.50, 0.75, 0.80))
5082                .theme(theme),
5083        );
5084        let output = runtime.render(window_id)?;
5085        let label = text_run_for(&output, "R");
5086        let value = text_run_for(&output, "0.250");
5087
5088        assert_text_run_uses_token(&label, theme.text.xs);
5089        assert_text_run_uses_token(&value, theme.text.xs);
5090        assert!(
5091            value
5092                .style
5093                .features
5094                .iter()
5095                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
5096        );
5097        Ok(())
5098    }
5099
5100    #[test]
5101    fn color_picker_dropdown_and_fields_preserve_tall_text_measurements() -> Result<()> {
5102        let mut theme = DefaultTheme::default();
5103        theme.text.xs = ThemeTextToken {
5104            size: 28.0,
5105            line_height: 10.0,
5106        };
5107        theme.metrics.color_picker_top_bar_height = 56.0;
5108        theme.metrics.color_picker_field_height = 46.0;
5109        theme.metrics.color_picker_encoding_menu_row_height = 46.0;
5110        let color = Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0);
5111        let (mut runtime, window_id) =
5112            build_runtime(ColorPicker::from_color("Accent picker", color).theme(theme));
5113
5114        let initial = runtime.render(window_id)?;
5115        let color_range = initial
5116            .semantics
5117            .iter()
5118            .find(|node| node.name.as_deref() == Some("Color range"))
5119            .expect("color range semantics present")
5120            .bounds;
5121        let color_range_center = rect_center(color_range);
5122        runtime.handle_event(
5123            window_id,
5124            primary_pointer(PointerEventKind::Down, color_range_center, true),
5125        )?;
5126        runtime.handle_event(
5127            window_id,
5128            primary_pointer(PointerEventKind::Up, color_range_center, false),
5129        )?;
5130
5131        let output = runtime.render(window_id)?;
5132        let bounds = Rect::new(
5133            0.0,
5134            0.0,
5135            output.frame.viewport.width,
5136            output.frame.viewport.height,
5137        );
5138        let picker = ColorPicker::from_color("Accent picker", color).theme(theme);
5139        let selector = picker.encoding_rect(bounds);
5140        let menu_item = picker.encoding_option_rect(bounds, 0);
5141        let hex = picker.hex_rect(bounds);
5142        let selector_run = text_run_for(&output, "BT709 Linear");
5143        let menu_run = text_run_for(&output, "sRGB");
5144        let hex_run = text_run_for(&output, "HDR hex unavailable");
5145        assert_text_run_uses_token(&selector_run, theme.text.xs);
5146        assert_text_run_uses_token(&menu_run, theme.text.xs);
5147        assert_text_run_uses_token(&hex_run, theme.text.xs);
5148        assert_eq!(hex_run.style.color, theme.palette.placeholder);
5149        assert!(
5150            (text_visual_center_for(&output, "BT709 Linear") - rect_center(selector).y).abs()
5151                < 0.75
5152        );
5153        assert!((text_visual_center_for(&output, "sRGB") - rect_center(menu_item).y).abs() < 0.75);
5154        assert!(
5155            (text_visual_center_for(&output, "HDR hex unavailable") - rect_center(hex).y).abs()
5156                < 0.75
5157        );
5158        Ok(())
5159    }
5160
5161    #[test]
5162    fn color_picker_encoding_selector_uses_dropdown_options() -> Result<()> {
5163        let changes = Rc::new(RefCell::new(Vec::new()));
5164        let on_change = Rc::clone(&changes);
5165        let (mut runtime, window_id) = build_runtime(
5166            ColorPicker::from_color(
5167                "Accent picker",
5168                Color::new(ColorSpace::LinearSrgb, 2.0, 0.65, 0.4, 1.0),
5169            )
5170            .on_change(move |color| on_change.borrow_mut().push(color)),
5171        );
5172
5173        let _ = runtime.render(window_id)?;
5174        runtime.handle_event(
5175            window_id,
5176            primary_pointer(PointerEventKind::Down, Point::new(300.0, 40.0), true),
5177        )?;
5178        runtime.handle_event(
5179            window_id,
5180            primary_pointer(PointerEventKind::Up, Point::new(300.0, 40.0), false),
5181        )?;
5182        assert!(
5183            changes.borrow().is_empty(),
5184            "opening the encoding dropdown should not change color space"
5185        );
5186        let output = runtime.render(window_id)?;
5187        let picker = output
5188            .semantics
5189            .iter()
5190            .find(|node| node.role == SemanticsRole::ColorPicker)
5191            .expect("color picker semantics present after opening encoding dropdown");
5192        let range = output
5193            .semantics
5194            .iter()
5195            .find(|node| {
5196                node.parent == Some(picker.id)
5197                    && node.role == SemanticsRole::ComboBox
5198                    && node.name.as_deref() == Some("Color range")
5199            })
5200            .expect("color range selector semantics present after opening dropdown");
5201        assert_eq!(range.state.expanded, Some(true));
5202        assert!(
5203            output.semantics.iter().any(|node| {
5204                node.role == SemanticsRole::MenuItem
5205                    && node.name.as_deref() == Some("Display P3")
5206                    && node.actions.contains(&SemanticsAction::Activate)
5207            }),
5208            "open color range dropdown should expose Display P3 option"
5209        );
5210
5211        runtime.handle_event(
5212            window_id,
5213            primary_pointer(PointerEventKind::Down, Point::new(300.0, 129.0), true),
5214        )?;
5215        runtime.handle_event(
5216            window_id,
5217            primary_pointer(PointerEventKind::Up, Point::new(300.0, 129.0), false),
5218        )?;
5219
5220        let changed_color = *changes
5221            .borrow()
5222            .last()
5223            .expect("encoding selector emitted change");
5224        assert_eq!(changed_color.space, ColorSpace::DisplayP3);
5225
5226        let output = runtime.render(window_id)?;
5227        let picker = output
5228            .semantics
5229            .iter()
5230            .find(|node| node.role == SemanticsRole::ColorPicker)
5231            .expect("color picker semantics present after encoding change");
5232        assert_eq!(
5233            picker.description.as_deref(),
5234            Some("Display P3 editing space; HDR range available")
5235        );
5236        Ok(())
5237    }
5238}