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
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
//! `Slider` — a horizontal range slider with a draggable thumb.

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

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::text::Font;
use crate::widget::{paint_subtree, Widget};
use crate::widgets::label::{Label, LabelAlign};

const TRACK_H: f64 = 4.0;
const THUMB_R: f64 = 7.0;
/// Total widget height.  Needs to fit the thumb (diameter `2 * THUMB_R`)
/// plus a little breathing room for the focus ring — `22 px` keeps rows
/// compact in settings-style panels while still being easy to grab.
const WIDGET_H: f64 = 22.0;
/// Default pixel budget reserved on the right for the numeric value
/// label.  Wide enough for 4-5 glyphs at the slider's default font
/// size.  Set to `0.0` via [`Slider::with_show_value(false)`] to hide.
const VALUE_W: f64 = 44.0;
/// Gap between the track's right edge and the value label's left edge.
const VALUE_GAP: f64 = 6.0;

/// Inspector-visible properties of a [`Slider`].
///
/// **The "companion props" pattern:** widgets that opt into the reflection-
/// driven inspector hold a small `*Props` struct exposing only their
/// directly-editable values.  This sidesteps two structural problems with
/// deriving `Reflect` on the whole widget:
///   1. `bevy_reflect::Reflect` requires `Send + Sync`, which widgets violate
///      because they carry `Rc<Cell<…>>` and non-`Sync` callbacks.
///   2. Sub-widgets (`Label` here) and `Arc<Font>` would force a cascading
///      `Reflect` derive across types that don't have it.
///
/// The companion struct contains plain values (`f64`, `bool`, `Option<usize>`)
/// — `Send + Sync + Reflect`-friendly — and the widget routes all reads/writes
/// through it.  The inspector edits the companion live and the widget reacts.
#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
#[derive(Clone, Debug)]
pub struct SliderProps {
    pub value: f64,
    pub min: f64,
    pub max: f64,
    pub step: f64,
    pub show_value: bool,
    /// Fixed decimals for the value label — overrides the step-based
    /// auto-format when `Some`.
    pub decimals: Option<usize>,
    pub font_size: f64,
}

impl Default for SliderProps {
    fn default() -> Self {
        Self {
            value: 0.0,
            min: 0.0,
            max: 1.0,
            step: 0.01,
            show_value: true,
            decimals: None,
            font_size: 12.0,
        }
    }
}

/// A horizontal slider for a `f64` value within `[min, max]`.
pub struct Slider {
    bounds: Rect,
    children: Vec<Box<dyn Widget>>, // always empty
    base: WidgetBase,
    /// Reflectable, inspector-editable values — see [`SliderProps`].
    pub props: SliderProps,
    dragging: bool,
    focused: bool,
    hovered: bool,
    on_change: Option<Box<dyn FnMut(f64)>>,
    /// Optional external mirror of `value`.  When `Some`, `layout()` re-reads
    /// the cell every frame so a second widget that writes the same cell
    /// drives this slider live; `set_value` writes back.  Mirrors the
    /// `ToggleSwitch::with_state_cell` pattern — the cell is the source-of-
    /// truth so multiple widgets can reflect the same value bidirectionally.
    value_cell: Option<Rc<Cell<f64>>>,
    /// Backbuffered Label that renders the numeric value.  Updated in
    /// `layout()` with the current formatted value so the text follows
    /// drags live.
    value_label: Label,
    /// Tracks the string last pushed into `value_label` so we only
    /// invalidate its cache when the displayed value actually changes.
    last_value_text: String,
}

impl Slider {
    pub fn new(value: f64, min: f64, max: f64, font: Arc<Font>) -> Self {
        let v = value.clamp(min, max);
        let font_size = 12.0;
        let value_label = Label::new("", Arc::clone(&font))
            .with_font_size(font_size)
            .with_align(LabelAlign::Right);
        Self {
            bounds: Rect::default(),
            children: Vec::new(),
            base: WidgetBase::new(),
            props: SliderProps {
                value: v,
                min,
                max,
                step: (max - min) / 100.0,
                show_value: true,
                decimals: None,
                font_size,
            },
            dragging: false,
            focused: false,
            hovered: false,
            on_change: None,
            value_cell: None,
            value_label,
            last_value_text: String::new(),
        }
    }

    pub fn with_step(mut self, step: f64) -> Self {
        self.props.step = step;
        self
    }

