agg-gui 0.2.0

Immediate-mode Rust GUI library with AGG rendering, Y-up layout, widgets, text, SVG, and native/WASM adapters
Documentation
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
//! `ToggleSwitch` — an iOS-style pill-shaped boolean toggle widget.
//!
//! Renders as a rounded-rectangle (pill) with a sliding white circle inside.
//! The pill is gray when off and blue when on.  Supports keyboard activation
//! (Space / Enter) and an optional shared [`Cell<bool>`] for two-way binding
//! with external state.

use std::cell::Cell;
use std::rc::Rc;

use crate::color::Color;
use crate::draw_ctx::DrawCtx;
use crate::event::{Event, EventResult, Key, MouseButton};
use crate::geometry::{Rect, Size};
use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
use crate::widget::Widget;

// ── Geometry constants ─────────────────────────────────────────────────────
//
// Sized to fit within a typical 16-18 px text line (13-14 px font) so the
// switch sits flush beside a label without inflating the row height.

const PILL_W: f64 = 32.0;
const PILL_H: f64 = 18.0;
/// Corner radius of the pill — a full semicircle on each end.
const PILL_R: f64 = PILL_H / 2.0;
/// Gap between the pill edge and the circle edge.
const CIRCLE_MARGIN: f64 = 2.5;
/// Circle radius derived from pill height and the margin.
const CIRCLE_R: f64 = PILL_H / 2.0 - CIRCLE_MARGIN;
/// Duration of the on/off slide animation in seconds.
const ANIM_SECS: f64 = 0.14;
/// Inset on each side between the widget's outer bounds and the pill
/// geometry.  The halo-AA pipeline extrudes the pill's filled edges one
/// pixel outward; without a margin that halo sits outside the widget's
/// own bounds and gets clipped by the parent's `clip_rect(0, 0, w, h)` —
/// the bottom edge loses its AA fade and looks flat-cut.  One pixel is
/// enough to keep the full halo inside the clip.
const PILL_HALO: f64 = 1.0;

// ── Press-ring overlay ───────────────────────────────────────────────────
//
// Matches MatterCAD's `RoundedToggleSwitch`: on mouse-down a translucent
// disc centred on the toggle circle expands outward; on mouse-up it fades
// back.  The MatterCAD version used a radius ratio of ~2.44× the circle
// radius (22 vs 9 px) and ~50/255 alpha with quadratic ease-out.

/// Maximum radius of the press-ring overlay (~2.4× the circle radius).
const RING_MAX_R: f64 = CIRCLE_R * 2.4;
/// Peak alpha of the press-ring at full expansion.
const RING_PEAK_ALPHA: f32 = 0.20;
/// Duration of the press-ring expand / retract animation in seconds.
const RING_ANIM_SECS: f64 = 0.22;

// Colors are resolved from ctx.visuals() at paint time.

// ── Struct ─────────────────────────────────────────────────────────────────

/// Inspector-visible properties of a [`ToggleSwitch`].
#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
#[derive(Clone, Debug, Default)]
pub struct ToggleSwitchProps {
    /// Internal on/off state, used when `state_cell` is `None`.
    pub on: bool,
}

/// An iOS-style boolean toggle.
///
/// Displays a pill-shaped background that switches from gray (off) to blue (on)
/// with a white circle that slides to the opposite end.
pub struct ToggleSwitch {
    bounds: Rect,
    children: Vec<Box<dyn Widget>>, // always empty
    base: WidgetBase,
    pub props: ToggleSwitchProps,
    /// When set, this cell is the authoritative state; `paint` reads from it
    /// and `toggle` writes to it so external changes are reflected immediately.
    state_cell: Option<Rc<Cell<bool>>>,
    hovered: bool,
    /// Interpolates between 0.0 (off) and 1.0 (on) for smooth colour/circle
    /// position transitions; driven by `animation::Tween`.
    anim: crate::animation::Tween,
    pressed: bool,
    /// Interpolates 0.0 → 1.0 while the mouse is pressed (ring expand) and
    /// back to 0.0 on release (ring fade).  Mirrors MatterCAD's
    /// `RoundedToggleSwitch` ripple overlay.
    press_anim: crate::animation::Tween,
    on_change: Option<Box<dyn FnMut(bool)>>,
}

// ── Constructors & builder methods ─────────────────────────────────────────

impl ToggleSwitch {
    /// Create a new toggle switch with an initial on/off state.
    pub fn new(on: bool) -> Self {
        let initial = if on { 1.0 } else { 0.0 };
        Self {
            bounds: Rect::default(),
            children: Vec::new(),
            base: WidgetBase::new(),
            props: ToggleSwitchProps { on },
            state_cell: None,
            hovered: false,
            anim: crate::animation::Tween::new(initial, ANIM_SECS),
            pressed: false,
            press_anim: crate::animation::Tween::new(0.0, RING_ANIM_SECS),
            on_change: None,
        }
    }

