rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! BezierCurveEditor widget — interactive cubic bezier curve editor for creating custom easing curves.
//!
//! This widget provides a visual editor for cubic bezier curves with two control points,
//! a grid background, snap-to-grid support, and drag interaction. It can be used to design
//! custom easing functions for animations.

use crate::core::{Color, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::expect_bool;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Control point handle radius in pixels.
const HANDLE_RADIUS: u32 = 8;
/// Weight, in `0.0..=1.0`, the grid is blended toward the text colour over the
/// surface. Previously an `u8` alpha (60/255 ≈ 0.24) applied to a fixed grey;
/// expressing it as a blend weight lets the grid follow the resolved surface.
const GRID_ALPHA: f32 = 0.24;

/// BezierCurveEditor widget for creating custom easing curves.
pub struct BezierCurveEditor {
    base: BaseWidget,
    /// First control point as a fraction of the widget area (0.0–1.0).
    control_point1: (f32, f32),
    /// Second control point as a fraction of the widget area (0.0–1.0).
    control_point2: (f32, f32),
    /// Grid cell size in pixels.
    grid_size: f32,
    /// Whether to draw the background grid.
    show_grid: bool,
    /// Whether control points snap to the grid.
    snap_to_grid: bool,
    /// Which handle is being dragged (None = not dragging).
    dragging: Option<DragTarget>,
    /// Which handle the pointer is currently over (None = between/outside the handles).
    ///
    /// Recorded by `MouseMove` through the same `hit_test_handle` the press uses, so the
    /// handle that lights up is the handle a press would grab. `BaseWidget::is_hovered()`
    /// answers whether the *pointer is over the control*; only this answers which handle
    /// it is over, and the two are not the same fact.
    hovered_handle: Option<DragTarget>,
    /// Emitted when the curve changes. Passes (control_point1, control_point2).
    pub curve_changed: Signal1<((f32, f32), (f32, f32))>,
}

/// Identifies which control point is being dragged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DragTarget {
    ControlPoint1,
    ControlPoint2,
}

