agg-gui 0.2.1

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
//! Reusable menu infrastructure.
//!
//! This module provides the shared model, geometry, state, painter, and widget
//! adapters used by context menus and top menu bars.

pub mod geometry;
pub mod model;
pub mod paint;
pub mod state;
pub mod strip;
pub mod widget;

pub use geometry::{BAR_H as MENU_BAR_H, MENU_W, ROW_H};
pub use model::{MenuEntry, MenuItem, MenuSelection, MenuShortcut, ShortcutKey};
pub use paint::MenuStyle;
pub use state::{MenuAnchorKind, MenuResponse, PopupMenuState};
pub use strip::MenuBarStrip;
pub use widget::{MenuBar, MenuOrientation, PopupMenu, TopMenu, VERTICAL_ROW_H};

#[cfg(test)]
mod tests {
    use crate::event::{Event, Key, Modifiers, MouseButton};
    use crate::geometry::{Point, Size};

    use super::geometry::{hit_test, stack_layout, MenuHit};
    use super::paint::submenu_chevron_points;
    use super::*;
    use crate::geometry::Rect;

    fn test_items() -> Vec<MenuEntry> {
        vec![
            MenuItem::action("Open", "open")
                .icon('\u{f07c}')
                .shortcut("Ctrl+O")
                .into(),
            MenuItem::action("Disabled", "disabled").disabled().into(),
            MenuEntry::Separator,
            MenuItem::submenu(
                "More",
                vec![
                    MenuItem::action("Leaf", "leaf").into(),
                    MenuItem::action("Checked", "checked").checked(true).into(),
                ],
            )
            .into(),
        ]
    }

    #[test]
    fn popup_clamps_to_viewport() {
        let items = test_items();
        let layouts = stack_layout(
            &items,
            Point::new(500.0, -50.0),
            MenuAnchorKind::Context,
            &[],
            Size::new(240.0, 120.0),
        );
        let rect = layouts[0].rect;
        assert!(rect.x >= 4.0);
        assert!(rect.y >= 4.0);
        assert!(rect.x + rect.width <= 240.0);
        assert!(rect.y + rect.height <= 120.0);
    }

    #[test]
    fn menu_bar_popups_can_open_below_the_bar() {
        let items = test_items();
        let layouts = stack_layout(
            &items,
            Point::new(20.0, 0.0),
            MenuAnchorKind::Bar,
            &[],
            Size::new(400.0, 240.0),
        );
        assert!(
            layouts[0].rect.y < 0.0,
            "bar popups use negative local Y so they paint below a top menu bar"
        );
    }

    #[test]
    fn hover_opens_submenu_and_hit_tests_nested_rows() {
        let items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let layouts = state.layouts(&items, viewport);
        let more_row = layouts[0].rows[3].rect;

        assert!(state.update_hover(
            &items,
            Point::new(more_row.x + 10.0, more_row.y + 10.0),
            viewport
        ));
        assert_eq!(state.open_path, vec![3]);

        let layouts = state.layouts(&items, viewport);
        let submenu_row = layouts[1].rows[0].rect;
        assert!(matches!(
            hit_test(
                &layouts,
                Point::new(submenu_row.x + 10.0, submenu_row.y + 10.0)
            ),
            Some(MenuHit::Item(path)) if path == vec![3, 0]
        ));
    }