    /// Bind this slider's value to an external `Rc<Cell<f64>>`.
    ///
    /// The cell becomes the source-of-truth: `layout()` reads it every
    /// frame so any other widget (or code path) that writes the cell
    /// will drive this slider live; drag interactions here write back
    /// to the cell too.  Pattern mirrors `ToggleSwitch::with_state_cell`.
    pub fn with_value_cell(mut self, cell: Rc<Cell<f64>>) -> Self {
        self.props.value = cell.get().clamp(self.props.min, self.props.max);
        self.value_cell = Some(cell);
        self
    }
    pub fn with_show_value(mut self, show: bool) -> Self {
        self.props.show_value = show;
        self
    }

    /// Force a specific decimal count for the numeric value label.  When
    /// unset, the format falls back to a heuristic based on `step`.
    pub fn with_decimals(mut self, decimals: usize) -> Self {
        self.props.decimals = Some(decimals);
        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
    }

    pub fn on_change(mut self, cb: impl FnMut(f64) + 'static) -> Self {
        self.on_change = Some(Box::new(cb));
        self
    }

    pub fn value(&self) -> f64 {
        self.props.value
    }

    pub fn set_value(&mut self, v: f64) {
        self.props.value = v.clamp(self.props.min, self.props.max);
        if let Some(cell) = &self.value_cell {
            cell.set(self.props.value);
        }
    }

    fn fire(&mut self) {
        let v = self.props.value;
        if let Some(cell) = &self.value_cell {
            cell.set(v);
        }
        if let Some(cb) = self.on_change.as_mut() {
            cb(v);
        }
    }

    /// Pixel X of the track's right edge.  The value label (when shown)
    /// lives in a reserved strip to the right of this, outside the track
    /// so a thumb at max doesn't overdraw the digits.
    fn track_right(&self) -> f64 {
        let reserved = if self.props.show_value {
            VALUE_W + VALUE_GAP
        } else {
            0.0
        };
        (self.bounds.width - reserved - THUMB_R).max(THUMB_R + 1.0)
    }

    /// Pixel X of the thumb center within the track area.
    fn thumb_x(&self) -> f64 {
        let track_left = THUMB_R;
        let track_right = self.track_right();
        let t = if self.props.max > self.props.min {
            (self.props.value - self.props.min) / (self.props.max - self.props.min)
        } else {
            0.0
        };
        track_left + t * (track_right - track_left)
    }

    fn value_from_x(&self, x: f64) -> f64 {
        let track_left = THUMB_R;
        let track_right = self.track_right();
        let t = ((x - track_left) / (track_right - track_left)).clamp(0.0, 1.0);
        let raw = self.props.min + t * (self.props.max - self.props.min);
        // Snap to step
        let snapped = (raw / self.props.step).round() * self.props.step;
        snapped.clamp(self.props.min, self.props.max)
    }

    /// Format the slider's value using `decimals` if set, otherwise heuristic
    /// based on `step`.
    fn format_value(&self) -> String {
        if let Some(d) = self.props.decimals {
            return format!("{:.*}", d, self.props.value);
        }
        if self.props.step >= 1.0 {
            format!("{:.0}", self.props.value)
        } else if self.props.step >= 0.1 {
            format!("{:.1}", self.props.value)
        } else if self.props.step >= 0.01 {
            format!("{:.2}", self.props.value)
        } else {
            format!("{:.3}", self.props.value)
        }
    }
}