    /// Bind the toggle state to a shared [`Cell<bool>`].
    ///
    /// When set, `paint` reads from the cell (so external writes are reflected
    /// immediately) and `toggle` writes to it in both directions.
    pub fn with_state_cell(mut self, cell: Rc<Cell<bool>>) -> Self {
        self.state_cell = Some(cell);
        self
    }

    /// Register a callback invoked with the new state whenever the switch
    /// is toggled.
    pub fn on_change(mut self, cb: impl FnMut(bool) + 'static) -> Self {
        self.on_change = Some(Box::new(cb));
        self
    }

    pub fn with_margin(mut self, m: Insets) -> Self {
        self.base.margin = m;
        self
    }
    pub fn with_h_anchor(mut self, h: HAnchor) -> Self {
        self.base.h_anchor = h;
        self
    }
    pub fn with_v_anchor(mut self, v: VAnchor) -> Self {
        self.base.v_anchor = v;
        self
    }
    pub fn with_min_size(mut self, s: Size) -> Self {
        self.base.min_size = s;
        self
    }
    pub fn with_max_size(mut self, s: Size) -> Self {
        self.base.max_size = s;
        self
    }

    // ── State accessors ────────────────────────────────────────────────────

    /// Returns the authoritative on/off state: the cell value if bound,
    /// otherwise the internal `on` field.
    pub fn is_on(&self) -> bool {
        if let Some(ref cell) = self.state_cell {
            cell.get()
        } else {
            self.props.on
        }
    }

    // ── Internal helpers ───────────────────────────────────────────────────

    fn toggle(&mut self) {
        let new_val = !self.is_on();
        self.props.on = new_val;
        if let Some(ref cell) = self.state_cell {
            cell.set(new_val);
        }
        if let Some(cb) = self.on_change.as_mut() {
            cb(new_val);
        }
    }

    /// X-center of the sliding circle given an interpolated position `t`
    /// in `[0, 1]` (0 = off, 1 = on).  Expressed in widget-local coords,
    /// so the `PILL_HALO` inset is baked in — callers don't need to know
    /// about it.
    fn circle_cx_at(t: f64) -> f64 {
        let x_off = PILL_HALO + CIRCLE_MARGIN + CIRCLE_R;
        let x_on = PILL_HALO + PILL_W - CIRCLE_MARGIN - CIRCLE_R;
        x_off + (x_on - x_off) * t.clamp(0.0, 1.0)
    }
}

/// Linear interpolation between two colours, component-wise.
fn lerp_color(a: Color, b: Color, t: f32) -> Color {
    let t = t.clamp(0.0, 1.0);
    Color::rgba(
        a.r + (b.r - a.r) * t,
        a.g + (b.g - a.g) * t,
        a.b + (b.b - a.b) * t,
        a.a + (b.a - a.a) * t,
    )
}

// ── Widget impl ────────────────────────────────────────────────────────────

