1use crate::{
20 Brush, ColorPickerHsvChannel, ColorPickerState, ColumnDefinition, CommonState, ControlBorder,
21 FocusVisual, Grid, GridCell, GridLength, Hsv, IncrementAmount, IncrementDirection, RangeBase,
22 RowDefinition, SLIDER_DEFAULT_MAXIMUM, SLIDER_DEFAULT_STEP_FREQUENCY,
23 SLIDER_FOCUS_VISUAL_MARGIN, Slider, SliderTemplate, SliderTemplateParts, SliderTemplateStates,
24 ThemeResources, ToolTip, ToolTipService, ValueChangedHandler, color_display_name,
25 color_from_rgba, control_text_style, decrease_definitions, fill_bounded, hsv_to_rgb,
26 increment_alpha_channel, increment_color_channel,
27};
28use std::{fmt, rc::Rc};
29use waft_embedder::{Canvas, Color, Rect, Size};
30use waft_foundation::{App, Handle};
31use waft_painting::{EdgeInsetsGeometry, draw_oval};
32use waft_rendering::{BoxConstraints, CustomPainter};
33use waft_services::{HardwareKeyboard, LogicalKeyboardKey};
34use waft_widgets::*;
35
36const TEMPLATE_MIN_SIZE: f64 = 32.0;
38const THUMB_BORDER_THICKNESS: f64 = 1.0;
40const THUMB_TOOL_TIP_OFFSET: f64 = 20.0;
42
43#[derive(Clone)]
45pub struct ColorPickerSlider {
46 pub value: f64,
48 pub value_changed: ValueChangedHandler,
50 pub color_channel: ColorPickerHsvChannel,
52 pub minimum: f64,
54 pub maximum: f64,
56 pub step_frequency: f64,
58 pub orientation: Axis,
60 pub is_direction_reversed: bool,
62 pub header: Option<WidgetRef>,
64 pub is_thumb_tool_tip_enabled: bool,
67 pub corner_radius: Option<f64>,
70 pub is_enabled: bool,
72 pub key: Option<KeyRef>,
74}
75
76impl ColorPickerSlider {
77 pub fn new(value: f64, value_changed: impl Fn(&mut App, f64) + 'static) -> ColorPickerSlider {
79 ColorPickerSlider {
81 value,
82 value_changed: Rc::new(value_changed),
83 color_channel: ColorPickerHsvChannel::Value,
84 minimum: 0.0,
85 maximum: SLIDER_DEFAULT_MAXIMUM,
86 step_frequency: SLIDER_DEFAULT_STEP_FREQUENCY,
87 orientation: Axis::Horizontal,
88 is_direction_reversed: false,
89 header: None,
90 is_thumb_tool_tip_enabled: true,
91 corner_radius: None,
92 is_enabled: true,
93 key: None,
94 }
95 }
96
97 pub fn color_channel(mut self, value: ColorPickerHsvChannel) -> Self {
99 self.color_channel = value;
100 self
101 }
102
103 pub fn minimum(mut self, value: f64) -> Self {
105 self.minimum = value;
106 self
107 }
108
109 pub fn maximum(mut self, value: f64) -> Self {
111 self.maximum = value;
112 self
113 }
114
115 pub fn step_frequency(mut self, value: f64) -> Self {
117 self.step_frequency = value;
118 self
119 }
120
121 pub fn orientation(mut self, value: Axis) -> Self {
123 self.orientation = value;
124 self
125 }
126
127 pub fn is_direction_reversed(mut self, value: bool) -> Self {
129 self.is_direction_reversed = value;
130 self
131 }
132
133 #[cfg_attr(debug_assertions, track_caller)]
135 pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
136 self.header = Some(value.into_widget());
137 self
138 }
139
140 pub fn is_thumb_tool_tip_enabled(mut self, value: bool) -> Self {
142 self.is_thumb_tool_tip_enabled = value;
143 self
144 }
145
146 pub fn corner_radius(mut self, value: f64) -> Self {
148 self.corner_radius = Some(value);
149 self
150 }
151
152 pub fn is_enabled(mut self, value: bool) -> Self {
154 self.is_enabled = value;
155 self
156 }
157
158 pub fn key(mut self, key: KeyRef) -> Self {
160 self.key = Some(key);
161 self
162 }
163}
164
165impl fmt::Debug for ColorPickerSlider {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_struct("ColorPickerSlider")
168 .field("value", &self.value)
169 .field("color_channel", &self.color_channel)
170 .field("minimum", &self.minimum)
171 .field("maximum", &self.maximum)
172 .field("orientation", &self.orientation)
173 .field("is_enabled", &self.is_enabled)
174 .finish_non_exhaustive()
175 }
176}
177
178impl StatefulWidget for ColorPickerSlider {
179 type State = ColorPickerSliderState;
180
181 fn key(&self) -> Option<&KeyRef> {
182 self.key.as_ref()
183 }
184
185 fn create_state(&self) -> ColorPickerSliderState {
186 ColorPickerSliderState {
187 state: StateData::new(),
188 tool_tip_text: String::new(),
189 tool_tip_enabled: self.is_thumb_tool_tip_enabled,
190 focused: false,
191 }
192 }
193}
194
195pub struct ColorPickerSliderState {
197 state: StateData<ColorPickerSlider>,
198 tool_tip_text: String,
200 tool_tip_enabled: bool,
202 focused: bool,
204}
205
206impl ColorPickerSliderState {
207 fn parent_color_picker(self: Handle<Self>, app: &App) -> Option<Handle<ColorPickerState>> {
209 self.context(app)
210 .find_ancestor_state_of_type::<ColorPickerState>(app)
211 }
212
213 fn tool_tip_string(self: Handle<Self>, app: &App) -> String {
216 let widget = self.widget(app);
217 let value = widget.value.round() as u32;
218 let channel = widget.color_channel;
219 if channel == ColorPickerHsvChannel::Alpha {
220 return format!("{value}% opacity");
221 }
222 let label = match channel {
223 ColorPickerHsvChannel::Hue => "Hue",
224 ColorPickerHsvChannel::Saturation => "Saturation",
225 _ => "Value",
226 };
227 let Some(picker) = self.parent_color_picker(app) else {
228 return format!("{label} {value}");
229 };
230 let mut hsv = picker.current_hsv(app);
231 match channel {
232 ColorPickerHsvChannel::Hue => hsv.h = widget.value,
233 ColorPickerHsvChannel::Saturation => hsv.s = widget.value / 100.0,
234 _ => hsv.v = widget.value / 100.0,
235 }
236 let name = color_display_name(color_from_rgba(hsv_to_rgb(hsv), 1.0));
237 format!("{label} {value} ({name})")
238 }
239
240 fn key_down(
245 self: Handle<Self>,
246 app: &mut App,
247 key: LogicalKeyboardKey,
248 ) -> Option<KeyEventResult> {
249 let direction = match key {
250 LogicalKeyboardKey::ARROW_LEFT | LogicalKeyboardKey::ARROW_DOWN => {
251 IncrementDirection::Lower
252 }
253 LogicalKeyboardKey::ARROW_RIGHT | LogicalKeyboardKey::ARROW_UP => {
254 IncrementDirection::Higher
255 }
256 _ => return None,
257 };
258 let Some(picker) = self.parent_color_picker(app) else {
259 return Some(KeyEventResult::Ignored);
260 };
261 let amount = if HardwareKeyboard::instance(app).is_control_pressed(app) {
262 IncrementAmount::Large
263 } else {
264 IncrementAmount::Small
265 };
266 let widget = self.widget(app).clone();
267 let bounds = picker.widget(app).clone();
268 let mut hsv: Hsv = picker.current_hsv(app);
269 let value = widget.value;
270 let new_value = match widget.color_channel {
271 ColorPickerHsvChannel::Alpha => {
272 increment_alpha_channel(value / 100.0, direction, amount, false, 0.0, 100.0) * 100.0
273 }
274 channel => {
275 let (min_bound, max_bound) = match channel {
276 ColorPickerHsvChannel::Hue => {
277 hsv.h = value;
278 (bounds.min_hue, bounds.max_hue)
279 }
280 ColorPickerHsvChannel::Saturation => {
281 hsv.s = value / 100.0;
282 (bounds.min_saturation, bounds.max_saturation)
283 }
284 _ => {
285 hsv.v = value / 100.0;
286 (bounds.min_value, bounds.max_value)
287 }
288 };
289 let hsv = increment_color_channel(
290 hsv,
291 channel,
292 direction,
293 amount,
294 false,
295 f64::from(min_bound),
296 f64::from(max_bound),
297 );
298 match channel {
299 ColorPickerHsvChannel::Hue => hsv.h,
300 ColorPickerHsvChannel::Saturation => hsv.s * 100.0,
301 _ => hsv.v * 100.0,
302 }
303 }
304 };
305 let coerced = RangeBase::new(widget.minimum, widget.maximum, new_value)
307 .coerced()
308 .value;
309 let current = RangeBase::new(widget.minimum, widget.maximum, value)
310 .coerced()
311 .value;
312 if coerced != current {
313 (widget.value_changed)(app, coerced);
314 }
315 Some(KeyEventResult::Handled)
316 }
317
318 fn focus_changed(self: Handle<Self>, app: &mut App, focused: bool) {
321 let text = focused.then(|| self.tool_tip_string(app));
322 self.set_state(app, |state| {
323 state.focused = focused;
324 if let Some(text) = text {
325 state.tool_tip_text = text;
326 state.tool_tip_enabled = true;
327 }
328 });
329 }
330}
331
332impl State for ColorPickerSliderState {
333 type Widget = ColorPickerSlider;
334 waft_widgets::state_accessors!();
335
336 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
337 if app.get(self).tool_tip_text.is_empty() {
339 app.get_mut(self).tool_tip_text = self.tool_tip_string(app);
340 }
341 }
342
343 fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ColorPickerSlider) {
344 let widget = self.widget(app).clone();
345 if old.is_thumb_tool_tip_enabled != widget.is_thumb_tool_tip_enabled {
346 app.get_mut(self).tool_tip_enabled = widget.is_thumb_tool_tip_enabled;
348 }
349 if old.value != widget.value {
350 let text = self.tool_tip_string(app);
352 let state = app.get_mut(self);
353 state.tool_tip_text = text;
354 state.tool_tip_enabled = true;
355 }
356 }
357
358 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
359 let widget = self.widget(app).clone();
360 let mut slider = Slider::new(widget.value, {
361 let changed = widget.value_changed.clone();
362 move |app, value| changed(app, value)
363 })
364 .minimum(widget.minimum)
365 .maximum(widget.maximum)
366 .step_frequency(widget.step_frequency)
367 .orientation(widget.orientation)
368 .is_direction_reversed(widget.is_direction_reversed)
369 .is_thumb_tool_tip_enabled(widget.is_thumb_tool_tip_enabled)
370 .is_enabled(widget.is_enabled)
371 .template(SliderTemplate::new(
372 0.0,
373 move |app, context, slider, states, parts| {
374 self.template(app, context, slider, states, parts)
375 },
376 ))
377 .key_down(move |app, key| self.key_down(app, key));
378 if let Some(header) = widget.header.clone() {
379 slider = slider.header(header);
380 }
381 Focus::new(slider)
382 .can_request_focus(false)
383 .skip_traversal(true)
384 .on_focus_change(move |app, focused| self.focus_changed(app, focused))
385 .into_widget()
386 }
387}
388
389impl ColorPickerSliderState {
390 fn template(
392 self: Handle<Self>,
393 app: &mut App,
394 context: BuildContext,
395 slider: &Slider,
396 states: SliderTemplateStates,
397 parts: &SliderTemplateParts,
398 ) -> WidgetRef {
399 let resources = ThemeResources::of(app, context);
400 let r = &resources;
401 let widget = self.widget(app).clone();
402 let thumbs = ThumbVisuals::of(r, states.slider);
403 let content = match slider.orientation {
404 Axis::Horizontal => self.horizontal_template(app, r, slider, states, thumbs),
405 Axis::Vertical => vertical_template(r, slider, states, thumbs),
406 };
407 let container =
409 parts.slider_container(ColoredBox::new(Color::from_argb(0, 0, 0, 0)).child(content));
410 let mut children = Vec::new();
411 if let Some(header) = &slider.header {
412 let [left, top, right, bottom] = r.slider_header_theme_margin;
414 let text = control_text_style(
415 &resources,
416 r.control_content_theme_font_size,
417 r.slider_header_theme_font_weight,
418 thumbs.header,
419 );
420 children.push(
421 GridCell::new(
422 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
423 .child(DefaultTextStyle::new(text, header.clone()).soft_wrap(true)),
424 )
425 .row(0)
426 .into_widget(),
427 );
428 }
429 children.push(
430 GridCell::new(
431 FocusVisual::new(container, resources.theme)
432 .visible(states.focused)
433 .margin(SLIDER_FOCUS_VISUAL_MARGIN)
434 .corner_radius(widget.corner_radius.unwrap_or(r.control_corner_radius[0])),
435 )
436 .row(1)
437 .into_widget(),
438 );
439 Grid::new()
440 .row_definitions([
441 RowDefinition::new(GridLength::AUTO),
442 RowDefinition::new(GridLength::STAR),
443 ])
444 .children(children)
445 .into_widget()
446 }
447
448 fn horizontal_template(
450 self: Handle<Self>,
451 app: &App,
452 r: &ThemeResources,
453 slider: &Slider,
454 states: SliderTemplateStates,
455 thumbs: ThumbVisuals,
456 ) -> WidgetRef {
457 let state = app.get(self);
458 let mut tool_tip = ToolTipService::new(
460 thumb(r, thumbs.horizontal),
461 ToolTip::text(state.tool_tip_text.clone())
462 .vertical_offset(THUMB_TOOL_TIP_OFFSET)
463 .placement_rect(thumb_slot(r)),
464 )
465 .is_enabled(state.tool_tip_enabled);
466 if states.tooltip_open || state.focused {
467 tool_tip = tool_tip.is_open(true);
468 }
469 let track = GridCell::new(fill_bounded(Axis::Horizontal, SizedBox::shrink()))
472 .row(1)
473 .column_span(3)
474 .into_widget();
475 let thumb = GridCell::new(
476 Center::new()
477 .width_factor(1.0)
478 .height_factor(1.0)
479 .child(tool_tip),
480 )
481 .row(0)
482 .row_span(3)
483 .column(1)
484 .into_widget();
485 let fraction = slider.range().fraction_of(states.intermediate_value);
486 let (first, last) = decrease_definitions(fraction, slider.is_direction_reversed);
487 let grid = Grid::new()
488 .column_definitions([
489 ColumnDefinition::new(first),
490 ColumnDefinition::new(GridLength::AUTO),
491 ColumnDefinition::new(last),
492 ])
493 .row_definitions([
494 RowDefinition::new(GridLength::pixel(r.slider_pre_content_margin)),
495 RowDefinition::new(GridLength::AUTO),
496 RowDefinition::new(GridLength::pixel(r.slider_post_content_margin)),
497 ])
498 .children([track, thumb]);
499 ConstrainedBox::new(BoxConstraints::new().min_height(TEMPLATE_MIN_SIZE))
500 .child(grid)
501 .into_widget()
502 }
503}
504
505fn vertical_template(
508 r: &ThemeResources,
509 slider: &Slider,
510 states: SliderTemplateStates,
511 thumbs: ThumbVisuals,
512) -> WidgetRef {
513 let mut tool_tip = ToolTipService::new(
514 thumb(r, thumbs.vertical),
515 ToolTip::new(SizedBox::shrink())
516 .vertical_offset(THUMB_TOOL_TIP_OFFSET)
517 .placement_rect(thumb_slot(r)),
518 )
519 .is_enabled(slider.is_thumb_tool_tip_enabled);
520 if states.tooltip_open {
521 tool_tip = tool_tip.is_open(true);
522 }
523 let track = GridCell::new(fill_bounded(Axis::Vertical, SizedBox::shrink()))
525 .column(1)
526 .row_span(3)
527 .into_widget();
528 let thumb = GridCell::new(
529 Center::new()
530 .width_factor(1.0)
531 .height_factor(1.0)
532 .child(tool_tip),
533 )
534 .row(1)
535 .column(0)
536 .column_span(3)
537 .into_widget();
538 let fraction = slider.range().fraction_of(states.intermediate_value);
539 let (last, first) = decrease_definitions(fraction, slider.is_direction_reversed);
541 let grid = Grid::new()
542 .row_definitions([
543 RowDefinition::new(first),
544 RowDefinition::new(GridLength::AUTO),
545 RowDefinition::new(last),
546 ])
547 .column_definitions([
548 ColumnDefinition::new(GridLength::pixel(r.slider_pre_content_margin)),
549 ColumnDefinition::new(GridLength::AUTO),
550 ColumnDefinition::new(GridLength::pixel(r.slider_post_content_margin)),
551 ])
552 .children([track, thumb]);
553 ConstrainedBox::new(BoxConstraints::new().min_width(TEMPLATE_MIN_SIZE))
554 .child(grid)
555 .into_widget()
556}
557
558fn thumb_slot(r: &ThemeResources) -> Rect {
560 Rect::from_ltwh(
561 0.0,
562 0.0,
563 r.slider_horizontal_thumb_width,
564 r.slider_horizontal_thumb_height,
565 )
566}
567
568#[derive(Clone, Copy, Debug, PartialEq)]
571struct ThumbVisuals {
572 horizontal: Color,
574 vertical: Color,
576 header: Color,
578}
579
580impl ThumbVisuals {
581 fn of(r: &ThemeResources, state: CommonState) -> ThumbVisuals {
582 let horizontal = match state {
583 CommonState::Normal => r.color_picker_slider_thumb_background,
584 CommonState::PointerOver => r.color_picker_slider_thumb_background_pointer_over,
585 CommonState::Pressed => r.color_picker_slider_thumb_background_pressed,
586 CommonState::Disabled => r.color_picker_slider_thumb_background_disabled,
587 };
588 ThumbVisuals {
589 horizontal,
590 vertical: r.color_picker_slider_thumb_background,
591 header: if state == CommonState::Disabled {
592 r.color_picker_header_content_disabled
593 } else {
594 r.slider_header_foreground
595 },
596 }
597 }
598}
599
600fn thumb(r: &ThemeResources, fill: Color) -> WidgetRef {
604 SizedBox::new()
605 .width(r.slider_horizontal_thumb_width)
606 .height(r.slider_horizontal_thumb_height)
607 .child(
608 ControlBorder::new(
609 Brush::Solid(r.slider_outer_thumb_background),
610 Brush::ControlElevation(r.slider_thumb_border_brush),
611 )
612 .border_thickness(THUMB_BORDER_THICKNESS)
613 .corner_radius(r.slider_thumb_corner_radius[0])
614 .child(
615 Center::new().child(
616 SizedBox::new()
617 .width(r.color_picker_slider_inner_thumb_width)
618 .height(r.color_picker_slider_inner_thumb_height)
619 .child(CustomPaint::new().painter(InnerThumbPainter { fill })),
620 ),
621 ),
622 )
623 .into_widget()
624}
625
626#[derive(Clone, Debug, PartialEq)]
628struct InnerThumbPainter {
629 fill: Color,
630}
631
632impl CustomPainter for InnerThumbPainter {
633 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
634 let bounds = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
635 draw_oval(
636 canvas,
637 bounds,
638 &waft_embedder::Paint::from_color(self.fill.into()),
639 );
640 }
641
642 fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
643 old_delegate.as_any().downcast_ref::<Self>() != Some(self)
644 }
645
646 fn as_any(&self) -> &dyn std::any::Any {
647 self
648 }
649}