1
//! Software menu-bar widget — the Linux fallback when there is no native global
2
//! menu (GNOME/KDE export their own; Windows uses `HMENU`, macOS the app menu).
3
//!
4
//! Renders the window's [`Menu`] (declared by the user via
5
//! `Dom::with_menu_bar(menu)`) as a horizontal bar of top-level items. Clicking a
6
//! top-level item opens its children as a dropdown popup positioned directly
7
//! below the item via [`CallbackInfo::open_menu_for_hit_node`] — which looks up
8
//! the clicked node's on-screen rect and opens a child window at its bottom-left
9
//! (the unified [`WindowPosition::RelativeToParentWindow`] path).
10
//!
11
//! ## Styling
12
//!
13
//! All styling is inline via `with_css(&str)` using the `system:` color namespace
14
//! (`system:window-background`, `system:text`, `system:selection-background`, …)
15
//! and the `system:ui` font, so the bar matches the OS theme without threading a
16
//! `SystemStyle` through. The bar MUST be injected at the *Dom* level (before
17
//! `StyledDom::create_from_dom`) so `scope_inline_css` scopes these rules in the
18
//! same flatten pass as the rest of the window — see
19
//! `shell2::common::layout::regenerate_layout`.
20
//!
21
//! ## Backreference pattern
22
//!
23
//! The dropdown's items are the user's own [`MenuItem`]s, each carrying the
24
//! `(RefAny, Callback)` backreference the user attached with
25
//! `StringMenuItem::with_callback(data, cb)`. Clicking a leaf fires that callback
26
//! with the user's data — so the bar is a thin shell and behaviour stays in user
27
//! code (see `doc/guide/en/architecture.md`, "the backreference pattern").
28
//!
29
//! [`WindowPosition::RelativeToParentWindow`]: azul_core::window::WindowPosition::RelativeToParentWindow
30

            
31
use azul_core::{
32
    callbacks::{CoreCallback, CoreCallbackData},
33
    dom::{Dom, EventFilter, HoverEventFilter, IdOrClass::Class, IdOrClassVec},
34
    menu::{Menu, MenuItem, MenuItemVec, StringMenuItem},
35
    refany::{OptionRefAny, RefAny},
36
};
37

            
38
/// Class on the injected bar root — also the detection marker the renderer / tests
39
/// use to recognise an injected software menu bar.
40
pub const MENUBAR_CLASS: &str = "__azul-native-menubar";
41
/// Class on each top-level bar item.
42
pub const MENUBAR_ITEM_CLASS: &str = "azul-menubar-item";
43

            
44
/// Inline CSS for the bar root: a full-width horizontal flex row themed from the
45
/// OS (`system:` colors + `system:ui` font). Bare declarations, so the rule is
46
/// scoped node-only at flatten time.
47
const MENUBAR_CSS: &str = "display: flex; flex-direction: row; align-items: stretch; width: 100%; \
48
                           height: 26px; background: system:window-background; color: \
49
                           system:text; font-family: system:ui; font-size: 14px; padding-left: \
50
                           2px;";
51

            
52
/// Inline CSS for a top-level item: vertically-centered click target with hover
53
/// feedback (the `:hover` block nests via CSS nesting in `parse_inline`).
54
const MENUBAR_ITEM_CSS: &str = "display: flex; flex-direction: row; align-items: center; \
55
                                padding-left: 10px; padding-right: 10px; color: system:text; \
56
                                cursor: pointer; :hover { background: \
57
                                system:selection-background; color: system:selection-text; }";