impl BezierCurveEditor {
    /// Creates a new BezierCurveEditor with the given geometry.
    /// Default control points form a standard ease-in-out curve.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::BezierCurveEditor, geometry, "BezierCurveEditor"),
            control_point1: (0.25, 0.1),
            control_point2: (0.75, 0.9),
            grid_size: 0.2,
            show_grid: true,
            snap_to_grid: false,
            dragging: None,
            hovered_handle: None,
            curve_changed: Signal1::new(),
        }
    }

    /// Returns the first control point as a fraction (0.0–1.0).
    pub fn control_point1(&self) -> (f32, f32) {
        self.control_point1
    }

    /// Sets the first control point with values clamped to 0.0–1.0.
    pub fn set_control_point1(&mut self, x: f32, y: f32) {
        let old = self.control_point1;
        self.control_point1 = (x.clamp(0.0, 1.0), y.clamp(0.0, 1.0));
        if self.control_point1 != old {
            self.emit_curve_changed();
            self.base.request_redraw();
        }
    }

    /// Returns the second control point as a fraction (0.0–1.0).
    pub fn control_point2(&self) -> (f32, f32) {
        self.control_point2
    }

    /// Sets the second control point with values clamped to 0.0–1.0.
    pub fn set_control_point2(&mut self, x: f32, y: f32) {
        let old = self.control_point2;
        self.control_point2 = (x.clamp(0.0, 1.0), y.clamp(0.0, 1.0));
        if self.control_point2 != old {
            self.emit_curve_changed();
            self.base.request_redraw();
        }
    }

    /// Sets whether the background grid is drawn.
    pub fn set_show_grid(&mut self, show: bool) {
        if self.show_grid != show {
            self.show_grid = show;
            self.base.request_redraw();
        }
    }

    /// Returns whether the background grid is shown.
    pub fn show_grid(&self) -> bool {
        self.show_grid
    }

    /// Sets whether control points snap to the grid.
    pub fn set_snap_to_grid(&mut self, snap: bool) {
        self.snap_to_grid = snap;
    }

    /// Returns whether control points snap to the grid.
    pub fn snap_to_grid(&self) -> bool {
        self.snap_to_grid
    }

    /// Sets the grid size (spacing between grid lines as a fraction of widget size).
    pub fn set_grid_size(&mut self, size: f32) {
        self.grid_size = size.clamp(0.05, 0.5);
        self.base.request_redraw();
    }

    /// Returns the grid size.
    pub fn grid_size(&self) -> f32 {
        self.grid_size
    }

    /// Evaluates the cubic bezier curve at parameter t (0.0–1.0).
    /// Returns the (x, y) value on the curve at that parameter.
    pub fn sample_at(&self, t: f32) -> (f32, f32) {
        let p0 = (0.0f32, 0.0f32);
        let p3 = (1.0f32, 1.0f32);
        Self::cubic_bezier(t, p0, self.control_point1, self.control_point2, p3)
    }

    /// Evaluates a cubic bezier curve at parameter t (0.0–1.0) with control points
    /// given as `(p0, p1, p2, p3)` tuples.
    pub fn cubic_bezier(
        t: f32,
        p0: (f32, f32),
        p1: (f32, f32),
        p2: (f32, f32),
        p3: (f32, f32),
    ) -> (f32, f32) {
        let (p0x, p0y) = p0;
        let (p1x, p1y) = p1;
        let (p2x, p2y) = p2;
        let (p3x, p3y) = p3;
        let u = 1.0 - t;
        let tt = t * t;
        let uu = u * u;
        let uuu = uu * u;
        let ttt = tt * t;
        let x = uuu * p0x + 3.0 * uu * t * p1x + 3.0 * u * tt * p2x + ttt * p3x;
        let y = uuu * p0y + 3.0 * uu * t * p1y + 3.0 * u * tt * p2y + ttt * p3y;
        (x, y)
    }

    /// Emits the curve_changed signal with current control points.
    fn emit_curve_changed(&self) {
        self.curve_changed.emit((self.control_point1, self.control_point2));
    }

    /// Converts a curve coordinate (0.0–1.0) to a pixel position within the widget.
    fn curve_to_pixel(&self, cx: f32, cy: f32) -> Point {
        let rect = self.geometry();
        let margin = HANDLE_RADIUS as i32 + 4;
        let draw_w = (rect.width as i32 - 2 * margin).max(1) as f32;
        let draw_h = (rect.height as i32 - 2 * margin).max(1) as f32;
        Point::new(
            (rect.x + margin) + (cx * draw_w) as i32,
            (rect.y + margin) + ((1.0 - cy) * draw_h) as i32,
        )
    }

    /// Converts a pixel position to a curve coordinate (0.0–1.0).
    fn pixel_to_curve(&self, px: i32, py: i32) -> (f32, f32) {
        let rect = self.geometry();
        let margin = HANDLE_RADIUS as i32 + 4;
        let draw_w = (rect.width as i32 - 2 * margin).max(1) as f32;
        let draw_h = (rect.height as i32 - 2 * margin).max(1) as f32;
        let cx = ((px - rect.x - margin) as f32 / draw_w).clamp(0.0, 1.0);
        let cy = 1.0 - ((py - rect.y - margin) as f32 / draw_h).clamp(0.0, 1.0);
        if self.snap_to_grid && self.grid_size > 0.0 {
            let snapped_x = (cx / self.grid_size).round() * self.grid_size;
            let snapped_y = (cy / self.grid_size).round() * self.grid_size;
            (snapped_x.clamp(0.0, 1.0), snapped_y.clamp(0.0, 1.0))
        } else {
            (cx, cy)
        }
    }

    /// Returns how close a pixel position is to a control point handle, in pixels.
    fn distance_to_handle(&self, pos: Point, cp: (f32, f32)) -> f64 {
        let hp = self.curve_to_pixel(cp.0, cp.1);
        let dx = (pos.x - hp.x) as f64;
        let dy = (pos.y - hp.y) as f64;
        (dx * dx + dy * dy).sqrt()
    }

    /// Returns which control point handle is at the given position, if any.
    fn hit_test_handle(&self, pos: Point) -> Option<DragTarget> {
        let threshold = (HANDLE_RADIUS + 4) as f64;
        let d1 = self.distance_to_handle(pos, self.control_point1);
        let d2 = self.distance_to_handle(pos, self.control_point2);
        if d1 < threshold && d1 <= d2 {
            Some(DragTarget::ControlPoint1)
        } else if d2 < threshold {
            Some(DragTarget::ControlPoint2)
        } else {
            None
        }
    }

    /// Draws a single grid line with a subtle color.
    fn draw_grid_line(&self, context: &mut RenderContext, from: Point, to: Point, color: Color) {
        context.draw_line(from, to, color);
    }

    /// Draws one control-point handle, with an emphasis ring when it is hovered or dragged.
    ///
    /// # Why the two emphasis weights differ
    ///
    /// A hover is "this is the one you would grab"; a drag is "you are holding it". The
    /// stronger weight on the drag is what tells a user mid-gesture that the pointer is
    /// still attached to the handle, which is the feedback a curve editor lives on. The
    /// two are the same pair of weights the theme's own state overlays use (0.08 hover,
    /// 0.12 pressed), so a handle does not invent a third visual language.
    ///
    /// The two flags are named for what they *draw* (`under_pointer`, `held`) rather than
    /// `hovered`/`dragging`, because `hovered` is the name of a control-level fact owned by
    /// `BaseWidget` — and a parameter that shadows that name is exactly what the
    /// state-source gate exists to flag.
    fn draw_handle(
        context: &mut RenderContext,
        center: Point,
        fill: Color,
        surface: Color,
        held: bool,
        under_pointer: bool,
    ) {
        const HOVER_HALO_RADIUS: u32 = HANDLE_RADIUS + 3;
        const DRAG_HALO_RADIUS: u32 = HANDLE_RADIUS + 5;
        if held {
            context.fill_circle(center, DRAG_HALO_RADIUS, fill.with_alpha(64));
        } else if under_pointer {
            context.fill_circle(center, HOVER_HALO_RADIUS, fill.with_alpha(40));
        }
        context.fill_circle(center, HANDLE_RADIUS, fill);
        context.draw_circle_stroke(center, HANDLE_RADIUS, surface, 2);
    }
}

