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