58

            
59
/// Build the software menu-bar DOM from a [`Menu`].
60
///
61
/// The bar is a flex row of one item per top-level `MenuItem::String`
62
/// (separators / break-lines are not rendered in the bar). Inject the returned
63
/// `Dom` at the Dom level so its `with_css` rules are scoped in the main flatten.
64
#[must_use]
65
79
pub fn build_menubar_dom(menu: &Menu) -> Dom {
66
79
    let mut bar = Dom::create_div()
67
79
        .with_ids_and_classes(IdOrClassVec::from_vec(vec![
68
79
            Class(MENUBAR_CLASS.into()),
69
79
            Class("azul-menubar".into()),
70
        ]))
71
79
        .with_css(MENUBAR_CSS);
72

            
73
1553
    for item in menu.items.as_slice() {
74
1553
        if let MenuItem::String(s) = item {
75
1540
            bar = bar.with_child(build_menubar_item(s));
76
1540
        }
77
    }
78

            
79
79
    bar
80
79
}
81

            
82
/// One clickable top-level bar item. Its `MouseUp` callback opens the item's
83
/// submenu (its children, or — for a top-level leaf — a one-item menu of itself
84
/// so the leaf's own callback still fires) below the item.
85
1552
fn build_menubar_item(item: &StringMenuItem) -> Dom {
86
    // The submenu carried (by value) into the click callback as its RefAny.
87
1552
    let submenu = if item.children.as_slice().is_empty() {
88
1541
        Menu::create(MenuItemVec::from_vec(vec![MenuItem::String(item.clone())]))
89
    } else {
90
11
        Menu::create(item.children.clone())
91
    };
92

            
93
1552
    Dom::create_div()
94
1552
        .with_ids_and_classes(IdOrClassVec::from_vec(vec![Class(
95
1552
            MENUBAR_ITEM_CLASS.into(),
96
1552
        )]))
97
1552
        .with_css(MENUBAR_ITEM_CSS)
98
1552
        .with_child(crate::widgets::widget_p_with_text(item.label.clone()))
99
1552
        .with_callbacks(
100
1552
            vec![CoreCallbackData {
101
1552
                event: EventFilter::Hover(HoverEventFilter::Click),
102
1552
                callback: CoreCallback {
103
1552
                    cb: callbacks::menubar_item_click as usize,
104
1552
                    ctx: OptionRefAny::None,
105
1552
                },
106
1552
                refany: RefAny::new(submenu),
107
1552
            }]
108
1552
            .into(),
109
        )
110
1552
}
111

            
112
pub(crate) mod callbacks {
113
    use azul_core::{callbacks::Update, menu::Menu, refany::RefAny};
114

            
115
    use crate::callbacks::CallbackInfo;
116

            
117
    /// Top-level bar item clicked → open its submenu under the item. The submenu
118
    /// `Menu` is the callback's `data` (a backreference set at build time); its
119
    /// items carry the user's own callbacks, fired by the menu system on click.
120
27
    pub(super) extern "C" fn menubar_item_click(
121
27
        mut data: RefAny,
122
27
        mut info: CallbackInfo,
123
27
    ) -> Update {
124
27
        if let Some(menu) = data.downcast_ref::<Menu>() {
125
24
            info.open_menu_for_hit_node(menu.clone());
126
24
        }
127
27
        Update::DoNothing
128
27
    }
129
}
130

            
131
#[cfg(test)]
132
mod autotest_generated {
133
    use std::{
134
        collections::{BTreeMap, HashMap},
135
        sync::{Arc, Mutex},
136
    };
137

            
138
    use azul_core::{
139
        callbacks::Update,
140
        dom::{DomId, DomNodeId, IdOrClass, NodeId, NodeType},
141
        geom::{LogicalPosition, LogicalRect, LogicalSize, OptionLogicalPosition},
142
        gl::OptionGlContextPtr,
143
        hit_test::ScrollPosition,
144
        menu::{CoreMenuCallback, MenuItemIcon, MenuItemState},
145
        resources::RendererResources,
146
        styled_dom::{NodeHierarchyItemId, StyledDom},
147
        window::{
148
            MonitorVec, RawWindowHandle, VirtualKeyCode, VirtualKeyCodeCombo, VirtualKeyCodeVec,
149
        },
150
    };
151
    use azul_css::AzString;
152
    use rust_fontconfig::FcFontCache;
153

            
154
    use super::{callbacks::menubar_item_click, *};
155
    #[cfg(feature = "icu")]
156
    use crate::icu::IcuLocalizerHandle;
157
    use crate::{
158
        callbacks::{CallbackChange, CallbackInfo, CallbackInfoRefData, ExternalSystemCallbacks},
159
        solver3::{
160
            display_list::{DisplayList, DisplayListItem, WindowLogicalRect},
161
            layout_tree::LayoutTree,
162
        },
163
        window::{DomLayoutResult, LayoutWindow},
164
        window_state::FullWindowState,
165
    };
166

            
167
    // ------------------------------------------------------------------
168
    // Menu fixtures
169
    // ------------------------------------------------------------------
170

            
171
    fn leaf(label: &str) -> StringMenuItem {
172
        StringMenuItem::create(AzString::from(label))
173
    }
174

            
175
    fn string_item(label: &str) -> MenuItem {
176
        MenuItem::String(leaf(label))
177
    }
178

            
179
    fn menu_of(items: Vec<MenuItem>) -> Menu {
180
        Menu::create(MenuItemVec::from_vec(items))
181
    }
182

            
183
    /// A leaf whose every optional field is populated — so "the leaf is wrapped
184
    /// verbatim" is a claim about *all* of `StringMenuItem`, not just its label.
185
    fn decorated_leaf(label: &str) -> StringMenuItem {
186
        let mut it = leaf(label);
187
        it.accelerator = Some(VirtualKeyCodeCombo {
188
            keys: VirtualKeyCodeVec::from_vec(vec![VirtualKeyCode::Q]),
189
        })
190
        .into();
191
        it.callback = Some(CoreMenuCallback {
192
            refany: RefAny::new(0xDEAD_BEEF_u64),
193
            callback: CoreCallback {
194
                cb: 0x1234_usize,
195
                ctx: OptionRefAny::None,
196
            },
197
        })
198
        .into();
199
        it.menu_item_state = MenuItemState::Greyed;
200
        it.icon = Some(MenuItemIcon::Checkbox(true)).into();
201
        it
202
    }
203

            
204
    /// `depth` levels of single-child nesting under one top-level item.
205
    /// Kept modest on purpose: the builders clone/drop recursively, and a test
206
    /// that blows the stack aborts the whole harness instead of failing.
207
    fn nested(depth: usize) -> StringMenuItem {
208
        let mut cur = leaf("bottom");
209
        for i in 0..depth {
210
            cur = leaf(&format!("lvl{i}")).with_child(MenuItem::String(cur));
211
        }
212
        cur
213
    }
214

            
215
    /// Labels/markers of a menu's items, in menu order.
216
    fn labels_of(menu: &Menu) -> Vec<String> {
217
        menu.items
218
            .as_slice()
219
            .iter()
220
            .map(|i| match i {
221
                MenuItem::String(s) => s.label.as_str().to_string(),
222
                MenuItem::Separator => "<sep>".to_string(),
223
                MenuItem::BreakLine => "<br>".to_string(),
224
            })
225
            .collect()
226
    }
227

            
228
    // ------------------------------------------------------------------
229
    // Dom inspection
230
    // ------------------------------------------------------------------
231

            
232
    fn text_of(node: &Dom) -> Option<&str> {
233
        match node.root.get_node_type() {
234
            NodeType::Text(t) => Some(t.as_ref().as_str()),
235
            _ => None,
236
        }
237
    }
238

            
239
    fn classes_of(node: &Dom) -> Vec<String> {
240
        node.root
241
            .get_ids_and_classes()
242
            .as_ref()
243
            .iter()
244
            .filter_map(|c| match c {
245
                Class(s) => Some(s.as_str().to_string()),
246
                IdOrClass::Id(_) => None,
247
            })
248
            .collect()
249
    }
250

            
251
    /// The label rendered by a bar item: a `<p>` block wrapping the text.
252
    ///
253
    /// The bar item used to hold a BARE text node. A text leaf owns no box, so
254
    /// in a flex/grid parent it competes as an item with no line box of its own
255
    /// — browsers wrap such runs in an anonymous block, azul does not. Every
256
    /// widget label is a `<p>` now, so this walks one level deeper.
257
    fn rendered_label(item_dom: &Dom) -> &str {
258
        let children = item_dom.children.as_ref();
259
        assert_eq!(
260
            children.len(),
261
            1,
262
            "a bar item renders exactly one label block"
263
        );
264
        let label = &children[0];
265
        assert!(
266
            matches!(label.root.get_node_type(), NodeType::P),
267
            "a bar item's label must be wrapped in a <p>, not a bare text node"
268
        );
269
        let inner = label.children.as_ref();
270
        assert_eq!(inner.len(), 1, "a label <p> wraps exactly one text node");
271
        text_of(&inner[0]).expect("the <p>'s only child must be a text node")
272
    }
273

            
274
    /// The true recursive descendant count — what `estimated_total_children`
275
    /// caches, and what `convert_dom_into_compact_dom` sizes its arenas from.
276
    fn recursive_descendants(node: &Dom) -> usize {
277
        node.children
278
            .as_ref()
279
            .iter()
280
            .map(|c| 1 + recursive_descendants(c))
281
            .sum()
282
    }
283

            
284
    fn assert_children_count_is_in_sync(dom: &Dom) {
285
        assert_eq!(
286
            dom.estimated_total_children,
287
            recursive_descendants(dom),
288
            "estimated_total_children must equal the real descendant count — a too-small value \
289
             makes convert_dom_into_compact_dom under-allocate",
290
        );
291
    }
292

            
293
    /// The `RefAny` a bar item carries on its click callback.
294
    fn refany_of(item_dom: &Dom) -> RefAny {
295
        let cbs = item_dom.root.callbacks.as_ref();
296
        assert_eq!(cbs.len(), 1, "a bar item registers exactly one callback");
297
        cbs[0].refany.clone()
298
    }
299

            
300
    /// Decodes a bar item's backreference back into the `Menu` it will open.
301
    fn submenu_of(item_dom: &Dom) -> Menu {
302
        let mut refany = refany_of(item_dom);
303
        let guard = refany
304
            .downcast_ref::<Menu>()
305
            .expect("a bar item's backreference must be a Menu");
306
        guard.clone()
307
    }
308

            
309
    /// DOM node ids of the bar items inside a flattened bar, in document order.
310
    fn item_node_ids(styled: &StyledDom) -> Vec<NodeId> {
311
        styled
312
            .node_data
313
            .as_ref()
314
            .iter()
315
            .enumerate()
316
            .filter(|(_, nd)| {
317
                nd.get_ids_and_classes()
318
                    .as_ref()
319
                    .iter()
320
                    .any(|c| matches!(c, Class(s) if s.as_str() == MENUBAR_ITEM_CLASS))
321
            })
322
            .map(|(i, _)| NodeId::new(i))
323
            .collect()
324
    }
325

            
326
    // ------------------------------------------------------------------
327
    // CallbackInfo harness (mirrors the one in `drop_down.rs`)
328
    // ------------------------------------------------------------------
329

            
330
    struct Env<'a> {
331
        ref_data: &'a CallbackInfoRefData<'a>,
332
        changes: &'a Arc<Mutex<Vec<CallbackChange>>>,
333
        default_hit: DomNodeId,
334
    }