impl Widget for BezierCurveEditor {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(300, 200)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `BezierCurveEditor`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch.
impl WidgetProperties for BezierCurveEditor {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "snap_to_grid" => Ok(CapabilityValue::Bool(self.snap_to_grid())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "snap_to_grid" => {
                self.set_snap_to_grid(expect_bool(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["snap_to_grid", BASE_PROPERTY_NAMES]
    }
}

impl Draw for BezierCurveEditor {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let is_enabled = self.base.is_enabled();
        let margin = HANDLE_RADIUS as i32 + 4;
        let draw_w = (rect.width as i32 - 2 * margin).max(1) as f32;
        let draw_h = (rect.height as i32 - 2 * margin).max(1) as f32;

        // Chrome colours resolve explicit style first, then the theme's resolved
        // style for this control, and only then a literal. The theme step is what
        // makes an appearance switch visible; previously the surface, grid, axes,
        // polygon and labels were all hardcoded, so light and dark rendered the same.
        //
        // `resolved_theme_style` and `semantic_color` each take and release the
        // global manager's lock internally, so no guard is held across the draw (the
        // mutex is not re-entrant).
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("bezier_curve_editor");
        let surface = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::WHITE);
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .unwrap_or_else(|| surface.blend(&Color::BLACK, 0.18));
        let text_color = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::BLACK);

        // ── Background ──
        // A disabled editor is the same surface, faded: derived from the resolved
        // colour rather than a second literal so it still follows the appearance.
        let bg = if !is_enabled { surface.with_alpha(100) } else { surface.with_alpha(255) };
        context.fill_rect(rect, bg);

        // ── Grid ──
        if self.show_grid && is_enabled {
            let grid_color = surface.blend(&text_color, GRID_ALPHA);
            let steps = (1.0 / self.grid_size) as u32;
            for i in 0..=steps {
                let frac = i as f32 * self.grid_size;
                let x = (rect.x + margin) + (frac * draw_w) as i32;
                let y = (rect.y + margin) + ((1.0 - frac) * draw_h) as i32;
                // Vertical grid line.
                self.draw_grid_line(
                    context,
                    Point::new(x, rect.y + margin),
                    Point::new(x, rect.y + margin + draw_h as i32),
                    grid_color,
                );
                // Horizontal grid line.
                self.draw_grid_line(
                    context,
                    Point::new(rect.x + margin, y),
                    Point::new(rect.x + margin + draw_w as i32, y),
                    grid_color,
                );
            }

            // ── Axis lines ──
            let axis_color = surface.blend(&text_color, 0.6);
            // X-axis (bottom edge).
            context.draw_line(
                Point::new(rect.x + margin, rect.y + margin + draw_h as i32),
                Point::new(rect.x + margin + draw_w as i32, rect.y + margin + draw_h as i32),
                axis_color,
            );
            // Y-axis (left edge).
            context.draw_line(
                Point::new(rect.x + margin, rect.y + margin),
                Point::new(rect.x + margin, rect.y + margin + draw_h as i32),
                axis_color,
            );
        }

        if !is_enabled {
            return;
        }

        // ── Control polygon (lines from endpoints to control points) ──
        let p0 = self.curve_to_pixel(0.0, 0.0);
        let p3 = self.curve_to_pixel(1.0, 1.0);
        let cp1_pixel = self.curve_to_pixel(self.control_point1.0, self.control_point1.1);
        let cp2_pixel = self.curve_to_pixel(self.control_point2.0, self.control_point2.1);

        // CP1 and CP2 are the two draggable identities of the curve, so they keep a
        // distinct hue each; both are drawn *over* the themed surface and their
        // handles are outlined in the surface colour so they stay readable in either
        // appearance. The handles' outline previously hardcoded white, which vanished
        // on a light surface once the surface stopped being hardcoded too.
        let cp1_color = surface.blend(&Color::BLUE, 0.75);
        let cp2_color = surface.blend(&Color::GREEN, 0.75);

        let poly_color = surface.blend(&text_color, 0.5);
        context.draw_line(p0, cp1_pixel, poly_color);
        context.draw_line(p3, cp2_pixel, poly_color);

        // ── Bezier curve ──
        let curve_color = crate::style::semantic_color(crate::style::SemanticColor::Info)
            .map(|token| surface.blend(&token, 0.8))
            .unwrap_or_else(|| surface.blend(&Color::BLUE, 0.8));
        let segments = 50;
        let mut prev = self.curve_to_pixel(0.0, 0.0);
        for i in 1..=segments {
            let t = i as f32 / segments as f32;
            let (cx, cy) = self.sample_at(t);
            let cur = self.curve_to_pixel(cx, cy);
            context.draw_line_stroke(prev, cur, curve_color, 2);
            prev = cur;
        }

        // ── Control point handles ──
        // The outline is the surface colour, not white: on a light appearance a white
        // outline would be invisible against the pale surface.
        //
        // A handle the pointer is over, and the one being dragged, gains a halo in its own
        // hue. Without it `dragging` was stored and announced but never *painted*, so a
        // drag looked exactly like a still frame — the point moved, but nothing said which
        // handle was under the pointer. Both facts come from the same `hit_test_handle`
        // the press uses, so the handle that lights up is the handle a drag would move.
        // CP1 handle.
        Self::draw_handle(
            context,
            cp1_pixel,
            cp1_color,
            surface,
            self.dragging == Some(DragTarget::ControlPoint1),
            self.hovered_handle == Some(DragTarget::ControlPoint1),
        );

        // CP2 handle.
        Self::draw_handle(
            context,
            cp2_pixel,
            cp2_color,
            surface,
            self.dragging == Some(DragTarget::ControlPoint2),
            self.hovered_handle == Some(DragTarget::ControlPoint2),
        );

        // ── Labels ──
        let font = crate::core::Font::default();
        let cp1_label =
            format!("CP1: ({:.2}, {:.2})", self.control_point1.0, self.control_point1.1);
        let cp2_label =
            format!("CP2: ({:.2}, {:.2})", self.control_point2.0, self.control_point2.1);

        context.draw_text(
            Point::new(rect.x + 4, rect.y + 12),
            &cp1_label,
            &font,
            // The labels name which control point is which, so the hue is information and stays
            // — but it has to be *readable* on the surface, which the handle's own colour is not:
            // the handle is a disc with a contrasting outline, so its fill only has to be visible
            // as a shape, whereas `rgb(5,5,196)` as text on the dark surface measured 1.63:1 and
            // the green measured 1.22:1 on the light one. Same hue, guaranteed ratio.
            cp1_color.legible_on(surface, 4.5),
            HorizontalAlignment::Left,
        );
        context.draw_text(
            Point::new(rect.x + 4, rect.y + 26),
            &cp2_label,
            &font,
            cp2_color.legible_on(surface, 4.5),
            HorizontalAlignment::Left,
        );

        // ── Endpoint markers ──
        context.fill_circle(p0, 4, surface.blend(&text_color, 0.6));
        context.fill_circle(p3, 4, surface.blend(&text_color, 0.6));

        // A frame separates the editor from whatever it is embedded in.
        context.draw_rect(rect, border);
    }
}

impl EventHandler for BezierCurveEditor {
    fn handle_event(&mut self, event: &Event) {
        // The base keeps the control-level facts (`hovered`, `pressed`, `focus_reason`) and its
        // `MouseEnter`/`MouseLeave` arms are what make `widget_state()` answer `Hover` here. This
        // handler used to forward only in its catch-all arm, so the pointer state never reached
        // the base for the events it *did* consume — the theme's `"bezier_curve_editor:hover"`
        // override could not fire while dragging, which is exactly when feedback matters most.
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button } => {
                if *button == 1 {
                    if let Some(target) = self.hit_test_handle(*pos) {
                        self.dragging = Some(target);
                        self.base.set_mouse_pressed(true);
                    }
                }
            }
            Event::MouseRelease { pos: _, button } => {
                if *button == 1 && self.dragging.is_some() {
                    self.dragging = None;
                    self.base.set_mouse_pressed(false);
                }
            }
            // Leaving the control clears both the hover emphasis and any drag the runtime
            // never delivered a release for. A press whose release lands outside the widget
            // never reaches the arm above: the runtime's hit-test returns `None` for a point
            // outside every control, so no `MouseRelease` is delivered. `dragging` (and the
            // base's pressed flag) stayed set, so the next hover kept moving a control point
            // with no button held. Cancelling on leave is the documented behaviour for this
            // pattern elsewhere (`KanbanBoard::cancel_drag`).
            Event::MouseLeave { .. } => {
                let had_drag = self.dragging.take().is_some();
                if self.hovered_handle.take().is_some() || had_drag {
                    self.base.set_mouse_pressed(false);
                    self.base.request_redraw();
                }
            }
            Event::MouseMove { pos } => {
                if let Some(target) = self.dragging {
                    let (cx, cy) = self.pixel_to_curve(pos.x, pos.y);
                    match target {
                        DragTarget::ControlPoint1 => {
                            self.set_control_point1(cx, cy);
                        }
                        DragTarget::ControlPoint2 => {
                            self.set_control_point2(cx, cy);
                        }
                    }
                }
                // Moving over a handle changes which one is emphasised, so the frame that
                // moved the pointer has to be repainted. The hit test is the same one the
                // press uses, so the handle that lights up is the handle a press would grab.
                let hovered = self.hit_test_handle(*pos);
                if hovered != self.hovered_handle {
                    self.hovered_handle = hovered;
                    self.base.request_redraw();
                }
            }
            _ => { /* Other events need no control-specific handling */ }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    use std::sync::{Arc, Mutex};

