agg-gui 0.3.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
//! `Checkbox` — a boolean toggle with a label.
//!
//! # Composition
//!
//! The checkbox label is rendered through a [`Label`] child with backbuffer
//! caching enabled (the default).  The box + checkmark are drawn directly via
//! path commands; only the text goes through the Label path.
//!
//! ```text
//! Checkbox (box + checkmark drawn via paths)
//!   └── Label (text, backbuffered)
//! ```

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

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::text::Font;
use crate::widget::Widget;
use crate::widgets::label::Label;

const BOX_SIZE: f64 = 16.0;
const FOCUS_PAD: f64 = 2.0;
const GAP: f64 = 8.0;
const BOX_STROKE_WIDTH: f64 = 1.5;

/// Inspector-visible properties of a [`Checkbox`].  See [`SliderProps`] for
/// the rationale of the companion-props pattern.
#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
#[derive(Clone, Debug, Default)]
pub struct CheckboxProps {
    pub checked: bool,
    pub font_size: f64,
    /// Explicit label colour override; `None` → follow active visuals.
    pub label_color: Option<Color>,
}

/// A boolean toggle with a square box and a text label.
pub struct Checkbox {
    bounds: Rect,
    /// `children[0]` is the [`Label`] that renders the text — composed as a
    /// real child so the framework's paint walk handles it.
    children: Vec<Box<dyn Widget>>,
    base: WidgetBase,
    font: Arc<Font>,
    pub props: CheckboxProps,
    /// When set, this cell is the authoritative checked state.  `paint` reads
    /// from it and `toggle` writes to it so the checkbox stays in sync with
    /// external state changes (e.g. a window's close button setting it to false).
    state_cell: Option<Rc<Cell<bool>>>,
    hovered: bool,
    focused: bool,
    on_change: Option<Box<dyn FnMut(bool)>>,
    /// When set and it returns `true`, the box renders a horizontal dash
    /// (egui's indeterminate/tri-state look) instead of a checkmark. This only
    /// affects appearance; clicking still toggles `checked`. Used for
    /// "check/uncheck all" controls whose state depends on a group of boxes.
    indeterminate_fn: Option<Box<dyn Fn() -> bool>>,
    /// Tracked label text — used for empty-check during layout and to rebuild
    /// the Label child when font size changes.
    label_text: String,
}

impl Checkbox {
    pub fn new(label: impl Into<String>, font: Arc<Font>, checked: bool) -> Self {
        let label_text: String = label.into();
        let font_size = 14.0;
        let label_widget = Label::new(&label_text, Arc::clone(&font)).with_font_size(font_size);
        Self {
            bounds: Rect::default(),
            children: vec![Box::new(label_widget)],
            base: WidgetBase::new(),
            font,
            props: CheckboxProps {
                checked,
                font_size,
                label_color: None,
            },
            state_cell: None,
            hovered: false,
            focused: false,
            on_change: None,
            indeterminate_fn: None,
            label_text,
        }
    }

    pub fn with_font_size(mut self, size: f64) -> Self {
        self.props.font_size = size;
        self.children[0] =
            Box::new(Label::new(&self.label_text, Arc::clone(&self.font)).with_font_size(size));
        self
    }
    pub fn with_label_color(mut self, c: Color) -> Self {
        self.props.label_color = Some(c);
        self
    }

    /// Bind checked state to a shared cell.
    ///
    /// When set, `paint` reads from the cell (so external changes — e.g. a
    /// window's close button — are reflected immediately), and `toggle` writes
    /// to it so both directions stay in sync.
    pub fn with_state_cell(mut self, cell: Rc<Cell<bool>>) -> Self {
        self.state_cell = Some(cell);
        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(bool) + 'static) -> Self {
        self.on_change = Some(Box::new(cb));
        self
    }