335

            
336
    impl Env<'_> {
337
        fn info(&self) -> CallbackInfo {
338
            self.info_at(self.default_hit)
339
        }
340

            
341
        fn info_at(&self, hit: DomNodeId) -> CallbackInfo {
342
            CallbackInfo::new(
343
                self.ref_data,
344
                self.changes,
345
                hit,
346
                OptionLogicalPosition::None,
347
                OptionLogicalPosition::None,
348
            )
349
        }
350

            
351
        fn take_changes(&self) -> Vec<CallbackChange> {
352
            self.changes
353
                .lock()
354
                .map(|mut c| core::mem::take(&mut *c))
355
                .unwrap_or_default()
356
        }
357

            
358
        fn take_one(&self) -> CallbackChange {
359
            let mut changes = self.take_changes();
360
            assert_eq!(changes.len(), 1, "expected exactly one change: {changes:?}");
361
            changes.remove(0)
362
        }
363
    }
364

            
365
    fn dom_node(node: NodeId) -> DomNodeId {
366
        DomNodeId {
367
            dom: DomId::ROOT_ID,
368
            node: NodeHierarchyItemId::from_crate_internal(Some(node)),
369
        }
370
    }
371

            
372
    fn no_hit_node() -> DomNodeId {
373
        DomNodeId {
374
            dom: DomId::ROOT_ID,
375
            node: NodeHierarchyItemId::NONE,
376
        }
377
    }
378

            
379
    /// The tag the hit-tester would use for `node`. `open_menu_for_node` resolves
380
    /// the anchor rect through this mapping, so a forged hit-test area must reuse
381
    /// the id the styling pass actually assigned.
382
    fn tag_of(styled_dom: &StyledDom, node: NodeId) -> u64 {
383
        let nid = NodeHierarchyItemId::from_crate_internal(Some(node));
384
        styled_dom
385
            .tag_ids_to_node_ids
386
            .iter()
387
            .find(|m| m.node_id == nid)
388
            .expect("a menubar item must be hit-testable")
389
            .tag_id
390
            .inner
391
    }
392

            
393
    /// A `DomLayoutResult` carrying only a `styled_dom` plus forged hit-test
394
    /// areas. `menubar_item_click` reaches exactly one geometry query
395
    /// (`get_node_hit_test_bounds`), which reads the display list only — so no
396
    /// real layout (and no font) is needed.