    fn default_editor() -> BezierCurveEditor {
        BezierCurveEditor::new(Rect::new(0, 0, 300, 300))
    }

    #[test]
    fn bezier_creation_defaults() {
        let editor = default_editor();
        assert_eq!(editor.control_point1(), (0.25, 0.1));
        assert_eq!(editor.control_point2(), (0.75, 0.9));
        assert!(editor.show_grid());
        assert!(!editor.snap_to_grid());
        assert!((editor.grid_size() - 0.2).abs() < 0.001);
        assert_eq!(editor.kind(), WidgetKind::BezierCurveEditor);
    }

    #[test]
    fn bezier_set_control_point1() {
        let mut editor = default_editor();
        editor.set_control_point1(0.5, 0.3);
        assert_eq!(editor.control_point1(), (0.5, 0.3));
    }

    #[test]
    fn bezier_set_control_point2() {
        let mut editor = default_editor();
        editor.set_control_point2(0.6, 0.7);
        assert_eq!(editor.control_point2(), (0.6, 0.7));
    }

    #[test]
    fn bezier_control_points_clamped() {
        let mut editor = default_editor();
        editor.set_control_point1(1.5, -0.5);
        assert_eq!(editor.control_point1(), (1.0, 0.0));

        editor.set_control_point2(2.0, 2.0);
        assert_eq!(editor.control_point2(), (1.0, 1.0));
    }