    /// Drive the indeterminate (tri-state) appearance from a closure.
    ///
    /// When the closure returns `true` the box shows a horizontal dash instead
    /// of a checkmark, mirroring egui's `Checkbox::indeterminate`. The closure
    /// is evaluated every paint, so it can reflect live aggregate state (e.g. a
    /// "check all" box that is indeterminate when only some children are set).
    pub fn with_indeterminate_fn(mut self, f: impl Fn() -> bool + 'static) -> Self {
        self.indeterminate_fn = Some(Box::new(f));
        self
    }

    /// Returns whether the box should currently render as indeterminate.
    #[inline]
    fn is_indeterminate(&self) -> bool {
        self.indeterminate_fn.as_ref().is_some_and(|f| f())
    }

    pub fn checked(&self) -> bool {
        self.props.checked
    }
    pub fn set_checked(&mut self, v: bool) {
        self.props.checked = v;
    }

    fn toggle(&mut self) {
        let new_val = !self.effective_checked();
        self.props.checked = 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);
        }
    }

    /// Returns the authoritative checked state: the cell value if bound, else
    /// the internal `checked` field.
    #[inline]
    fn effective_checked(&self) -> bool {
        if let Some(ref cell) = self.state_cell {
            cell.get()
        } else {
            self.props.checked
        }
    }

    fn unchecked_colors(v: &crate::theme::Visuals, hovered: bool) -> (Color, Color) {
        let luma = v.bg_color.r * 0.299 + v.bg_color.g * 0.587 + v.bg_color.b * 0.114;
        if luma < 0.5 {
            let fill = if hovered { v.widget_bg } else { v.window_fill };
            (fill, Color::rgba(1.0, 1.0, 1.0, 0.34))
        } else {
            let fill = if hovered {
                v.widget_bg_hovered
            } else {
                v.widget_bg
            };
            (fill, v.widget_stroke)
        }
    }
}