impl Widget for ToggleSwitch {
    fn type_name(&self) -> &'static str {
        "ToggleSwitch"
    }

    fn bounds(&self) -> Rect {
        self.bounds
    }
    fn set_bounds(&mut self, b: Rect) {
        self.bounds = b;
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.children
    }
    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
        &mut self.children
    }

    #[cfg(feature = "reflect")]
    fn as_reflect(&self) -> Option<&dyn bevy_reflect::Reflect> {
        Some(&self.props)
    }
    #[cfg(feature = "reflect")]
    fn as_reflect_mut(&mut self) -> Option<&mut dyn bevy_reflect::Reflect> {
        Some(&mut self.props)
    }
    fn is_focusable(&self) -> bool {
        true
    }

    fn margin(&self) -> Insets {
        self.base.margin
    }
    fn widget_base(&self) -> Option<&WidgetBase> {
        Some(&self.base)
    }
    fn widget_base_mut(&mut self) -> Option<&mut WidgetBase> {
        Some(&mut self.base)
    }
    fn h_anchor(&self) -> HAnchor {
        self.base.h_anchor
    }
    fn v_anchor(&self) -> VAnchor {
        self.base.v_anchor
    }
    fn min_size(&self) -> Size {
        self.base.min_size
    }
    fn max_size(&self) -> Size {
        self.base.max_size
    }

    /// Always returns the fixed pill size (plus a 1 px halo margin on
    /// every side); the available space is ignored.  See [`PILL_HALO`]
    /// for why the margin is needed.
    fn layout(&mut self, _available: Size) -> Size {
        Size::new(PILL_W + 2.0 * PILL_HALO, PILL_H + 2.0 * PILL_HALO)
    }

    fn needs_draw(&self) -> bool {
        if !self.is_visible() {
            return false;
        }
        self.anim.is_animating()
            || self.press_anim.is_animating()
            || self.children().iter().any(|c| c.needs_draw())
    }

    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
        let v = ctx.visuals();

        // Retarget the tween each paint so external state-cell writes are
        // picked up (e.g. a checkbox-style binding toggled from outside), then
        // advance it to get this frame's interpolated position.
        self.anim.set_target(if self.is_on() { 1.0 } else { 0.0 });
        let t = self.anim.tick();

        // Inset the pill by the halo margin so halo-AA has room inside
        // the widget's own clip.  Origin (0,0) is the widget's bottom-
        // left in Y-up; the framework has already translated there.
        let pill_x = PILL_HALO;
        let pill_y = PILL_HALO;

        // ── Pill background ────────────────────────────────────────────────
        // Interpolate between the off colour (gray) and the on colour (accent);
        // a separate hover tint is applied as a multiplicative brighten.
        let off_color = v.widget_stroke;
        let on_color = v.accent;
        let mut bg = lerp_color(off_color, on_color, t as f32);
        if self.hovered {
            let hover_off = v.widget_bg_hovered;
            let hover_on = v.accent_hovered;
            bg = lerp_color(hover_off, hover_on, t as f32);
        }
        ctx.set_fill_color(bg);
        ctx.begin_path();
        ctx.rounded_rect(pill_x, pill_y, PILL_W, PILL_H, PILL_R);
        ctx.fill();

        // ── Sliding white circle ───────────────────────────────────────────
        let cx = Self::circle_cx_at(t);
        let cy = PILL_HALO + PILL_H * 0.5;
        ctx.set_fill_color(Color::white());
        ctx.begin_path();
        ctx.circle(cx, cy, CIRCLE_R);
        ctx.fill();

        // The press-ring itself is drawn in `paint_overlay` — it needs to
        // expand beyond the widget's own bounds, which requires escaping the
        // parent-set clip that `paint` runs under.
    }

    fn paint_overlay(&mut self, ctx: &mut dyn DrawCtx) {
        // ── Press-ring overlay (ripple) ────────────────────────────────────
        // Translucent disc centred on the toggle circle.  At full expansion
        // the ring is ~2.4× the circle radius and would be cropped by the
        // pill-sized widget clip if drawn in `paint()`.  We therefore draw it
        // in `paint_overlay` and temporarily lift the parent's clip via
        // `reset_clip` so the ring can render the full ripple geometry (then
        // `restore` puts the saved clip state back before returning).
        let ring_t = self.press_anim.tick();
        if ring_t <= 0.001 {
            return;
        }

        let v = ctx.visuals();
        let cx = Self::circle_cx_at(self.anim.value());
        let cy = PILL_HALO + PILL_H * 0.5;
        let toggle_color = if self.is_on() {
            v.accent
        } else {
            v.widget_stroke
        };
        let alpha = RING_PEAK_ALPHA * (ring_t as f32);

        ctx.save();
        ctx.reset_clip();
        ctx.set_fill_color(Color::rgba(
            toggle_color.r,
            toggle_color.g,
            toggle_color.b,
            alpha,
        ));
        ctx.begin_path();
        ctx.circle(cx, cy, RING_MAX_R * ring_t);
        ctx.fill();
        ctx.restore();
    }

    fn on_event(&mut self, event: &Event) -> EventResult {
        match event {
            Event::MouseMove { pos } => {
                let was = self.hovered;
                self.hovered = self.hit_test(*pos);
                if was != self.hovered {
                    crate::animation::request_draw();
                    return EventResult::Consumed;
                }
                EventResult::Ignored
            }
            Event::MouseDown {
                button: MouseButton::Left,
                ..
            } => {
                // Consume on down so the widget "captures" the gesture, and
                // start the press-ring expand animation.
                self.pressed = true;
                self.press_anim.set_target(1.0);
                crate::animation::request_draw();
                EventResult::Consumed
            }
            Event::MouseUp {
                button: MouseButton::Left,
                pos,
                ..
            } => {
                if self.hit_test(*pos) {
                    self.toggle();
                }
                // Ring fades back out whether or not the release landed on us.
                self.pressed = false;
                self.press_anim.set_target(0.0);
                crate::animation::request_draw();
                EventResult::Consumed
            }
            Event::KeyDown {
                key: Key::Char(' '),
                ..
            }
            | Event::KeyDown {
                key: Key::Enter, ..
            } => {
                self.toggle();
                crate::animation::request_draw();
                EventResult::Consumed
            }
            _ => EventResult::Ignored,
        }
    }

    /// Hit test restricted to the pill bounds (matches the visible shape).
    /// The halo margin is excluded so the ~1 px ring around the pill
    /// doesn't register as pointer-over.
    fn hit_test(&self, local_pos: crate::geometry::Point) -> bool {
        local_pos.x >= PILL_HALO
            && local_pos.x <= PILL_HALO + PILL_W
            && local_pos.y >= PILL_HALO
            && local_pos.y <= PILL_HALO + PILL_H
    }
}