397
    fn layout_result(styled_dom: StyledDom, anchors: &[(NodeId, LogicalRect)]) -> DomLayoutResult {
398
        let mut display_list = DisplayList::default();
399
        for (node, rect) in anchors {
400
            let tag = tag_of(&styled_dom, *node);
401
            display_list.items.push(DisplayListItem::HitTestArea {
402
                bounds: WindowLogicalRect::new(rect.origin, rect.size),
403
                // The tag TYPE matters: `get_node_hit_test_bounds` looks for
404
                // a DOM-node area specifically (text-run cursor areas share
405
                // the `tag.0` numbering space), so a forged area must carry
406
                // the same type the display list builder stamps.
407
                tag: (tag, azul_core::hit_test::TAG_TYPE_DOM_NODE),
408
            });
409
        }
410

            
411
        DomLayoutResult {
412
            styled_dom,
413
            layout_tree: LayoutTree {
414
                nodes: Vec::new(),
415
                warm: Vec::new(),
416
                cold: Vec::new(),
417
                root: 0,
418
                dom_to_layout: BTreeMap::new(),
419
                children_arena: Vec::new(),
420
                children_offsets: Vec::new(),
421
                subtree_needs_intrinsic: Vec::new(),
422
            },
423
            calculated_positions: Vec::new(),
424
            viewport: LogicalRect::zero(),
425
            display_list: Arc::new(display_list),
426
            scroll_ids: HashMap::new(),
427
            scroll_id_to_node_id: HashMap::new(),
428
        }
429
    }
430

            
431
    /// Empty `LayoutWindow`, no hit node — the "nothing to anchor to" case.