    #[test]
    fn action_click_consumes_and_suppresses_followup_mouse_up() {
        let mut items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let first_row = state.layouts(&items, viewport)[0].rows[0].rect;

        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: Point::new(first_row.x + 10.0, first_row.y + 10.0),
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            viewport,
        );
        assert_eq!(response, MenuResponse::Action("open".to_string()));
        assert!(state.take_suppress_mouse_up());
    }

    #[test]
    fn keep_open_check_and_radio_actions_do_not_close() {
        let mut items = vec![
            MenuItem::action("Check", "check")
                .checked(false)
                .keep_open()
                .into(),
            MenuItem::action("Radio A", "radio-a")
                .radio(true)
                .keep_open()
                .into(),
            MenuItem::action("Radio B", "radio-b")
                .radio(false)
                .keep_open()
                .into(),
        ];
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 120.0), MenuAnchorKind::Context);
        let viewport = Size::new(300.0, 200.0);
        let first_row = state.layouts(&items, viewport)[0].rows[0].rect;

        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: Point::new(first_row.x + 10.0, first_row.y + 10.0),
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            viewport,
        );

        assert_eq!(response, MenuResponse::Action("check".to_string()));
        assert!(state.open);
        assert!(!state.should_suppress_mouse_up());
        let MenuEntry::Item(item) = &items[0] else {
            panic!("first row should be an item");
        };
        assert_eq!(item.selection, MenuSelection::Check { selected: true });

        let third_row = state.layouts(&items, viewport)[0].rows[2].rect;
        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: Point::new(third_row.x + 10.0, third_row.y + 10.0),
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            viewport,
        );
        assert_eq!(response, MenuResponse::Action("radio-b".to_string()));
        assert!(state.open);
        let MenuEntry::Item(item) = &items[1] else {
            panic!("second row should be an item");
        };
        assert_eq!(item.selection, MenuSelection::Radio { selected: false });
        let MenuEntry::Item(item) = &items[2] else {
            panic!("third row should be an item");
        };
        assert_eq!(item.selection, MenuSelection::Radio { selected: true });
    }

    #[test]
    fn disabled_rows_do_not_fire_actions() {
        let mut items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let disabled_row = state.layouts(&items, viewport)[0].rows[1].rect;

        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: Point::new(disabled_row.x + 10.0, disabled_row.y + 10.0),
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            viewport,
        );
        assert_eq!(response, MenuResponse::None);
        assert!(state.open);
    }

    #[test]
    fn touch_synth_move_does_not_open_submenu() {
        // Root cause of "tapping a submenu parent activates its first child on
        // mobile": a touch tap synthesises a MouseMove at the tap point before
        // the MouseDown.  `update_hover` used to OPEN the submenu (`open_path`)
        // on that move; the follow-up MouseDown then hit-tested the freshly
        // opened submenu and — on a narrow viewport where the submenu overlaps
        // its parent — landed on (and activated) the first child.  On touch,
        // submenus must open only on the explicit tap in `handle_left_down`,
        // never on the synth move.
        let items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 200.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 300.0);
        // Row 3 is the "More" submenu parent in `test_items`.
        let more_row = state.layouts(&items, viewport)[0].rows[3].rect;

        crate::touch_state::clear_last_touch_event_for_testing();
        crate::touch_state::note_touch_event();

        state.update_hover(
            &items,
            Point::new(more_row.x + 10.0, more_row.y + more_row.height * 0.5),
            viewport,
        );
        assert!(
            state.open_path.is_empty(),
            "a touch-synth MouseMove must not open a submenu (open_path = {:?})",
            state.open_path
        );

        crate::touch_state::clear_last_touch_event_for_testing();
    }

    #[test]
    fn touch_tap_on_submenu_parent_opens_it_without_activating_child() {
        // End-to-end symptom: on a NARROW viewport the "More" submenu clamps
        // back over its parent, so the first child lands under the finger.  A
        // touch tap (synth MouseMove → MouseDown at the same point) on the
        // submenu parent must OPEN the submenu and must NOT activate a child.
        let mut items = test_items();
        let mut state = PopupMenuState::default();
        // Narrow enough that the submenu (MENU_W = 224) can't sit beside the
        // parent and gets clamped over it.
        let viewport = Size::new(300.0, 320.0);
        state.open_at(Point::new(20.0, 250.0), MenuAnchorKind::Context);
        let more_row = state.layouts(&items, viewport)[0].rows[3].rect;
        // Tap toward the right of the parent row, where the clamped submenu's
        // first child overlaps.
        let tap = Point::new(more_row.x + more_row.width - 20.0, more_row.y + more_row.height * 0.5);

        crate::touch_state::clear_last_touch_event_for_testing();
        crate::touch_state::note_touch_event();

        // Synth MouseMove (touchstart), then MouseDown at the same point.
        state.handle_event(&mut items, &Event::MouseMove { pos: tap }, viewport);
        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: tap,
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            viewport,
        );

        assert!(
            !matches!(response, MenuResponse::Action(_)),
            "tapping a submenu parent must not activate a child (got {response:?})"
        );
        assert_eq!(
            state.open_path,
            vec![3],
            "tapping the submenu parent should open its submenu"
        );

        crate::touch_state::clear_last_touch_event_for_testing();
    }

    #[test]
    fn disabled_rows_do_not_become_hovered() {
        let items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let disabled_row = state.layouts(&items, viewport)[0].rows[1].rect;

        assert!(!state.update_hover(
            &items,
            Point::new(disabled_row.x + 10.0, disabled_row.y + 10.0),
            viewport,
        ));
        assert_eq!(state.hover_path, None);
    }

    #[test]
    fn touch_synthesized_move_does_not_set_popup_hover() {
        // Regression: a touch tap synthesises a MouseMove at the tap point
        // before the MouseDown.  Without suppression, that move would set
        // `hover_path` and the post-tap state would still paint a hover
        // panel on the just-tapped row even though the menu has closed.
        // After the fix, an enabled-row MouseMove inside the touch-synth
        // window must leave `hover_path` as `None`.
        let items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let first_row = state.layouts(&items, viewport)[0].rows[0].rect;

        // Force the touch-synth window to be active by recording a touch
        // event right before the MouseMove — same call the touch shells
        // make on every touchstart / touchmove / touchend.
        crate::touch_state::clear_last_touch_event_for_testing();
        crate::touch_state::note_touch_event();

        state.update_hover(
            &items,
            Point::new(first_row.x + 10.0, first_row.y + 10.0),
            viewport,
        );
        assert_eq!(
            state.hover_path, None,
            "a touch-synth MouseMove must not paint a popup-row hover"
        );

        // Reset for sibling tests.
        crate::touch_state::clear_last_touch_event_for_testing();
    }

    #[test]
    fn desktop_move_still_sets_popup_hover() {
        // Mirror test: outside the touch-synth window the same MouseMove
        // SHOULD set hover so desktop users see the subtle hover panel.
        let items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);
        let first_row = state.layouts(&items, viewport)[0].rows[0].rect;

        crate::touch_state::clear_last_touch_event_for_testing();

        assert!(state.update_hover(
            &items,
            Point::new(first_row.x + 10.0, first_row.y + 10.0),
            viewport,
        ));
        assert_eq!(state.hover_path, Some(vec![0]));
    }

    #[test]
    fn outside_click_dismisses_menu() {
        let mut items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let (_, response) = state.handle_event(
            &mut items,
            &Event::MouseDown {
                pos: Point::new(390.0, 10.0),
                button: MouseButton::Left,
                modifiers: Modifiers::default(),
            },
            Size::new(400.0, 240.0),
        );
        assert_eq!(response, MenuResponse::Closed);
        assert!(!state.open);
    }

    #[test]
    fn keyboard_navigation_activates_hovered_row() {
        let mut items = test_items();
        let mut state = PopupMenuState::default();
        state.open_at(Point::new(20.0, 160.0), MenuAnchorKind::Context);
        let viewport = Size::new(400.0, 240.0);

        state.handle_event(
            &mut items,
            &Event::KeyDown {
                key: Key::ArrowDown,
                modifiers: Modifiers::default(),
            },
            viewport,
        );
        let (_, response) = state.handle_event(
            &mut items,
            &Event::KeyDown {
                key: Key::Enter,
                modifiers: Modifiers::default(),
            },
            viewport,
        );
        assert_eq!(response, MenuResponse::Action("open".to_string()));
    }

    #[test]
    fn submenu_chevron_renders_as_vector_triangle_pointing_right() {
        // Regression: the chevron used to be painted via `fill_text`
        // with U+25B8.  Hosts whose font (and any icon fallback) lacked
        // that code point — e.g. AtomArtist's NotoSans + Bootstrap Icons
        // stack — drew an empty tofu box instead of the indicator.  The
        // chevron is now a pure vector polyline so it renders correctly
        // regardless of the host's font configuration.
        let row = Rect::new(100.0, 50.0, 200.0, 24.0);
        let [top, apex, bottom] = submenu_chevron_points(row);

        // Apex points to the right of the two arms.
        assert!(apex.0 > top.0);
        assert!(apex.0 > bottom.0);

        // Top and bottom arms share an x and straddle the apex's y.
        assert!((top.0 - bottom.0).abs() < f64::EPSILON);
        let mid_y = row.y + row.height * 0.5;
        assert!((top.1 - mid_y - (mid_y - bottom.1)).abs() < f64::EPSILON);

        // Chevron sits within the row's bounds (no leak into the
        // shortcut column or off the right edge).
        let right_edge = row.x + row.width;
        assert!(apex.0 < right_edge);
        assert!(top.1 <= row.y + row.height);
        assert!(bottom.1 >= row.y);
    }

    #[test]
    fn model_and_style_include_icons_and_shadow() {
        let items = test_items();
        let MenuEntry::Item(item) = &items[0] else {
            panic!("first row should be an item");
        };
        assert_eq!(item.icon, Some('\u{f07c}'));
        assert!(item.shortcut.is_some());
        assert!(MenuStyle::default().shadow_alpha > 0.0);
    }
}