impl Widget for Slider {
    fn type_name(&self) -> &'static str {
        "Slider"
    }
    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
    }

    fn layout(&mut self, available: Size) -> Size {
        // Re-read external cell every frame — another widget (e.g. the
        // System window's slider) may have written a new value.  Skip
        // while dragging so the user's in-flight drag isn't fought
        // back by rounding inside the source cell.
        if !self.dragging {
            if let Some(cell) = &self.value_cell {
                self.props.value = cell.get().clamp(self.props.min, self.props.max);
            }
        }

        // Refresh the value-label text only when the displayed string
        // actually changed — Label's `set_text` invalidates its cache
        // so we want to skip this when the value is unchanged (e.g.
        // idle frames between drags).
        if self.props.show_value {
            let new_text = self.format_value();
            if new_text != self.last_value_text {
                self.value_label.set_text(new_text.clone());
                self.last_value_text = new_text;
            }
            // Size the label to exactly the reserved strip; right-align
            // anchors the digits to the widget's right edge.
            let lh = self.props.font_size * 1.5;
            let _ = self.value_label.layout(Size::new(VALUE_W, lh));
            self.value_label
                .set_bounds(Rect::new(0.0, 0.0, VALUE_W, lh));
        }

        Size::new(available.width, WIDGET_H)
    }

    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
        let v = ctx.visuals();
        let h = self.bounds.height;
        let cy = h * 0.5;

        let track_right = self.track_right();
        let track_w = (track_right - THUMB_R).max(0.0);

        // Track (background)
        ctx.set_fill_color(v.track_bg);
        ctx.begin_path();
        ctx.rounded_rect(THUMB_R, cy - TRACK_H * 0.5, track_w, TRACK_H, TRACK_H * 0.5);
        ctx.fill();

        // Track (filled portion up to thumb)
        let tx = self.thumb_x();
        if tx > THUMB_R {
            ctx.set_fill_color(v.accent);
            ctx.begin_path();
            ctx.rounded_rect(
                THUMB_R,
                cy - TRACK_H * 0.5,
                tx - THUMB_R,
                TRACK_H,
                TRACK_H * 0.5,
            );
            ctx.fill();
        }

        // Focus ring
        if self.focused {
            ctx.set_stroke_color(v.accent_focus);
            ctx.set_line_width(2.0);
            ctx.begin_path();
            ctx.circle(tx, cy, THUMB_R + 3.0);
            ctx.stroke();
        }

        // Thumb
        let thumb_color = if self.dragging || self.focused {
            v.accent_pressed
        } else if self.hovered {
            v.accent_hovered
        } else {
            v.accent
        };
        ctx.set_fill_color(thumb_color);
        ctx.begin_path();
        ctx.circle(tx, cy, THUMB_R);
        ctx.fill();

        ctx.set_fill_color(v.widget_bg);
        ctx.begin_path();
        ctx.circle(tx, cy, THUMB_R - 2.5);
        ctx.fill();

        // Value label — composed via backbuffered Label so it uses the
        // same text-raster path as every other label in the app.  The
        // Label is right-aligned inside its box and positioned in the
        // reserved strip to the right of the track.
        if self.props.show_value {
            self.value_label.set_color(v.text_color);
            let lb = self.value_label.bounds();
            let strip_left = track_right + VALUE_GAP;
            let ly = cy - lb.height * 0.5;
            self.value_label
                .set_bounds(Rect::new(strip_left, ly, lb.width, lb.height));
            ctx.save();
            ctx.translate(strip_left, ly);
            paint_subtree(&mut self.value_label, ctx);
            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 self.dragging {
                    self.props.value = self.value_from_x(pos.x);
                    self.fire();
                    crate::animation::request_draw();
                    return EventResult::Consumed;
                }
                if was != self.hovered {
                    crate::animation::request_draw();
                    return EventResult::Consumed;
                }
                EventResult::Ignored
            }
            Event::MouseDown {
                button: MouseButton::Left,
                pos,
                ..
            } => {
                self.dragging = true;
                self.props.value = self.value_from_x(pos.x);
                self.fire();
                crate::animation::request_draw();
                EventResult::Consumed
            }
            Event::MouseUp {
                button: MouseButton::Left,
                ..
            } => {
                let was = self.dragging;
                self.dragging = false;
                if was {
                    crate::animation::request_draw();
                }
                EventResult::Consumed
            }
            Event::KeyDown { key, .. } => {
                let changed = match key {
                    Key::ArrowLeft => {
                        self.props.value =
                            (self.props.value - self.props.step).clamp(self.props.min, self.props.max);
                        true
                    }
                    Key::ArrowRight => {
                        self.props.value =
                            (self.props.value + self.props.step).clamp(self.props.min, self.props.max);
                        true
                    }
                    Key::ArrowDown => {
                        self.props.value = (self.props.value - self.props.step * 10.0)
                            .clamp(self.props.min, self.props.max);
                        true
                    }
                    Key::ArrowUp => {
                        self.props.value = (self.props.value + self.props.step * 10.0)
                            .clamp(self.props.min, self.props.max);
                        true
                    }
                    _ => false,
                };
                if changed {
                    self.fire();
                    crate::animation::request_draw();
                    EventResult::Consumed
                } else {
                    EventResult::Ignored
                }
            }
            Event::FocusGained => {
                let was = self.focused;
                self.focused = true;
                if !was {
                    crate::animation::request_draw();
                    EventResult::Consumed
                } else {
                    EventResult::Ignored
                }
            }
            Event::FocusLost => {
                let was_focused = self.focused;
                let was_dragging = self.dragging;
                self.focused = false;
                self.dragging = false;
                if was_focused || was_dragging {
                    crate::animation::request_draw();
                    EventResult::Consumed
                } else {
                    EventResult::Ignored
                }
            }
            _ => EventResult::Ignored,
        }
    }
}