    #[test]
    fn bezier_cubic_bezier_static() {
        // Linear curve: endpoints (0,0) and (1,1), control points on the line.
        let (x, y) =
            BezierCurveEditor::cubic_bezier(0.5, (0.0, 0.0), (0.5, 0.5), (0.5, 0.5), (1.0, 1.0));
        assert!((x - 0.5).abs() < 0.01);
        assert!((y - 0.5).abs() < 0.01);
    }

    #[test]
    fn bezier_sample_at() {
        let editor = default_editor();
        // At t=0, we should be at (0,0).
        let (x0, y0) = editor.sample_at(0.0);
        assert!((x0 - 0.0).abs() < 0.01);
        assert!((y0 - 0.0).abs() < 0.01);

        // At t=1, we should be at (1,1).
        let (x1, y1) = editor.sample_at(1.0);
        assert!((x1 - 1.0).abs() < 0.01);
        assert!((y1 - 1.0).abs() < 0.01);
    }

    #[test]
    fn bezier_curve_changed_signal() {
        let mut editor = default_editor();
        let captured = Arc::new(Mutex::new(None));
        editor.curve_changed.connect({
            let captured = Arc::clone(&captured);
            move |val: Arc<((f32, f32), (f32, f32))>| {
                *captured.lock().unwrap() = Some(*val);
            }
        });

        editor.set_control_point1(0.5, 0.2);
        let signal_val = *captured.lock().unwrap();
        assert!(signal_val.is_some());
        let (cp1, _cp2) = signal_val.unwrap();
        assert_eq!(cp1, (0.5, 0.2));
    }

