1use crate::{
8 BackgroundSizing, Brush, ColumnDefinition, CommonState, CommonStates, ControlBorder,
9 ControlStates, FocusVisual, Grid, GridCell, GridLength, ThemeResources, control_text_style,
10};
11use std::{any::TypeId, collections::HashMap, fmt, rc::Rc, time::Duration};
12use waft_animation::{
13 Animation, AnimationBehavior, AnimationController, AnimationStatusListener, Cubic, Curve,
14};
15use waft_embedder::valo::{Cap, FillRule, Join, Point};
16use waft_embedder::{
17 Canvas, Color, FontWeight, Offset, Paint, PaintStyle, PathBuilder, Size, Stroke,
18};
19use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
20use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry};
21use waft_rendering::{BoxConstraints, CustomPainter};
22use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
23use waft_services::LogicalKeyboardKey;
24use waft_widgets::*;
25
26pub const CHECK_BOX_ROOT_BORDER_THICKNESS: f64 = 0.0;
28pub const CHECK_GLYPH_OFFSET: Offset = Offset::new(0.0, 1.0);
30
31pub const ACCEPT_VISUAL_SIZE: f64 = 48.0;
33pub const ACCEPT_VISUAL_DURATION: Duration = Duration::from_nanos(26_666_666 * 100);
35pub const NORMAL_OFF_TO_NORMAL_ON: (f64, f64) = (0.0940625, 0.2128125);
37pub const NORMAL_ON_TO_NORMAL_OFF: (f64, f64) = (0.0, 0.0253125);
39pub const TRIM_END_EASING: [f64; 4] = [0.55, 0.0, 0.0, 1.0];
41pub const TRIM_START_EASING: [f64; 4] = [0.167, 0.167, 0.833, 0.833];
43pub const ACCEPT_STROKE_THICKNESS: f32 = 4.0;
45pub const CHECK_POLYLINE: [(f32, f32); 3] = [(-15.172, 0.016), (-5.0, 10.188), (15.337, -10.337)];
47pub const INDETERMINATE_POLYLINE: [(f32, f32); 2] = [(-11.75, -0.125), (11.875, -0.125)];
49pub const SPRITE_SCALE: f32 = 0.7;
51pub const CHECK_SPRITE_OFFSET: (f32, f32) = (24.0, 23.0);
52pub const INDETERMINATE_SPRITE_OFFSET: (f32, f32) = (24.0, 24.0);
53pub const LAYER_SCALE: f32 = 1.05;
55
56pub fn segment_duration(markers: (f64, f64)) -> Duration {
58 ACCEPT_VISUAL_DURATION.mul_f64(markers.1 - markers.0)
59}
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
66pub(crate) enum CheckState {
67 #[default]
68 Unchecked,
69 Checked,
70 Indeterminate,
71}
72
73impl CheckState {
74 pub(crate) fn from_is_checked(is_checked: Option<bool>) -> CheckState {
75 match is_checked {
76 Some(true) => CheckState::Checked,
77 Some(false) => CheckState::Unchecked,
78 None => CheckState::Indeterminate,
79 }
80 }
81}
82
83pub fn toggle_is_checked(is_checked: Option<bool>, is_three_state: bool) -> Option<bool> {
85 match is_checked {
86 None => Some(false),
87 Some(true) if is_three_state => None,
88 Some(true) => Some(false),
89 Some(false) => Some(true),
90 }
91}
92
93#[derive(Clone, Copy, Debug, PartialEq)]
95pub struct CheckBoxBrushes {
96 pub foreground: Color,
98 pub background: Color,
100 pub border: Color,
102 pub box_stroke: Color,
104 pub box_fill: Color,
106 pub glyph: Color,
108}
109
110pub(crate) fn check_box_brushes(
112 r: &ThemeResources,
113 check: CheckState,
114 common: CommonState,
115) -> CheckBoxBrushes {
116 match (check, common) {
117 (CheckState::Unchecked, CommonState::Normal) => CheckBoxBrushes {
119 foreground: r.check_box_foreground_unchecked,
120 background: r.check_box_background_unchecked,
121 border: r.check_box_border_brush_unchecked,
122 box_stroke: r.check_box_check_background_stroke_unchecked,
123 box_fill: r.check_box_check_background_fill_unchecked,
124 glyph: r.check_box_check_glyph_foreground_unchecked,
125 },
126 (CheckState::Unchecked, CommonState::PointerOver) => CheckBoxBrushes {
127 foreground: r.check_box_foreground_unchecked_pointer_over,
128 background: r.check_box_background_unchecked_pointer_over,
129 border: r.check_box_border_brush_unchecked_pointer_over,
130 box_stroke: r.check_box_check_background_stroke_unchecked_pointer_over,
131 box_fill: r.check_box_check_background_fill_unchecked_pointer_over,
132 glyph: r.check_box_check_glyph_foreground_unchecked_pointer_over,
133 },
134 (CheckState::Unchecked, CommonState::Pressed) => CheckBoxBrushes {
135 foreground: r.check_box_foreground_unchecked_pressed,
136 background: r.check_box_background_unchecked_pressed,
137 border: r.check_box_border_brush_unchecked_pressed,
138 box_stroke: r.check_box_check_background_stroke_unchecked_pressed,
139 box_fill: r.check_box_check_background_fill_unchecked_pressed,
140 glyph: r.check_box_check_glyph_foreground_unchecked_pressed,
141 },
142 (CheckState::Unchecked, CommonState::Disabled) => CheckBoxBrushes {
143 foreground: r.check_box_foreground_unchecked_disabled,
144 background: r.check_box_background_unchecked_disabled,
145 border: r.check_box_border_brush_unchecked_disabled,
146 box_stroke: r.check_box_check_background_stroke_unchecked_disabled,
147 box_fill: r.check_box_check_background_fill_unchecked_disabled,
148 glyph: r.check_box_check_glyph_foreground_unchecked_disabled,
149 },
150 (CheckState::Checked, CommonState::Normal) => CheckBoxBrushes {
151 foreground: r.check_box_foreground_checked,
152 background: r.check_box_background_checked,
153 border: r.check_box_border_brush_checked,
154 box_stroke: r.check_box_check_background_stroke_checked,
155 box_fill: r.check_box_check_background_fill_checked,
156 glyph: r.check_box_check_glyph_foreground_checked,
157 },
158 (CheckState::Checked, CommonState::PointerOver) => CheckBoxBrushes {
159 foreground: r.check_box_foreground_checked_pointer_over,
160 background: r.check_box_background_checked_pointer_over,
161 border: r.check_box_border_brush_checked_pointer_over,
162 box_stroke: r.check_box_check_background_stroke_checked_pointer_over,
163 box_fill: r.check_box_check_background_fill_checked_pointer_over,
164 glyph: r.check_box_check_glyph_foreground_checked_pointer_over,
165 },
166 (CheckState::Checked, CommonState::Pressed) => CheckBoxBrushes {
167 foreground: r.check_box_foreground_checked_pressed,
168 background: r.check_box_background_checked_pressed,
169 border: r.check_box_border_brush_checked_pressed,
170 box_stroke: r.check_box_check_background_stroke_checked_pressed,
171 box_fill: r.check_box_check_background_fill_checked_pressed,
172 glyph: r.check_box_check_glyph_foreground_checked_pressed,
173 },
174 (CheckState::Checked, CommonState::Disabled) => CheckBoxBrushes {
175 foreground: r.check_box_foreground_checked_disabled,
176 background: r.check_box_background_checked_disabled,
177 border: r.check_box_border_brush_checked_disabled,
178 box_stroke: r.check_box_check_background_stroke_checked_disabled,
179 box_fill: r.check_box_check_background_fill_checked_disabled,
180 glyph: r.check_box_check_glyph_foreground_checked_disabled,
181 },
182 (CheckState::Indeterminate, CommonState::Normal) => CheckBoxBrushes {
183 foreground: r.check_box_foreground_indeterminate,
184 background: r.check_box_background_indeterminate,
185 border: r.check_box_border_brush_indeterminate,
186 box_stroke: r.check_box_check_background_stroke_indeterminate,
187 box_fill: r.check_box_check_background_fill_indeterminate,
188 glyph: r.check_box_check_glyph_foreground_indeterminate,
189 },
190 (CheckState::Indeterminate, CommonState::PointerOver) => CheckBoxBrushes {
191 foreground: r.check_box_foreground_indeterminate_pointer_over,
192 background: r.check_box_background_indeterminate_pointer_over,
193 border: r.check_box_border_brush_indeterminate_pointer_over,
194 box_stroke: r.check_box_check_background_stroke_indeterminate_pointer_over,
195 box_fill: r.check_box_check_background_fill_indeterminate_pointer_over,
196 glyph: r.check_box_check_glyph_foreground_indeterminate_pointer_over,
197 },
198 (CheckState::Indeterminate, CommonState::Pressed) => CheckBoxBrushes {
199 foreground: r.check_box_foreground_indeterminate_pressed,
200 background: r.check_box_background_indeterminate_pressed,
201 border: r.check_box_border_brush_indeterminate_pressed,
202 box_stroke: r.check_box_check_background_stroke_indeterminate_pressed,
203 box_fill: r.check_box_check_background_fill_indeterminate_pressed,
204 glyph: r.check_box_check_glyph_foreground_indeterminate_pressed,
205 },
206 (CheckState::Indeterminate, CommonState::Disabled) => CheckBoxBrushes {
207 foreground: r.check_box_foreground_indeterminate_disabled,
208 background: r.check_box_background_indeterminate_disabled,
209 border: r.check_box_border_brush_indeterminate_disabled,
210 box_stroke: r.check_box_check_background_stroke_indeterminate_disabled,
211 box_fill: r.check_box_check_background_fill_indeterminate_disabled,
212 glyph: r.check_box_check_glyph_foreground_indeterminate_disabled,
213 },
214 }
215}
216
217pub type CheckBoxCheckedHandler = Rc<dyn Fn(&mut App, Option<bool>)>;
219
220#[derive(Clone)]
222pub struct CheckBox {
223 pub is_checked: Option<bool>,
224 pub checked: CheckBoxCheckedHandler,
226 pub content: Option<WidgetRef>,
227 pub is_three_state: bool,
228 pub is_enabled: bool,
229 pub key: Option<KeyRef>,
230}
231
232impl CheckBox {
233 pub fn new(
234 is_checked: Option<bool>,
235 checked: impl Fn(&mut App, Option<bool>) + 'static,
236 ) -> CheckBox {
237 CheckBox {
238 is_checked,
239 checked: Rc::new(checked),
240 content: None,
241 is_three_state: false,
242 is_enabled: true,
243 key: None,
244 }
245 }
246
247 #[cfg_attr(debug_assertions, track_caller)]
249 pub fn content<K>(mut self, content: impl IntoWidget<K>) -> CheckBox {
250 self.content = Some(content.into_widget());
251 self
252 }
253
254 pub fn is_three_state(mut self, three_state: bool) -> CheckBox {
256 self.is_three_state = three_state;
257 self
258 }
259
260 pub fn is_enabled(mut self, enabled: bool) -> CheckBox {
262 self.is_enabled = enabled;
263 self
264 }
265
266 pub fn key(mut self, key: KeyRef) -> CheckBox {
267 self.key = Some(key);
268 self
269 }
270
271 fn set_is_checked(&self, value: Option<bool>) -> Listener {
272 let checked = self.checked.clone();
273 Listener::new(move |app| checked(app, value))
274 }
275}
276
277impl fmt::Debug for CheckBox {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 f.debug_struct("CheckBox")
280 .field("is_checked", &self.is_checked)
281 .field("is_three_state", &self.is_three_state)
282 .field("is_enabled", &self.is_enabled)
283 .finish_non_exhaustive()
284 }
285}
286
287impl StatelessWidget for CheckBox {
288 fn key(&self) -> Option<&KeyRef> {
289 self.key.as_ref()
290 }
291
292 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
293 let widget = self.clone();
294 let click = self.set_is_checked(toggle_is_checked(self.is_checked, self.is_three_state));
296 let states = CommonStates::new(click, move |app, context, states| {
298 template(app, context, &widget, states)
299 })
300 .is_enabled(self.is_enabled)
301 .accepts_return(false);
302 CheckBoxKeys {
303 check: self.set_is_checked(Some(true)),
304 uncheck: self.set_is_checked(Some(false)),
305 is_three_state: self.is_three_state,
306 is_enabled: self.is_enabled,
307 child: states.into_widget(),
308 }
309 .into_widget()
310 }
311}
312
313fn template(
315 app: &mut App,
316 context: BuildContext,
317 widget: &CheckBox,
318 states: ControlStates,
319) -> WidgetRef {
320 let resources = ThemeResources::of(app, context);
321 let check = CheckState::from_is_checked(widget.is_checked);
322 let brushes = check_box_brushes(&resources, check, states.common);
323 let root = Grid::new()
325 .column_definitions([
326 ColumnDefinition::new(GridLength::AUTO),
327 ColumnDefinition::new(GridLength::STAR),
328 ])
329 .background(Brush::Solid(brushes.background))
330 .border_brush(Brush::Solid(brushes.border))
331 .border_thickness(CHECK_BOX_ROOT_BORDER_THICKNESS)
332 .corner_radius(resources.control_corner_radius[0])
333 .children([
334 GridCell::new(check_area(&resources, &brushes, check)).into_widget(),
335 GridCell::new(content_presenter(&resources, widget, &brushes))
336 .column(1)
337 .into_widget(),
338 ]);
339 let body = ConstrainedBox::new(
341 BoxConstraints::new()
342 .min_width(resources.check_box_min_width)
343 .min_height(resources.check_box_height),
344 )
345 .child(root);
346 FocusVisual::new(body, resources.theme)
347 .visible(states.focused)
348 .margin(resources.check_box_focus_visual_margin)
349 .corner_radius(resources.control_corner_radius[0])
350 .into_widget()
351}
352
353fn check_area(r: &ThemeResources, brushes: &CheckBoxBrushes, check: CheckState) -> WidgetRef {
355 let rectangle = ControlBorder::new(
357 Brush::Solid(brushes.box_fill),
358 Brush::Solid(brushes.box_stroke),
359 )
360 .border_thickness(r.check_box_border_thickness)
361 .corner_radius(r.control_corner_radius[0])
362 .background_sizing(BackgroundSizing::OuterBorderEdge);
363 let glyph = CheckGlyph {
364 check,
365 color: brushes.glyph,
366 };
367 let glyph = match check {
369 CheckState::Indeterminate => glyph.into_widget(),
370 _ => Transform::translate(CHECK_GLYPH_OFFSET)
371 .child(glyph)
372 .into_widget(),
373 };
374 let grid = Grid::new().children([
375 GridCell::new(rectangle).into_widget(),
376 GridCell::new(glyph).into_widget(),
377 ]);
378 Center::new()
379 .width_factor(1.0)
380 .height_factor(1.0)
381 .child(
382 SizedBox::new()
383 .width(r.check_box_size)
384 .height(r.check_box_size)
385 .child(grid),
386 )
387 .into_widget()
388}
389
390fn content_presenter(
392 r: &ThemeResources,
393 widget: &CheckBox,
394 brushes: &CheckBoxBrushes,
395) -> WidgetRef {
396 let [left, top, right, bottom] = r.check_box_padding;
397 let text = control_text_style(
398 r,
399 r.control_content_theme_font_size,
400 FontWeight::W400,
401 brushes.foreground,
402 );
403 let presenter = Align::new()
404 .alignment(AlignmentGeometry::TOP_LEFT)
405 .width_factor(1.0)
406 .height_factor(1.0);
407 let presenter = match &widget.content {
408 Some(content) => presenter.child(DefaultTextStyle::new(text, content.clone())),
409 None => presenter,
410 };
411 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
412 .child(presenter)
413 .into_widget()
414}
415
416#[derive(Clone)]
418struct CheckBoxKeys {
419 check: Listener,
420 uncheck: Listener,
421 is_three_state: bool,
422 is_enabled: bool,
423 child: WidgetRef,
424}
425
426impl fmt::Debug for CheckBoxKeys {
427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428 f.debug_struct("CheckBoxKeys")
429 .field("is_three_state", &self.is_three_state)
430 .field("is_enabled", &self.is_enabled)
431 .finish_non_exhaustive()
432 }
433}
434
435#[derive(Debug)]
436struct CheckIntent;
437impl Intent for CheckIntent {
438 fn as_any(&self) -> &dyn std::any::Any {
439 self
440 }
441}
442
443#[derive(Debug)]
444struct UncheckIntent;
445impl Intent for UncheckIntent {
446 fn as_any(&self) -> &dyn std::any::Any {
447 self
448 }
449}
450
451struct CheckBoxKeysState {
452 state: StateData<CheckBoxKeys>,
453 actions: HashMap<TypeId, ActionRef>,
454}
455
456impl StatefulWidget for CheckBoxKeys {
457 type State = CheckBoxKeysState;
458 fn create_state(&self) -> CheckBoxKeysState {
459 CheckBoxKeysState {
460 state: StateData::new(),
461 actions: HashMap::new(),
462 }
463 }
464}
465
466impl CheckBoxKeysState {
467 fn shortcuts(widget: &CheckBoxKeys) -> ShortcutMap {
468 let bind =
469 |key: LogicalKeyboardKey, intent: IntentRef| -> (ShortcutActivatorRef, IntentRef) {
470 (Rc::new(SingleActivator::new(key)), intent)
471 };
472 let mut map = Vec::new();
473 if !widget.is_three_state && widget.is_enabled {
474 map.push(bind(LogicalKeyboardKey::NUMPAD_ADD, Rc::new(CheckIntent)));
475 map.push(bind(
476 LogicalKeyboardKey::NUMPAD_SUBTRACT,
477 Rc::new(UncheckIntent),
478 ));
479 }
480 map
481 }
482}
483
484impl State for CheckBoxKeysState {
485 type Widget = CheckBoxKeys;
486 waft_widgets::state_accessors!();
487
488 fn init_state(self: Handle<Self>, app: &mut App) {
489 let check = CallbackAction::<CheckIntent>::new(
490 app,
491 Rc::new(move |app, _| {
492 self.widget(app).check.clone().call(app);
493 None
494 }),
495 );
496 let uncheck = CallbackAction::<UncheckIntent>::new(
497 app,
498 Rc::new(move |app, _| {
499 self.widget(app).uncheck.clone().call(app);
500 None
501 }),
502 );
503 let actions = &mut app.get_mut(self).actions;
504 actions.insert(TypeId::of::<CheckIntent>(), check.into_erased());
505 actions.insert(TypeId::of::<UncheckIntent>(), uncheck.into_erased());
506 }
507
508 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
509 let widget = self.widget(app).clone();
510 let actions = app.get(self).actions.clone();
511 Shortcuts::new(
512 Self::shortcuts(&widget),
513 Actions::new(actions, widget.child),
514 )
515 .into_widget()
516 }
517}
518
519#[derive(Clone, Copy, Debug, PartialEq)]
521pub(crate) struct CheckGlyph {
522 pub(crate) check: CheckState,
523 pub(crate) color: Color,
524}
525
526#[derive(Clone, Copy, Debug, PartialEq, Eq)]
528enum Segment {
529 Still,
531 DrawOn,
533 Erase,
535}
536
537pub(crate) struct CheckGlyphState {
538 state: StateData<CheckGlyph>,
539 single_ticker_provider: SingleTickerProviderStateMixinData,
540 controller: Option<Ref<AnimationController>>,
541 segment: Segment,
542}
543
544impl StatefulWidget for CheckGlyph {
545 type State = CheckGlyphState;
546 fn create_state(&self) -> CheckGlyphState {
547 CheckGlyphState {
548 state: StateData::new(),
549 single_ticker_provider: SingleTickerProviderStateMixinData::default(),
550 controller: None,
551 segment: Segment::Still,
552 }
553 }
554}
555
556impl SingleTickerProviderStateMixin for CheckGlyphState {
557 fn single_ticker_provider_data(
558 self: Handle<Self>,
559 app: &App,
560 ) -> &SingleTickerProviderStateMixinData {
561 &app.get(self).single_ticker_provider
562 }
563 fn single_ticker_provider_data_mut(
564 self: Handle<Self>,
565 app: &mut App,
566 ) -> &mut SingleTickerProviderStateMixinData {
567 &mut app.get_mut(self).single_ticker_provider
568 }
569}
570
571impl TickerProviderObject for CheckGlyphState {
572 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
573 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
574 }
575}
576
577impl CheckGlyphState {
578 fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
579 app.get(self)
580 .controller
581 .handle()
582 .expect("created in init_state")
583 }
584
585 fn play(self: Handle<Self>, app: &mut App, from: CheckState, to: CheckState) {
587 let (segment, markers, easing) = match (from, to) {
588 (CheckState::Unchecked, CheckState::Checked) => {
589 (Segment::DrawOn, NORMAL_OFF_TO_NORMAL_ON, TRIM_END_EASING)
590 }
591 (CheckState::Checked, CheckState::Unchecked) => {
592 (Segment::Erase, NORMAL_ON_TO_NORMAL_OFF, TRIM_START_EASING)
593 }
594 _ => {
595 app.get_mut(self).segment = Segment::Still;
596 self.controller(app).set_value(app, 1.0);
597 return;
598 }
599 };
600 app.get_mut(self).segment = segment;
601 let controller = self.controller(app);
602 controller.set_value(app, 0.0);
603 let [x1, y1, x2, y2] = easing;
604 let curve: Rc<dyn Curve> = Rc::new(Cubic::new(x1, y1, x2, y2));
605 controller.animate_to(app, 1.0, Some(segment_duration(markers)), curve);
606 }
607
608 fn frame(self: Handle<Self>, app: &App) -> Option<(Glyph, (f32, f32))> {
610 let value = self.controller(app).value(app) as f32;
611 let check = self.widget(app).check;
612 match (app.get(self).segment, check) {
613 (Segment::DrawOn, _) => Some((Glyph::Check, (0.0, value))),
614 (Segment::Erase, _) => Some((Glyph::Check, (value, 1.0))),
615 (Segment::Still, CheckState::Checked) => Some((Glyph::Check, (0.0, 1.0))),
616 (Segment::Still, CheckState::Indeterminate) => Some((Glyph::Indeterminate, (0.0, 1.0))),
617 (Segment::Still, CheckState::Unchecked) => None,
618 }
619 }
620}
621
622impl State for CheckGlyphState {
623 type Widget = CheckGlyph;
624 waft_widgets::state_accessors!();
625
626 fn init_state(self: Handle<Self>, app: &mut App) {
627 let controller = AnimationController::new(
628 app,
629 Some(1.0),
630 Some(ACCEPT_VISUAL_DURATION),
631 None,
632 0.0,
633 1.0,
634 AnimationBehavior::Normal,
635 self,
636 );
637 controller.add_listener(app, Listener::new(move |app| self.set_state(app, |_| {})));
638 controller.add_status_listener(
639 app,
640 AnimationStatusListener::new(move |status, app| {
641 if status.is_completed() {
642 self.set_state(app, |state| state.segment = Segment::Still);
643 }
644 }),
645 );
646 app.get_mut(self).controller = Some(controller);
647 }
648
649 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &CheckGlyph) {
650 let check = self.widget(app).check;
651 if check != old_widget.check {
652 self.play(app, old_widget.check, check);
653 }
654 }
655
656 fn activate(self: Handle<Self>, app: &mut App) {
657 SingleTickerProviderStateMixin::activate(self, app);
658 }
659
660 fn dispose(self: Handle<Self>, app: &mut App) {
661 self.controller(app).dispose(app);
662 SingleTickerProviderStateMixin::dispose(self, app);
663 }
664
665 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
666 let painter = AcceptVisualPainter {
667 frame: self.frame(app),
668 color: self.widget(app).color,
669 };
670 CustomPaint::new().painter(painter).into_widget()
671 }
672}
673
674#[derive(Clone, Copy, Debug, PartialEq, Eq)]
676enum Glyph {
677 Check,
679 Indeterminate,
681}
682
683impl Glyph {
684 fn polyline(self) -> &'static [(f32, f32)] {
685 match self {
686 Glyph::Check => &CHECK_POLYLINE,
687 Glyph::Indeterminate => &INDETERMINATE_POLYLINE,
688 }
689 }
690
691 fn sprite_offset(self) -> (f32, f32) {
692 match self {
693 Glyph::Check => CHECK_SPRITE_OFFSET,
694 Glyph::Indeterminate => INDETERMINATE_SPRITE_OFFSET,
695 }
696 }
697}
698
699#[derive(Clone, Debug, PartialEq)]
701struct AcceptVisualPainter {
702 frame: Option<(Glyph, (f32, f32))>,
703 color: Color,
704}
705
706impl CustomPainter for AcceptVisualPainter {
707 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
708 let Some((glyph, trim)) = self.frame else {
709 return;
710 };
711 let Some(path) = trimmed_polyline(glyph.polyline(), trim) else {
712 return;
713 };
714 let scale = (size.width().min(size.height()) / ACCEPT_VISUAL_SIZE) as f32;
715 let canvas_size = ACCEPT_VISUAL_SIZE as f32 * scale;
716 let (dx, dy) = glyph.sprite_offset();
717 canvas.save();
718 canvas.translate(
720 (size.width() as f32 - canvas_size) / 2.0,
721 (size.height() as f32 - canvas_size) / 2.0,
722 );
723 canvas.scale(scale, scale);
724 canvas.translate(
726 ACCEPT_VISUAL_SIZE as f32 / 2.0,
727 ACCEPT_VISUAL_SIZE as f32 / 2.0,
728 );
729 canvas.scale(LAYER_SCALE, LAYER_SCALE);
730 canvas.translate(
731 -ACCEPT_VISUAL_SIZE as f32 / 2.0,
732 -ACCEPT_VISUAL_SIZE as f32 / 2.0,
733 );
734 canvas.translate(dx, dy);
736 canvas.scale(SPRITE_SCALE, SPRITE_SCALE);
737 let mut stroke = Stroke::new(ACCEPT_STROKE_THICKNESS);
738 stroke.cap = Cap::Round;
739 stroke.join = Join::Round;
740 let mut paint = Paint::from_color(self.color.into());
741 paint.style = PaintStyle::Stroke(stroke);
742 canvas.draw_path(&path, FillRule::NonZero, &paint);
743 canvas.restore();
744 }
745
746 fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
747 old_delegate.as_any().downcast_ref::<Self>() != Some(self)
748 }
749
750 fn as_any(&self) -> &dyn std::any::Any {
751 self
752 }
753}
754
755fn trimmed_polyline(
757 points: &[(f32, f32)],
758 (start, end): (f32, f32),
759) -> Option<std::sync::Arc<waft_embedder::valo::Path>> {
760 let lengths: Vec<f32> = points
761 .windows(2)
762 .map(|pair| {
763 let (ax, ay) = pair[0];
764 let (bx, by) = pair[1];
765 ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt()
766 })
767 .collect();
768 let total: f32 = lengths.iter().sum();
769 let (from, to) = (start.clamp(0.0, 1.0) * total, end.clamp(0.0, 1.0) * total);
770 if to <= from {
771 return None;
772 }
773 let point_at = |distance: f32| -> Point {
774 let mut travelled = 0.0;
775 let mut index = 0;
776 while index + 1 < lengths.len() && distance > travelled + lengths[index] {
777 travelled += lengths[index];
778 index += 1;
779 }
780 let t = ((distance - travelled) / lengths[index]).clamp(0.0, 1.0);
781 let (ax, ay) = points[index];
782 let (bx, by) = points[index + 1];
783 Point::new(ax + (bx - ax) * t, ay + (by - ay) * t)
784 };
785 let mut path = PathBuilder::new();
786 path.move_to(point_at(from));
787 let mut travelled = 0.0;
788 for (&(x, y), length) in points[1..].iter().zip(&lengths) {
789 travelled += *length;
790 if travelled > from && travelled < to {
791 path.line_to(Point::new(x, y));
792 }
793 }
794 path.line_to(point_at(to));
795 Some(path.build())
796}