432
    fn with_env<R>(f: impl FnOnce(&Env<'_>) -> R) -> R {
433
        with_env_cfg(None, &[], None, f)
434
    }
435

            
436
    fn with_anchored_env<R>(
437
        styled_dom: StyledDom,
438
        anchors: &[(NodeId, LogicalRect)],
439
        hit: NodeId,
440
        f: impl FnOnce(&Env<'_>) -> R,
441
    ) -> R {
442
        with_env_cfg(Some(styled_dom), anchors, Some(hit), f)
443
    }
444

            
445
    fn with_env_cfg<R>(
446
        styled: Option<StyledDom>,
447
        anchors: &[(NodeId, LogicalRect)],
448
        hit: Option<NodeId>,
449
        f: impl FnOnce(&Env<'_>) -> R,
450
    ) -> R {
451
        let mut layout_window =
452
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
453
        if let Some(sd) = styled {
454
            layout_window
455
                .layout_results
456
                .insert(DomId::ROOT_ID, layout_result(sd, anchors));
457
        }
458

            
459
        let renderer_resources = RendererResources::default();
460
        let previous_window_state: Option<FullWindowState> = None;
461
        let current_window_state = FullWindowState::default();
462
        let gl_context = OptionGlContextPtr::None;
463
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
464
            BTreeMap::new();
465
        let window_handle = RawWindowHandle::Unsupported;
466
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
467

            
468
        let ref_data = CallbackInfoRefData {
469
            layout_window: &layout_window,
470
            renderer_resources: &renderer_resources,
471
            previous_window_state: &previous_window_state,
472
            current_window_state: &current_window_state,
473
            gl_context: &gl_context,
474
            current_scroll_manager: &scroll_states,
475
            current_window_handle: &window_handle,
476
            system_callbacks: &system_callbacks,
477
            system_style: Arc::new(azul_css::system::SystemStyle::default()),
478
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
479
            #[cfg(feature = "icu")]
480
            icu_localizer: IcuLocalizerHandle::default(),
481
            ctx: OptionRefAny::None,
482
        };
483

            
484
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
485
        let env = Env {
486
            ref_data: &ref_data,
487
            changes: &changes,
488
            default_hit: hit.map_or_else(no_hit_node, dom_node),
489
        };
490
        f(&env)
491
    }
492

            
493
    // ==================================================================
494
    // build_menubar_dom
495
    // ==================================================================
496

            
497
    #[test]
498
    fn build_menubar_dom_on_an_empty_menu_yields_a_childless_bar() {
499
        let bar = build_menubar_dom(&menu_of(Vec::new()));
500

            
501
        assert!(
502
            bar.children.as_ref().is_empty(),
503
            "an empty menu must produce no bar items — not a placeholder"
504
        );
505
        assert_eq!(bar.estimated_total_children, 0);
506
        assert_eq!(
507
            classes_of(&bar),
508
            vec![MENUBAR_CLASS.to_string(), "azul-menubar".to_string()],
509
            "the detection marker class must be present even on an empty bar"
510
        );
511
        assert!(
512
            bar.root.callbacks.as_ref().is_empty(),
513
            "the bar root itself is inert — only its items are clickable"
514
        );
515
    }
516

            
517
    #[test]
518
    fn build_menubar_dom_attaches_the_bar_css_exactly_once() {
519
        let bar = build_menubar_dom(&menu_of(vec![string_item("File")]));
520

            
521
        let css = bar.css.as_ref();
522
        assert_eq!(
523
            css.len(),
524
            1,
525
            "with_css must push exactly one component stylesheet"
526
        );
527
        assert!(
528
            !css[0].rules.as_ref().is_empty(),
529
            "MENUBAR_CSS must not silently parse to nothing"
530
        );
531

            
532
        let item_css = bar.children.as_ref()[0].css.as_ref();
533
        assert_eq!(item_css.len(), 1, "each item carries its own stylesheet");
534
        assert!(
535
            !item_css[0].rules.as_ref().is_empty(),
536
            "MENUBAR_ITEM_CSS (incl. its nested :hover block) must not parse to nothing"
537
        );
538
    }
539

            
540
    #[test]
541
    fn build_menubar_dom_renders_only_string_items() {
542
        // Separators / break-lines are documented as *not* rendered in the bar,
543
        // and — the real trap — must not shift the item↦child mapping.
544
        let m = menu_of(vec![
545
            MenuItem::Separator,
546
            string_item("File"),
547
            MenuItem::BreakLine,
548
            MenuItem::Separator,
549
            string_item("Edit"),
550
            MenuItem::BreakLine,
551
        ]);
552
        let bar = build_menubar_dom(&m);
553

            
554
        let labels: Vec<&str> = bar.children.as_ref().iter().map(rendered_label).collect();
555
        assert_eq!(
556
            labels,
557
            vec!["File", "Edit"],
558
            "order must survive the skipped items"
559
        );
560

            
561
        for child in bar.children.as_ref() {
562
            assert_eq!(classes_of(child), vec![MENUBAR_ITEM_CLASS.to_string()]);
563
        }
564
    }
565

            
566
    #[test]
567
    fn build_menubar_dom_on_only_non_string_items_yields_a_childless_bar() {
568
        for items in [
569
            vec![MenuItem::Separator],
570
            vec![MenuItem::BreakLine],
571
            vec![
572
                MenuItem::Separator,
573
                MenuItem::BreakLine,
574
                MenuItem::Separator,
575
            ],
576
        ] {
577
            let bar = build_menubar_dom(&menu_of(items));
578
            assert!(
579
                bar.children.as_ref().is_empty(),
580
                "separators/break-lines are never rendered in the bar"
581
            );
582
            assert_children_count_is_in_sync(&bar);
583
        }
584
    }
585

            
586
    #[test]
587
    fn build_menubar_dom_preserves_pathological_labels_byte_for_byte() {
588
        let huge = "x".repeat(100_000);
589
        let cases = vec![
590
            "",
591
            " ",
592
            "\t\n\r",
593
            "a\u{0}b",                // interior NUL
594
            "\u{0}",                  // lone NUL
595
            "👨‍👩‍👧‍👦",                     // ZWJ sequence
596
            "مرحبا",                  // RTL
597
            "e\u{301}\u{301}\u{301}", // stacked combining marks
598
            "\u{200b}\u{feff}",       // zero-width / BOM
599
            "\u{1f600}\u{fe0f}",      // astral + variation selector
600
            "&<>\"'",                 // markup metacharacters
601
            "{ color: red }",         // CSS-looking label
602
            huge.as_str(),
603
        ];
604
        let m = menu_of(cases.iter().map(|c| string_item(c)).collect::<Vec<_>>());
605
        let bar = build_menubar_dom(&m);
606

            
607
        let labels: Vec<&str> = bar.children.as_ref().iter().map(rendered_label).collect();
608
        assert_eq!(
609
            labels, cases,
610
            "labels must round-trip into the DOM verbatim"
611
        );
612
        assert_eq!(
613
            labels[cases.len() - 1].len(),
614
            100_000,
615
            "a 100k-char label must not be truncated"
616
        );
617
        assert_children_count_is_in_sync(&bar);
618
    }
619

            
620
    #[test]
621
    fn build_menubar_dom_keeps_estimated_total_children_in_sync() {
622
        for n in [0_usize, 1, 2, 17, 256] {
623
            let m = menu_of((0..n).map(|i| string_item(&format!("m{i}"))).collect());
624
            let bar = build_menubar_dom(&m);
625

            
626
            assert_eq!(bar.children.as_ref().len(), n);
627
            assert_eq!(
628
                bar.estimated_total_children,
629
                3 * n,
630
                "each item contributes itself + its label <p> + the text node"
631
            );
632
            assert_children_count_is_in_sync(&bar);
633
        }
634
    }
635

            
636
    #[test]
637
    fn build_menubar_dom_scales_to_a_wide_menu() {
638
        const N: usize = 1_000;
639
        let m = menu_of((0..N).map(|i| string_item(&format!("item{i}"))).collect());
640
        let bar = build_menubar_dom(&m);
641

            
642
        assert_eq!(bar.children.as_ref().len(), N);
643
        for (i, child) in bar.children.as_ref().iter().enumerate() {
644
            assert_eq!(
645
                rendered_label(child),
646
                format!("item{i}"),
647
                "item {i} is misplaced"
648
            );
649
        }
650
        assert_children_count_is_in_sync(&bar);
651
    }
652

            
653
    #[test]
654
    fn build_menubar_dom_round_trips_every_item_into_its_own_submenu() {
655
        // Duplicate labels + interleaved separators: if the builder ever indexed
656
        // `menu.items` instead of iterating the *rendered* items, this mapping
657
        // would slip by one.
658
        let with_kids = leaf("File").with_children(MenuItemVec::from_vec(vec![
659
            string_item("New"),
660
            MenuItem::Separator,
661
            string_item("Open"),
662
        ]));
663
        let dup_a = leaf("Same").with_child(string_item("a"));
664
        let dup_b = leaf("Same").with_child(string_item("b"));
665
        let bare = leaf("Help");
666

            
667
        let m = menu_of(vec![
668
            MenuItem::Separator,
669
            MenuItem::String(with_kids.clone()),
670
            MenuItem::String(dup_a.clone()),
671
            MenuItem::BreakLine,
672
            MenuItem::String(dup_b.clone()),
673
            MenuItem::String(bare.clone()),
674
        ]);
675
        let bar = build_menubar_dom(&m);
676
        let children = bar.children.as_ref();
677
        assert_eq!(children.len(), 4);
678

            
679
        assert_eq!(
680
            labels_of(&submenu_of(&children[0])),
681
            vec!["New", "<sep>", "Open"]
682
        );
683
        assert_eq!(labels_of(&submenu_of(&children[1])), vec!["a"]);
684
        assert_eq!(labels_of(&submenu_of(&children[2])), vec!["b"]);
685
        // A top-level leaf opens a one-item menu of *itself* so its own callback
686
        // still fires.
687
        assert_eq!(
688
            submenu_of(&children[3]),
689
            Menu::create(MenuItemVec::from_vec(vec![MenuItem::String(bare)])),
690
        );
691
    }
692

            
693
    #[test]
694
    fn build_menubar_dom_gives_identical_items_distinct_backreferences() {
695
        let m = menu_of(vec![string_item("Same"), string_item("Same")]);
696
        let bar = build_menubar_dom(&m);
697

            
698
        let a = refany_of(&bar.children.as_ref()[0]);
699
        let b = refany_of(&bar.children.as_ref()[1]);
700
        assert!(
701
            a != b,
702
            "two bar items must not share one RefAny — dropping one would then invalidate the \
703
             other's submenu"
704
        );
705
        assert_eq!(
706
            a.get_type_id(),
707
            b.get_type_id(),
708
            "…while still both being Menus"
709
        );
710
    }
711

            
712
    #[test]
713
    fn build_menubar_dom_only_renders_the_top_level_of_a_deep_menu() {
714
        let deep = nested(64);
715
        let bar = build_menubar_dom(&menu_of(vec![MenuItem::String(deep.clone())]));
716

            
717
        assert_eq!(
718
            bar.children.as_ref().len(),
719
            1,
720
            "nesting depth is not bar width"
721
        );
722
        assert_children_count_is_in_sync(&bar);
723

            
724
        // Only the *direct* children are carried into the popup.
725
        let sub = submenu_of(&bar.children.as_ref()[0]);
726
        assert_eq!(sub.items.as_slice().len(), 1);
727
        assert_eq!(labels_of(&sub), vec!["lvl62"]);
728
    }
729

            
730
    #[test]
731
    fn build_menubar_dom_flattens_into_a_styled_dom_with_hit_testable_items() {
732
        let m = menu_of(vec![
733
            string_item("File"),
734
            MenuItem::Separator,
735
            string_item("Edit"),
736
        ]);
737
        let styled = StyledDom::create_from_dom(build_menubar_dom(&m));
738

            
739
        let items = item_node_ids(&styled);
740
        assert_eq!(items.len(), 2, "one flat node per rendered bar item");
741
        for id in items {
742
            // Panics with a clear message if the item lost its tag.
743
            let _tag = tag_of(&styled, id);
744
        }
745
    }
746

            
747
    // ==================================================================
748
    // build_menubar_item
749
    // ==================================================================
750

            
751
    #[test]
752
    fn build_menubar_item_wraps_a_leaf_verbatim_including_every_optional_field() {
753
        let item = decorated_leaf("Quit");
754
        let dom = build_menubar_item(&item);
755

            
756
        let sub = submenu_of(&dom);
757
        assert_eq!(
758
            sub,
759
            Menu::create(MenuItemVec::from_vec(vec![MenuItem::String(item.clone())])),
760
            "a leaf must be wrapped byte-for-byte — accelerator, callback, state and icon \
761
             included — or its own callback can never fire",
762
        );
763

            
764
        let MenuItem::String(wrapped) = &sub.items.as_slice()[0] else {
765
            panic!("the wrapped item must still be a String item");
766
        };
767
        assert_eq!(wrapped.menu_item_state, MenuItemState::Greyed);
768
        assert!(wrapped.accelerator.is_some());
769
        assert!(wrapped.icon.is_some());
770
        assert!(wrapped.callback.is_some());
771
    }
772

            
773
    #[test]
774
    fn build_menubar_item_with_children_opens_exactly_those_children() {
775
        let children = vec![
776
            string_item("New"),
777
            MenuItem::Separator,
778
            string_item("Open"),
779
            MenuItem::BreakLine,
780
            MenuItem::String(decorated_leaf("Quit")),
781
        ];
782
        let item = leaf("File").with_children(MenuItemVec::from_vec(children.clone()));
783
        let dom = build_menubar_item(&item);
784

            
785
        let sub = submenu_of(&dom);
786
        assert_eq!(
787
            sub,
788
            Menu::create(MenuItemVec::from_vec(children)),
789
            "a parent must open its children verbatim, not itself",
790
        );
791
        assert!(
792
            !labels_of(&sub).contains(&"File".to_string()),
793
            "a parent must NOT wrap itself — that would duplicate the top-level entry",
794
        );
795
    }
796

            
797
    #[test]
798
    fn build_menubar_item_registers_exactly_one_mouseup_hover_callback() {
799
        let dom = build_menubar_item(&leaf("File"));
800
        let cbs = dom.root.callbacks.as_ref();
801

            
802
        assert_eq!(cbs.len(), 1);
803
        assert_eq!(cbs[0].event, EventFilter::Hover(HoverEventFilter::Click));
804
        assert_eq!(
805
            cbs[0].callback.cb, menubar_item_click as usize,
806
            "the item must be wired to the menubar click handler",
807
        );
808
        assert!(
809
            matches!(cbs[0].callback.ctx, OptionRefAny::None),
810
            "a native Rust callback carries no FFI context",
811
        );
812
    }
813

            
814
    #[test]
815
    fn build_menubar_item_shape_is_one_class_one_text_child() {
816
        let huge = "z".repeat(100_000);
817
        for label in ["", "File", "👨‍👩‍👧‍👦", "a\u{0}b", huge.as_str()] {
818
            let dom = build_menubar_item(&leaf(label));
819

            
820
            assert_eq!(classes_of(&dom), vec![MENUBAR_ITEM_CLASS.to_string()]);
821
            assert_eq!(
822
                rendered_label(&dom),
823
                label,
824
                "the label must survive verbatim"
825
            );
826
            // The item, its label <p>, and the text leaf inside it. This was 1
827
            // when the item held a BARE text node; every widget label is a <p>
828
            // now, because a text leaf owns no box and misbehaves as a
829
            // flex/grid item.
830
            assert_eq!(dom.estimated_total_children, 2);
831
            assert_children_count_is_in_sync(&dom);
832
        }
833
    }
834

            
835
    #[test]
836
    fn build_menubar_item_is_pure_and_repeatable() {
837
        let item = leaf("File").with_child(string_item("New"));
838

            
839
        let a = build_menubar_item(&item);
840
        let b = build_menubar_item(&item);
841

            
842
        assert_eq!(submenu_of(&a), submenu_of(&b), "same input ⇒ same submenu");
843
        assert!(
844
            refany_of(&a) != refany_of(&b),
845
            "each build must allocate its own backreference",
846
        );
847
        // The source item is untouched (it is only ever cloned).
848
        assert_eq!(item.label.as_str(), "File");
849
        assert_eq!(item.children.as_slice().len(), 1);
850
    }
851

            
852
    #[test]
853
    fn build_menubar_item_treats_an_empty_child_vec_as_a_leaf() {
854
        let empty = leaf("Help").with_children(MenuItemVec::from_vec(Vec::new()));
855
        let sub = submenu_of(&build_menubar_item(&empty));
856

            
857
        assert_eq!(
858
            sub.items.as_slice().len(),
859
            1,
860
            "an explicitly-empty child vec is still a leaf, so it self-wraps rather than opening \
861
             an empty popup",
862
        );
863
        assert_eq!(labels_of(&sub), vec!["Help"]);
864
    }
865

            
866
    // ==================================================================
867
    // menubar_item_click
868
    // ==================================================================
869

            
870
    #[test]
871
    fn menubar_item_click_without_a_hit_node_queues_nothing() {
872
        let data = refany_of(&build_menubar_item(&leaf("File")));
873

            
874
        with_env(|env| {
875
            assert_eq!(
876
                menubar_item_click(data.clone(), env.info()),
877
                Update::DoNothing
878
            );
879
            assert!(
880
                env.take_changes().is_empty(),
881
                "no anchor ⇒ no half-opened menu",
882
            );
883
        });
884
    }
885

            
886
    #[test]
887
    fn menubar_item_click_without_layout_geometry_queues_nothing() {
888
        let m = menu_of(vec![string_item("File")]);
889
        let bar = build_menubar_dom(&m);
890
        let data = refany_of(&bar.children.as_ref()[0]);
891
        let styled = StyledDom::create_from_dom(bar);
892
        let item = item_node_ids(&styled)[0];
893

            
894
        // Flattened DOM, but no hit-test area for the item: the geometry lookup
895
        // must fail closed.
896
        with_anchored_env(styled, &[], item, |env| {
897
            assert_eq!(
898
                menubar_item_click(data.clone(), env.info()),
899
                Update::DoNothing
900
            );
901
            assert!(env.take_changes().is_empty());
902
        });
903
    }
904

            
905
    #[test]
906
    fn menubar_item_click_on_a_foreign_payload_is_a_no_op() {
907
        for mut data in [
908
            RefAny::new(0_u32),
909
            RefAny::new(String::from("not a menu")),
910
            RefAny::new(Vec::<u8>::new()),
911
        ] {
912
            with_env(|env| {
913
                assert_eq!(
914
                    menubar_item_click(data.clone(), env.info()),
915
                    Update::DoNothing,
916
                    "a wrong-typed backreference must be ignored, not downcast blindly",
917
                );
918
                assert!(env.take_changes().is_empty());
919
            });
920
            assert!(
921
                data.downcast_ref::<Menu>().is_none(),
922
                "…and the payload is still not a Menu afterwards",
923
            );
924
        }
925
    }
926

            
927
    #[test]
928
    fn menubar_item_click_opens_the_submenu_at_the_bottom_left_of_the_item() {
929
        let m = menu_of(vec![MenuItem::String(leaf("File").with_children(
930
            MenuItemVec::from_vec(vec![
931
                string_item("New"),
932
                MenuItem::Separator,
933
                string_item("Open"),
934
            ]),
935
        ))]);
936
        let bar = build_menubar_dom(&m);
937
        let data = refany_of(&bar.children.as_ref()[0]);
938
        let expected = submenu_of(&bar.children.as_ref()[0]);
939
        let styled = StyledDom::create_from_dom(bar);
940
        let item = item_node_ids(&styled)[0];
941

            
942
        let rect = LogicalRect::new(
943
            LogicalPosition::new(10.0, 20.0),
944
            LogicalSize::new(100.0, 26.0),
945
        );
946
        with_anchored_env(styled, &[(item, rect)], item, |env| {
947
            assert_eq!(
948
                menubar_item_click(data.clone(), env.info()),
949
                Update::DoNothing
950
            );
951

            
952
            let CallbackChange::OpenMenu {
953
                menu,
954
                position,
955
                anchor: _,
956
            } = env.take_one()
957
            else {
958
                panic!("expected exactly one OpenMenu change");
959
            };
960
            assert_eq!(
961
                menu, expected,
962
                "the queued menu must be the item's backreference"
963
            );
964

            
965
            let p = position.expect("the popup must be pinned under the bar item");
966
            assert_eq!((p.x, p.y), (10.0, 46.0), "bottom-left of the item rect");
967
        });
968
    }
969

            
970
    #[test]
971
    fn menubar_item_click_opens_each_bar_items_own_menu() {
972
        let m = menu_of(vec![
973
            MenuItem::String(leaf("File").with_child(string_item("New"))),
974
            MenuItem::Separator,
975
            MenuItem::String(leaf("Edit").with_child(string_item("Undo"))),
976
            MenuItem::String(leaf("Help")),
977
        ]);
978
        let bar = build_menubar_dom(&m);
979
        let payloads: Vec<RefAny> = bar.children.as_ref().iter().map(refany_of).collect();
980
        let styled = StyledDom::create_from_dom(bar);
981
        let items = item_node_ids(&styled);
982
        assert_eq!(items.len(), 3);
983

            
984
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(40.0, 26.0));
985
        let anchors: Vec<(NodeId, LogicalRect)> = items.iter().map(|n| (*n, rect)).collect();
986
        let expected = [vec!["New"], vec!["Undo"], vec!["Help"]];
987

            
988
        with_anchored_env(styled, &anchors, items[0], |env| {
989
            for (i, node) in items.iter().enumerate() {
990
                assert_eq!(
991
                    menubar_item_click(payloads[i].clone(), env.info_at(dom_node(*node))),
992
                    Update::DoNothing,
993
                );
994
                let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
995
                    panic!("item {i}: expected an OpenMenu change");
996
                };
997
                assert_eq!(
998
                    labels_of(&menu),
999
                    expected[i],
                    "item {i} opened the wrong menu"
                );
            }
        });
    }
    #[test]
    fn menubar_item_click_is_repeatable_and_does_not_consume_the_payload() {
        let bar = build_menubar_dom(&menu_of(vec![string_item("File")]));
        let mut data = refany_of(&bar.children.as_ref()[0]);
        let styled = StyledDom::create_from_dom(bar);
        let item = item_node_ids(&styled)[0];
        let rect = LogicalRect::new(LogicalPosition::new(1.0, 2.0), LogicalSize::new(3.0, 4.0));
        with_anchored_env(styled, &[(item, rect)], item, |env| {
            for round in 0..5 {
                assert_eq!(
                    menubar_item_click(data.clone(), env.info()),
                    Update::DoNothing
                );
                let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                    panic!("round {round}: expected an OpenMenu change");
                };
                assert_eq!(labels_of(&menu), vec!["File"]);
            }
        });
        assert!(
            data.downcast_ref::<Menu>().is_some(),
            "the backreference must survive repeated clicks",
        );
    }
    #[test]
    fn menubar_item_click_rejects_degenerate_anchor_rects() {
        // `get_node_hit_test_bounds` only accepts strictly positive extents, so
        // each of these must fail closed instead of queueing a menu at nowhere.
        let degenerate = [
            LogicalSize::new(0.0, 26.0),
            LogicalSize::new(100.0, 0.0),
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(-100.0, -26.0),
            LogicalSize::new(f32::NAN, 26.0),
            LogicalSize::new(100.0, f32::NAN),
            LogicalSize::new(f32::NAN, f32::NAN),
        ];
        for size in degenerate {
            let bar = build_menubar_dom(&menu_of(vec![string_item("File")]));
            let data = refany_of(&bar.children.as_ref()[0]);
            let styled = StyledDom::create_from_dom(bar);
            let item = item_node_ids(&styled)[0];
            let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), size);
            with_anchored_env(styled, &[(item, rect)], item, |env| {
                assert_eq!(
                    menubar_item_click(data.clone(), env.info()),
                    Update::DoNothing
                );
                assert!(
                    env.take_changes().is_empty(),
                    "a {size:?} anchor must not queue a menu",
                );
            });
        }
    }
    #[test]
    fn menubar_item_click_survives_non_finite_anchor_origins() {
        // Origin/height arithmetic (`origin.y + size.height`) is unchecked — it
        // must saturate to an infinity or NaN rather than panic.
        let cases = [
            (
                LogicalPosition::new(f32::MAX, f32::MAX),
                LogicalSize::new(1.0, f32::MAX),
            ),
            (
                LogicalPosition::new(f32::MIN, f32::MIN),
                LogicalSize::new(1.0, 1.0),
            ),
            (
                LogicalPosition::new(f32::NAN, f32::NAN),
                LogicalSize::new(1.0, 1.0),
            ),
            (
                LogicalPosition::new(f32::INFINITY, f32::NEG_INFINITY),
                LogicalSize::new(1.0, f32::INFINITY),
            ),
        ];
        for (origin, size) in cases {
            let bar = build_menubar_dom(&menu_of(vec![string_item("File")]));
            let data = refany_of(&bar.children.as_ref()[0]);
            let styled = StyledDom::create_from_dom(bar);
            let item = item_node_ids(&styled)[0];
            let rect = LogicalRect::new(origin, size);
            with_anchored_env(styled, &[(item, rect)], item, |env| {
                assert_eq!(
                    menubar_item_click(data.clone(), env.info()),
                    Update::DoNothing
                );
                let CallbackChange::OpenMenu { position, .. } = env.take_one() else {
                    panic!("expected an OpenMenu change for {origin:?}/{size:?}");
                };
                let p = position.expect("a positive-extent anchor still yields a position");
                let expected_y = origin.y + size.height;
                assert_eq!(p.x.is_nan(), origin.x.is_nan());
                if !p.x.is_nan() {
                    assert_eq!(p.x, origin.x);
                }
                assert_eq!(
                    p.y.is_nan(),
                    expected_y.is_nan(),
                    "NaN must propagate, not turn into a bogus finite coordinate",
                );
                if !p.y.is_nan() {
                    assert_eq!(p.y, expected_y, "y must saturate to origin.y + height");
                }
            });
        }
    }
    #[test]
    fn menubar_item_click_queues_an_empty_menu_for_an_empty_backreference() {
        // Not reachable through the builders (a leaf self-wraps), but the handler
        // must still not panic on a menu with no items.
        let bar = build_menubar_dom(&menu_of(vec![string_item("File")]));
        let data = RefAny::new(Menu::create(MenuItemVec::from_vec(Vec::new())));
        let styled = StyledDom::create_from_dom(bar);
        let item = item_node_ids(&styled)[0];
        let rect = LogicalRect::new(LogicalPosition::new(5.0, 5.0), LogicalSize::new(5.0, 5.0));
        with_anchored_env(styled, &[(item, rect)], item, |env| {
            assert_eq!(
                menubar_item_click(data.clone(), env.info()),
                Update::DoNothing
            );
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            assert!(
                menu.items.as_slice().is_empty(),
                "an empty menu is not a panic"
            );
        });
    }
    #[test]
    fn menubar_item_click_queues_a_wide_menu_without_truncation() {
        const N: usize = 500;
        let children: Vec<MenuItem> = (0..N).map(|i| string_item(&format!("c{i}"))).collect();
        let m = menu_of(vec![MenuItem::String(
            leaf("File").with_children(MenuItemVec::from_vec(children)),
        )]);
        let bar = build_menubar_dom(&m);
        let data = refany_of(&bar.children.as_ref()[0]);
        let styled = StyledDom::create_from_dom(bar);
        let item = item_node_ids(&styled)[0];
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(1.0, 1.0));
        with_anchored_env(styled, &[(item, rect)], item, |env| {
            assert_eq!(
                menubar_item_click(data.clone(), env.info()),
                Update::DoNothing
            );
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            assert_eq!(menu.items.as_slice().len(), N);
            assert_eq!(labels_of(&menu)[N - 1], format!("c{}", N - 1));
        });
    }
}