    #[test]
    fn bezier_set_show_grid() {
        let mut editor = default_editor();
        assert!(editor.show_grid());
        editor.set_show_grid(false);
        assert!(!editor.show_grid());
        editor.set_show_grid(true);
        assert!(editor.show_grid());
    }

    #[test]
    fn bezier_set_snap_to_grid() {
        let mut editor = default_editor();
        assert!(!editor.snap_to_grid());
        editor.set_snap_to_grid(true);
        assert!(editor.snap_to_grid());
    }

    #[test]
    fn bezier_set_grid_size_clamped() {
        let mut editor = default_editor();
        editor.set_grid_size(0.1);
        assert!((editor.grid_size() - 0.1).abs() < 0.001);

        editor.set_grid_size(0.01); // below minimum, clamped
        assert!((editor.grid_size() - 0.05).abs() < 0.001);

        editor.set_grid_size(1.0); // above maximum, clamped
        assert!((editor.grid_size() - 0.5).abs() < 0.001);
    }

    #[test]
    fn bezier_pixel_to_curve_roundtrip() {
        let editor = BezierCurveEditor::new(Rect::new(10, 10, 200, 200));
        // Test roundtrip: curve -> pixel -> curve.
        let test_points = [(0.0, 0.0), (1.0, 1.0), (0.5, 0.5), (0.25, 0.75)];
        for &(cx, cy) in &test_points {
            let pixel = editor.curve_to_pixel(cx, cy);
            let (rx, ry) = editor.pixel_to_curve(pixel.x, pixel.y);
            assert!((cx - rx).abs() < 0.02, "X roundtrip failed for ({}, {})", cx, cy);
            assert!((cy - ry).abs() < 0.02, "Y roundtrip failed for ({}, {})", cx, cy);
        }
    }