impl Widget for Checkbox {
    fn type_name(&self) -> &'static str {
        "Checkbox"
    }
    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 {
        let box_slot_w = BOX_SIZE + FOCUS_PAD * 2.0;
        let h = (BOX_SIZE + FOCUS_PAD * 2.0).max(self.props.font_size * 1.25);
        let label_avail_w = (available.width - box_slot_w - GAP).max(0.0);
        let s = self.children[0].layout(Size::new(label_avail_w, h));
        let lx = if self.label_text.is_empty() {
            box_slot_w
        } else {
            box_slot_w + GAP
        };
        let ly = (h - s.height) * 0.5;
        self.children[0].set_bounds(Rect::new(lx, ly, s.width, s.height));
        let natural_w = if self.label_text.is_empty() {
            box_slot_w
        } else {
            box_slot_w + GAP + s.width
        };
        let w = natural_w.min(available.width);
        self.bounds = Rect::new(0.0, 0.0, w, h);
        Size::new(w, h)
    }

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

        // Focus ring
        if self.focused {
            ctx.set_stroke_color(v.accent_focus);
            ctx.set_line_width(2.0);
            ctx.begin_path();
            ctx.rounded_rect(
                box_x - 1.5,
                box_y - 1.5,
                BOX_SIZE + 3.0,
                BOX_SIZE + 3.0,
                4.0,
            );
            ctx.stroke();
        }

        let checked = self.effective_checked();
        let indeterminate = self.is_indeterminate();
        // The indeterminate state renders with the "on" (accent) fill, matching
        // our checked look, so it reads as a partial selection rather than empty.
        let filled = checked || indeterminate;

        // Box background
        let (unchecked_bg, unchecked_border) = Self::unchecked_colors(&v, self.hovered);
        let bg = if filled { v.accent } else { unchecked_bg };
        ctx.set_fill_color(bg);
        ctx.begin_path();
        ctx.rounded_rect(box_x, box_y, BOX_SIZE, BOX_SIZE, 3.0);
        ctx.fill();

        // Box border
        let border = if filled {
            v.widget_stroke_active
        } else {
            unchecked_border
        };
        ctx.set_stroke_color(border);
        ctx.set_line_width(BOX_STROKE_WIDTH);
        ctx.begin_path();
        let stroke_inset = BOX_STROKE_WIDTH * 0.5;
        ctx.rounded_rect(
            box_x + stroke_inset,
            box_y + stroke_inset,
            BOX_SIZE - BOX_STROKE_WIDTH,
            BOX_SIZE - BOX_STROKE_WIDTH,
            3.0,
        );
        ctx.stroke();

        // Mark — coordinates in Y-up space (origin = box bottom-left).
        // Indeterminate takes visual priority: draw a horizontal dash rather
        // than the checkmark, matching egui's tri-state look.
        if indeterminate {
            ctx.set_stroke_color(Color::white());
            ctx.set_line_width(2.0);
            ctx.begin_path();
            ctx.move_to(box_x + 3.0, box_y + BOX_SIZE * 0.5);
            ctx.line_to(box_x + BOX_SIZE - 3.0, box_y + BOX_SIZE * 0.5);
            ctx.stroke();
        } else if checked {
            ctx.set_stroke_color(Color::white());
            ctx.set_line_width(2.0);
            ctx.begin_path();
            let bx = box_x;
            let by = box_y;
            ctx.move_to(bx + 3.0, by + BOX_SIZE * 0.55);
            ctx.line_to(bx + BOX_SIZE * 0.42, by + BOX_SIZE * 0.28);
            ctx.line_to(bx + BOX_SIZE - 3.0, by + BOX_SIZE * 0.75);
            ctx.stroke();
        }

        // Label colour — child paints itself via the framework's tree walk.
        let label_color = self.props.label_color.unwrap_or(v.text_color);
        self.children[0].set_label_color(label_color);
    }

    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,
                ..
            } => EventResult::Consumed,
            Event::MouseUp {
                button: MouseButton::Left,
                pos,
                ..
            } => {
                if self.hit_test(*pos) {
                    self.toggle();
                    crate::animation::request_draw();
                }
                EventResult::Consumed
            }
            Event::KeyDown {
                key: Key::Char(' '),
                ..
            } => {
                self.toggle();
                crate::animation::request_draw();
                EventResult::Consumed
            }
            Event::FocusGained => {
                let was = self.focused;
                self.focused = true;
                if !was {
                    crate::animation::request_draw();
                    EventResult::Consumed
                } else {
                    EventResult::Ignored
                }
            }
            Event::FocusLost => {
                let was = self.focused;
                self.focused = false;
                if was {
                    crate::animation::request_draw();
                    EventResult::Consumed
                } else {
                    EventResult::Ignored
                }
            }
            _ => EventResult::Ignored,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const FONT_BYTES: &[u8] = include_bytes!("../../../demo/assets/CascadiaCode.ttf");

    fn test_font() -> Arc<Font> {
        Arc::new(Font::from_slice(FONT_BYTES).expect("font"))
    }

    #[test]
    fn no_indeterminate_fn_reads_false() {
        let cb = Checkbox::new("x", test_font(), false);
        assert!(!cb.is_indeterminate());
    }

    #[test]
    fn indeterminate_fn_drives_visual_state() {
        let flag = Rc::new(Cell::new(true));
        let f = Rc::clone(&flag);
        let cb = Checkbox::new("x", test_font(), false).with_indeterminate_fn(move || f.get());
        assert!(cb.is_indeterminate());
        flag.set(false);
        assert!(!cb.is_indeterminate());
    }

    #[test]
    fn click_still_toggles_while_indeterminate() {
        // Indeterminate only affects appearance; toggling must still work.
        let cb = Checkbox::new("x", test_font(), false).with_indeterminate_fn(|| true);
        let mut cb = cb;
        assert!(!cb.effective_checked());
        cb.toggle();
        assert!(cb.effective_checked());
    }
}