agg_gui/widgets/toggle_switch.rs
1//! `ToggleSwitch` — an iOS-style pill-shaped boolean toggle widget.
2//!
3//! Renders as a rounded-rectangle (pill) with a sliding white circle inside.
4//! The pill is gray when off and blue when on. Supports keyboard activation
5//! (Space / Enter) and an optional shared [`Cell<bool>`] for two-way binding
6//! with external state.
7
8use std::cell::Cell;
9use std::rc::Rc;
10
11use crate::color::Color;
12use crate::draw_ctx::DrawCtx;
13use crate::event::{Event, EventResult, Key, MouseButton};
14use crate::geometry::{Rect, Size};
15use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
16use crate::widget::Widget;
17
18// ── Geometry constants ─────────────────────────────────────────────────────
19//
20// Sized to fit within a typical 16-18 px text line (13-14 px font) so the
21// switch sits flush beside a label without inflating the row height.
22
23const PILL_W: f64 = 32.0;
24const PILL_H: f64 = 18.0;
25/// Corner radius of the pill — a full semicircle on each end.
26const PILL_R: f64 = PILL_H / 2.0;
27/// Gap between the pill edge and the circle edge.
28const CIRCLE_MARGIN: f64 = 2.5;
29/// Circle radius derived from pill height and the margin.
30const CIRCLE_R: f64 = PILL_H / 2.0 - CIRCLE_MARGIN;
31/// Duration of the on/off slide animation in seconds.
32const ANIM_SECS: f64 = 0.14;
33/// Inset on each side between the widget's outer bounds and the pill
34/// geometry. The halo-AA pipeline extrudes the pill's filled edges one
35/// pixel outward; without a margin that halo sits outside the widget's
36/// own bounds and gets clipped by the parent's `clip_rect(0, 0, w, h)` —
37/// the bottom edge loses its AA fade and looks flat-cut. One pixel is
38/// enough to keep the full halo inside the clip.
39const PILL_HALO: f64 = 1.0;
40
41// ── Press-ring overlay ───────────────────────────────────────────────────
42//
43// Matches MatterCAD's `RoundedToggleSwitch`: on mouse-down a translucent
44// disc centred on the toggle circle expands outward; on mouse-up it fades
45// back. The MatterCAD version used a radius ratio of ~2.44× the circle
46// radius (22 vs 9 px) and ~50/255 alpha with quadratic ease-out.
47
48/// Maximum radius of the press-ring overlay (~2.4× the circle radius).
49const RING_MAX_R: f64 = CIRCLE_R * 2.4;
50/// Peak alpha of the press-ring at full expansion.
51const RING_PEAK_ALPHA: f32 = 0.20;
52/// Duration of the press-ring expand / retract animation in seconds.
53const RING_ANIM_SECS: f64 = 0.22;
54
55// Colors are resolved from ctx.visuals() at paint time.
56
57// ── Struct ─────────────────────────────────────────────────────────────────
58
59/// An iOS-style boolean toggle.
60///
61/// Displays a pill-shaped background that switches from gray (off) to blue (on)
62/// with a white circle that slides to the opposite end.
63pub struct ToggleSwitch {
64 bounds: Rect,
65 children: Vec<Box<dyn Widget>>, // always empty
66 base: WidgetBase,
67 /// Internal on/off state, used when `state_cell` is `None`.
68 on: bool,
69 /// When set, this cell is the authoritative state; `paint` reads from it
70 /// and `toggle` writes to it so external changes are reflected immediately.
71 state_cell: Option<Rc<Cell<bool>>>,
72 hovered: bool,
73 /// Interpolates between 0.0 (off) and 1.0 (on) for smooth colour/circle
74 /// position transitions; driven by `animation::Tween`.
75 anim: crate::animation::Tween,
76 /// Interpolates 0.0 → 1.0 while the mouse is pressed (ring expand) and
77 /// back to 0.0 on release (ring fade). Mirrors MatterCAD's
78 /// `RoundedToggleSwitch` ripple overlay.
79 press_anim: crate::animation::Tween,
80 on_change: Option<Box<dyn FnMut(bool)>>,
81}
82
83// ── Constructors & builder methods ─────────────────────────────────────────
84
85impl ToggleSwitch {
86 /// Create a new toggle switch with an initial on/off state.
87 pub fn new(on: bool) -> Self {
88 let initial = if on { 1.0 } else { 0.0 };
89 Self {
90 bounds: Rect::default(),
91 children: Vec::new(),
92 base: WidgetBase::new(),
93 on,
94 state_cell: None,
95 hovered: false,
96 anim: crate::animation::Tween::new(initial, ANIM_SECS),
97 press_anim: crate::animation::Tween::new(0.0, RING_ANIM_SECS),
98 on_change: None,
99 }
100 }
101
102 /// Bind the toggle state to a shared [`Cell<bool>`].
103 ///
104 /// When set, `paint` reads from the cell (so external writes are reflected
105 /// immediately) and `toggle` writes to it in both directions.
106 pub fn with_state_cell(mut self, cell: Rc<Cell<bool>>) -> Self {
107 self.state_cell = Some(cell);
108 self
109 }
110
111 /// Register a callback invoked with the new state whenever the switch
112 /// is toggled.
113 pub fn on_change(mut self, cb: impl FnMut(bool) + 'static) -> Self {
114 self.on_change = Some(Box::new(cb));
115 self
116 }
117
118 pub fn with_margin(mut self, m: Insets) -> Self { self.base.margin = m; self }
119 pub fn with_h_anchor(mut self, h: HAnchor) -> Self { self.base.h_anchor = h; self }
120 pub fn with_v_anchor(mut self, v: VAnchor) -> Self { self.base.v_anchor = v; self }
121 pub fn with_min_size(mut self, s: Size) -> Self { self.base.min_size = s; self }
122 pub fn with_max_size(mut self, s: Size) -> Self { self.base.max_size = s; self }
123
124 // ── State accessors ────────────────────────────────────────────────────
125
126 /// Returns the authoritative on/off state: the cell value if bound,
127 /// otherwise the internal `on` field.
128 pub fn is_on(&self) -> bool {
129 if let Some(ref cell) = self.state_cell { cell.get() } else { self.on }
130 }
131
132 // ── Internal helpers ───────────────────────────────────────────────────
133
134 fn toggle(&mut self) {
135 let new_val = !self.is_on();
136 self.on = new_val;
137 if let Some(ref cell) = self.state_cell { cell.set(new_val); }
138 if let Some(cb) = self.on_change.as_mut() { cb(new_val); }
139 }
140
141 /// X-center of the sliding circle given an interpolated position `t`
142 /// in `[0, 1]` (0 = off, 1 = on). Expressed in widget-local coords,
143 /// so the `PILL_HALO` inset is baked in — callers don't need to know
144 /// about it.
145 fn circle_cx_at(t: f64) -> f64 {
146 let x_off = PILL_HALO + CIRCLE_MARGIN + CIRCLE_R;
147 let x_on = PILL_HALO + PILL_W - CIRCLE_MARGIN - CIRCLE_R;
148 x_off + (x_on - x_off) * t.clamp(0.0, 1.0)
149 }
150}
151
152/// Linear interpolation between two colours, component-wise.
153fn lerp_color(a: Color, b: Color, t: f32) -> Color {
154 let t = t.clamp(0.0, 1.0);
155 Color::rgba(
156 a.r + (b.r - a.r) * t,
157 a.g + (b.g - a.g) * t,
158 a.b + (b.b - a.b) * t,
159 a.a + (b.a - a.a) * t,
160 )
161}
162
163// ── Widget impl ────────────────────────────────────────────────────────────
164
165impl Widget for ToggleSwitch {
166 fn type_name(&self) -> &'static str { "ToggleSwitch" }
167
168 fn bounds(&self) -> Rect { self.bounds }
169 fn set_bounds(&mut self, b: Rect) { self.bounds = b; }
170 fn children(&self) -> &[Box<dyn Widget>] { &self.children }
171 fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> { &mut self.children }
172
173 fn is_focusable(&self) -> bool { true }
174
175 fn margin(&self) -> Insets { self.base.margin }
176 fn h_anchor(&self) -> HAnchor { self.base.h_anchor }
177 fn v_anchor(&self) -> VAnchor { self.base.v_anchor }
178 fn min_size(&self) -> Size { self.base.min_size }
179 fn max_size(&self) -> Size { self.base.max_size }
180
181 /// Always returns the fixed pill size (plus a 1 px halo margin on
182 /// every side); the available space is ignored. See [`PILL_HALO`]
183 /// for why the margin is needed.
184 fn layout(&mut self, _available: Size) -> Size {
185 Size::new(PILL_W + 2.0 * PILL_HALO, PILL_H + 2.0 * PILL_HALO)
186 }
187
188 fn paint(&mut self, ctx: &mut dyn DrawCtx) {
189 let v = ctx.visuals();
190
191 // Retarget the tween each paint so external state-cell writes are
192 // picked up (e.g. a checkbox-style binding toggled from outside), then
193 // advance it to get this frame's interpolated position.
194 self.anim.set_target(if self.is_on() { 1.0 } else { 0.0 });
195 let t = self.anim.tick();
196
197 // Inset the pill by the halo margin so halo-AA has room inside
198 // the widget's own clip. Origin (0,0) is the widget's bottom-
199 // left in Y-up; the framework has already translated there.
200 let pill_x = PILL_HALO;
201 let pill_y = PILL_HALO;
202
203 // ── Pill background ────────────────────────────────────────────────
204 // Interpolate between the off colour (gray) and the on colour (accent);
205 // a separate hover tint is applied as a multiplicative brighten.
206 let off_color = v.widget_stroke;
207 let on_color = v.accent;
208 let mut bg = lerp_color(off_color, on_color, t as f32);
209 if self.hovered {
210 let hover_off = v.widget_bg_hovered;
211 let hover_on = v.accent_hovered;
212 bg = lerp_color(hover_off, hover_on, t as f32);
213 }
214 ctx.set_fill_color(bg);
215 ctx.begin_path();
216 ctx.rounded_rect(pill_x, pill_y, PILL_W, PILL_H, PILL_R);
217 ctx.fill();
218
219 // ── Sliding white circle ───────────────────────────────────────────
220 let cx = Self::circle_cx_at(t);
221 let cy = PILL_HALO + PILL_H * 0.5;
222 ctx.set_fill_color(Color::white());
223 ctx.begin_path();
224 ctx.circle(cx, cy, CIRCLE_R);
225 ctx.fill();
226
227 // The press-ring itself is drawn in `paint_overlay` — it needs to
228 // expand beyond the widget's own bounds, which requires escaping the
229 // parent-set clip that `paint` runs under.
230 }
231
232 fn paint_overlay(&mut self, ctx: &mut dyn DrawCtx) {
233 // ── Press-ring overlay (ripple) ────────────────────────────────────
234 // Translucent disc centred on the toggle circle. At full expansion
235 // the ring is ~2.4× the circle radius and would be cropped by the
236 // pill-sized widget clip if drawn in `paint()`. We therefore draw it
237 // in `paint_overlay` and temporarily lift the parent's clip via
238 // `reset_clip` so the ring can render the full ripple geometry (then
239 // `restore` puts the saved clip state back before returning).
240 let ring_t = self.press_anim.tick();
241 if ring_t <= 0.001 { return; }
242
243 let v = ctx.visuals();
244 let cx = Self::circle_cx_at(self.anim.value());
245 let cy = PILL_HALO + PILL_H * 0.5;
246 let toggle_color = if self.is_on() { v.accent } else { v.widget_stroke };
247 let alpha = RING_PEAK_ALPHA * (ring_t as f32);
248
249 ctx.save();
250 ctx.reset_clip();
251 ctx.set_fill_color(Color::rgba(
252 toggle_color.r, toggle_color.g, toggle_color.b, alpha));
253 ctx.begin_path();
254 ctx.circle(cx, cy, RING_MAX_R * ring_t);
255 ctx.fill();
256 ctx.restore();
257 }
258
259 fn on_event(&mut self, event: &Event) -> EventResult {
260 match event {
261 Event::MouseMove { pos } => {
262 let was = self.hovered;
263 self.hovered = self.hit_test(*pos);
264 if was != self.hovered { crate::animation::request_tick(); }
265 EventResult::Ignored
266 }
267 Event::MouseDown { button: MouseButton::Left, .. } => {
268 // Consume on down so the widget "captures" the gesture, and
269 // start the press-ring expand animation.
270 self.press_anim.set_target(1.0);
271 crate::animation::request_tick();
272 EventResult::Consumed
273 }
274 Event::MouseUp { button: MouseButton::Left, pos, .. } => {
275 if self.hit_test(*pos) { self.toggle(); }
276 // Ring fades back out whether or not the release landed on us.
277 self.press_anim.set_target(0.0);
278 crate::animation::request_tick();
279 EventResult::Consumed
280 }
281 Event::KeyDown { key: Key::Char(' '), .. }
282 | Event::KeyDown { key: Key::Enter, .. } => {
283 self.toggle();
284 crate::animation::request_tick();
285 EventResult::Consumed
286 }
287 _ => EventResult::Ignored,
288 }
289 }
290
291 /// Hit test restricted to the pill bounds (matches the visible shape).
292 /// The halo margin is excluded so the ~1 px ring around the pill
293 /// doesn't register as pointer-over.
294 fn hit_test(&self, local_pos: crate::geometry::Point) -> bool {
295 local_pos.x >= PILL_HALO && local_pos.x <= PILL_HALO + PILL_W
296 && local_pos.y >= PILL_HALO && local_pos.y <= PILL_HALO + PILL_H
297 }
298}