    #[test]
    fn bezier_hit_test_handle() {
        let mut editor = BezierCurveEditor::new(Rect::new(0, 0, 300, 300));
        editor.set_control_point1(0.25, 0.1);
        editor.set_control_point2(0.75, 0.9);

        // The handle positions depend on margin (12) and draw area.
        // CP1: x=12+0.25*276=81, y=12+(1-0.1)*276=12+248.4=260
        // Let's just check the function returns Some for positions near the curve.
        let cp1_pixel = editor.curve_to_pixel(0.25, 0.1);
        let hit = editor.hit_test_handle(cp1_pixel);
        assert_eq!(hit, Some(DragTarget::ControlPoint1));

        let cp2_pixel = editor.curve_to_pixel(0.75, 0.9);
        let hit = editor.hit_test_handle(cp2_pixel);
        assert_eq!(hit, Some(DragTarget::ControlPoint2));

        // Far away from any handle.
        let hit = editor.hit_test_handle(Point::new(5, 5));
        assert_eq!(hit, None);
    }

    #[test]
    fn bezier_drag_control_point1() {
        let mut editor = BezierCurveEditor::new(Rect::new(0, 0, 300, 300));
        let cp1_pixel = editor.curve_to_pixel(0.25, 0.1);

        // Mouse press on CP1.
        editor.handle_event(&Event::MousePress { pos: cp1_pixel, button: 1 });
        assert!(editor.base.is_mouse_pressed());

        // Drag to a new position.
        let new_pixel = editor.curve_to_pixel(0.5, 0.5);
        editor.handle_event(&Event::MouseMove { pos: new_pixel });

        let (cx, cy) = editor.control_point1();
        assert!((cx - 0.5).abs() < 0.02);
        assert!((cy - 0.5).abs() < 0.02);

        // Release.
        editor.handle_event(&Event::MouseRelease { pos: new_pixel, button: 1 });
        assert!(!editor.base.is_mouse_pressed());
    }

    #[test]
    fn bezier_disabled_blocks_events() {
        let mut editor = default_editor();
        editor.set_enabled(false);
        editor.handle_event(&Event::MousePress { pos: Point::new(100, 100), button: 1 });
        assert!(!editor.base.is_mouse_pressed());
    }

    #[test]
    fn bezier_cubic_bezier_endpoints() {
        // At t=0, the result must equal p0.
        let (x, y) =
            BezierCurveEditor::cubic_bezier(0.0, (0.1, 0.2), (0.3, 0.4), (0.5, 0.6), (0.7, 0.8));
        assert!((x - 0.1).abs() < 0.001);
        assert!((y - 0.2).abs() < 0.001);

        // At t=1, the result must equal p3.
        let (x, y) =
            BezierCurveEditor::cubic_bezier(1.0, (0.1, 0.2), (0.3, 0.4), (0.5, 0.6), (0.7, 0.8));
        assert!((x - 0.7).abs() < 0.001);
        assert!((y - 0.8).abs() < 0.001);
    }

    #[test]
    fn bezier_svg_output() {
        let mut editor = BezierCurveEditor::new(Rect::new(0, 0, 300, 300));
        let svg = crate::widget::svg::render_to_svg(&mut editor);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }

    /// The pointer reaching a handle has to reach the *base* too, or the theme's
    /// `"bezier_curve_editor:hover"` entry is a key nothing can spell.
    ///
    /// Regression: this handler forwarded to the base only in its catch-all arm, so every
    /// event it actually consumed — press, release, move, leave — never recorded the
    /// pointer fact. `widget_state()` therefore answered `Normal` for the whole drag, which
    /// is the one moment a curve editor's feedback matters most.
    #[test]
    fn bezier_pointer_state_reaches_the_base() {
        use crate::style::WidgetState;

        let mut editor = default_editor();
        let rect = editor.geometry();
        editor.handle_event(&Event::MouseEnter { pos: Point::new(rect.x, rect.y) });
        assert_eq!(
            editor.widget_state(),
            WidgetState::Hover,
            "the base must have been told the pointer arrived"
        );
        editor.handle_event(&Event::MouseEnter { pos: Point::new(rect.x, rect.y) });
        let cp1_pixel = editor.curve_to_pixel(0.25, 0.1);
        editor.handle_event(&Event::MousePress { pos: cp1_pixel, button: 1 });
        assert_eq!(
            editor.widget_state(),
            WidgetState::Pressed,
            "a drag must outrank a hover, and the base is what decides that"
        );
        editor.handle_event(&Event::MouseLeave { pos: Point::new(rect.x, rect.y) });
        assert!(!editor.base.is_hovered(), "leaving must clear the hover fact");
    }

    /// The handle under the pointer has to be *painted* differently, or `dragging` is a
    /// field that is written and announced but never read.
    ///
    /// Assertion is a relation between two renders, not a literal colour: the frame with a
    /// pointer over a handle must differ from the frame without one, and both must still be
    /// a valid document. That is exactly what the defect (a stored-and-unread field) broke.
    #[test]
    fn the_handle_under_the_pointer_is_emphasised() {
        // Holds the crate-wide theme guard: this test renders, and a concurrent
        // test that switches the appearance would otherwise change a later frame.
        let _theme_guard = crate::style::theme_test_guard();
        let mut editor = BezierCurveEditor::new(Rect::new(0, 0, 300, 300));
        let idle = crate::widget::svg::render_to_svg(&mut editor);

        let cp1_pixel = editor.curve_to_pixel(0.25, 0.1);
        editor.handle_event(&Event::MouseMove { pos: cp1_pixel });
        assert_eq!(editor.hovered_handle, Some(DragTarget::ControlPoint1));
        let hovered = crate::widget::svg::render_to_svg(&mut editor);
        assert_ne!(
            idle, hovered,
            "a handle under the pointer must render differently from an idle one"
        );

        // Away from every handle the emphasis has to clear again, or the last handle the
        // pointer crossed stays lit forever — the `hovered_row` mistake `list_view` made.
        editor.handle_event(&Event::MouseMove { pos: Point::new(5, 5) });
        assert_eq!(editor.hovered_handle, None);
        let cleared = crate::widget::svg::render_to_svg(&mut editor);
        assert_eq!(cleared, idle, "moving off every handle must restore the idle frame");
    }
}