1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod accelerator_contract {
5
    use super::*;
6
    use crate::window::{VirtualKeyCode as K, VirtualKeyCodeVec};
7

            
8
9
    fn keyboard(down: &[K], pressed: K) -> KeyboardState {
9
9
        KeyboardState {
10
9
            pressed_virtual_keycodes: VirtualKeyCodeVec::from_vec(down.to_vec()),
11
9
            current_virtual_keycode: Some(pressed).into(),
12
9
            ..KeyboardState::default()
13
9
        }
14
9
    }
15
7
    fn combo(keys: &[K]) -> VirtualKeyCodeCombo {
16
7
        VirtualKeyCodeCombo {
17
7
            keys: VirtualKeyCodeVec::from_vec(keys.to_vec()),
18
7
        }
19
7
    }
20
    /// The modifier the platform treats as "primary" (`[LWin, x]` in a
21
    /// combo): Cmd on macOS, Ctrl elsewhere.
22
6
    fn primary() -> K {
23
6
        if cfg!(target_os = "macos") {
24
            K::LWin
25
        } else {
26
6
            K::LControl
27
        }
28
6
    }
29

            
30
    #[test]
31
1
    fn a_primary_chord_matches_the_platforms_primary_modifier_from_one_definition() {
32
1
        let save = combo(&[K::LWin, K::S]);
33
1
        assert!(accelerator_matches(
34
1
            &save,
35
1
            &keyboard(&[primary(), K::S], K::S),
36
1
            K::S
37
        ));
38
        // the bare key, or the wrong key, never
39
1
        assert!(!accelerator_matches(&save, &keyboard(&[K::S], K::S), K::S));
40
1
        assert!(!accelerator_matches(
41
1
            &save,
42
1
            &keyboard(&[primary(), K::O], K::O),
43
1
            K::O
44
1
        ));
45
1
    }
46

            
47
    #[test]
48
1
    fn the_match_is_exact_so_ctrl_s_and_ctrl_shift_s_coexist() {
49
1
        let save = combo(&[K::LWin, K::S]);
50
1
        let save_as = combo(&[K::LWin, K::LShift, K::S]);
51
1
        let ctrl_shift_s = keyboard(&[primary(), K::LShift, K::S], K::S);
52
1
        assert!(
53
1
            !accelerator_matches(&save, &ctrl_shift_s, K::S),
54
            "Shift held: not plain Ctrl+S"
55
        );
56
1
        assert!(accelerator_matches(&save_as, &ctrl_shift_s, K::S));
57
1
        let ctrl_s = keyboard(&[primary(), K::S], K::S);
58
1
        assert!(accelerator_matches(&save, &ctrl_s, K::S));
59
1
        assert!(
60
1
            !accelerator_matches(&save_as, &ctrl_s, K::S),
61
            "Shift missing: not Ctrl+Shift+S"
62
        );
63
        // right-hand twins count
64
1
        assert!(accelerator_matches(
65
1
            &combo(&[K::RShift, K::LWin, K::S]),
66
1
            &ctrl_shift_s,
67
1
            K::S
68
        ));
69
        // a combo naming two non-modifier keys is not a chord
70
1
        assert!(!accelerator_matches(
71
1
            &combo(&[K::A, K::S]),
72
1
            &keyboard(&[K::A, K::S], K::S),
73
1
            K::S
74
1
        ));
75
1
    }
76

            
77
    #[test]
78
1
    fn find_accelerated_item_walks_submenus_and_skips_disabled_items() {
79
1
        let mut greyed = StringMenuItem::create("Greyed".into());
80
1
        greyed.accelerator = Some(combo(&[K::LWin, K::G])).into();
81
1
        greyed.menu_item_state = MenuItemState::Greyed;
82
1
        let mut save = StringMenuItem::create("Save".into());
83
1
        save.accelerator = Some(combo(&[K::LWin, K::S])).into();
84
1
        let file = StringMenuItem::create("File".into()).with_children(
85
1
            alloc::vec![
86
1
                MenuItem::String(greyed),
87
1
                MenuItem::Separator,
88
1
                MenuItem::String(save)
89
            ]
90
1
            .into(),
91
        );
92
1
        let menu = Menu::create(alloc::vec![MenuItem::String(file)].into());
93
1
        let hit = menu
94
1
            .find_accelerated_item(&keyboard(&[primary(), K::S], K::S), K::S)
95
1
            .expect("Save is nested under File");
96
1
        assert_eq!(hit.label.as_str(), "Save");
97
1
        assert!(
98
1
            menu.find_accelerated_item(&keyboard(&[primary(), K::G], K::G), K::G)
99
1
                .is_none(),
100
            "a greyed item's accelerator is dead"
101
        );
102
1
        assert!(menu
103
1
            .find_accelerated_item(&keyboard(&[K::S], K::S), K::S)
104
1
            .is_none());
105
1
    }
106
}
107

            
108
#[cfg(test)]
109
mod autotest_generated {
110
    use alloc::{format, string::String, vec, vec::Vec};
111

            
112
    use super::*;
113
    use crate::{
114
        refany::RefAny,
115
        window::{ContextMenuMouseButton, VirtualKeyCodeCombo, VirtualKeyCodeVec},
116
    };
117

            
118
    const ALL_POSITIONS: [MenuPopupPosition; 10] = [
119
        MenuPopupPosition::BottomLeftOfCursor,
120
        MenuPopupPosition::BottomRightOfCursor,
121
        MenuPopupPosition::TopLeftOfCursor,
122
        MenuPopupPosition::TopRightOfCursor,
123
        MenuPopupPosition::BottomOfHitRect,
124
        MenuPopupPosition::LeftOfHitRect,
125
        MenuPopupPosition::TopOfHitRect,
126
        MenuPopupPosition::RightOfHitRect,
127
        MenuPopupPosition::AutoCursor,
128
        MenuPopupPosition::AutoHitRect,
129
    ];
130

            
131
    fn item(label: &str) -> MenuItem {
132
        MenuItem::String(StringMenuItem::create(label.into()))
133
    }
134

            
135
    fn item_vec(labels: &[&str]) -> MenuItemVec {
136
        labels.iter().map(|l| item(l)).collect::<Vec<_>>().into()
137
    }
138

            
139
    fn labels_of(v: &MenuItemVec) -> Vec<&str> {
140
        v.as_slice()
141
            .iter()
142
            .map(|i| match i {
143
                MenuItem::String(s) => s.label.as_str(),
144
                MenuItem::Separator => "<sep>",
145
                MenuItem::BreakLine => "<br>",
146
            })
147
            .collect()
148
    }
149

            
150
    fn all_distinct(hashes: &[u64]) -> bool {
151
        let mut sorted = hashes.to_vec();
152
        sorted.sort_unstable();
153
        sorted.dedup();
154
        sorted.len() == hashes.len()
155
    }
156

            
157
    // ---- Menu::create ---------------------------------------------------
158

            
159
    #[test]
160
    fn menu_create_defaults_and_extreme_inputs() {
161
        for items in [
162
            MenuItemVec::new(),
163
            MenuItemVec::from_const_slice(&[]),
164
            item_vec(&["a"]),
165
            vec![MenuItem::Separator; 10_000].into(),
166
        ] {
167
            let expected_len = items.len();
168
            let menu = Menu::create(items);
169
            assert_eq!(menu.items.len(), expected_len);
170
            assert_eq!(menu.position, MenuPopupPosition::AutoCursor);
171
            assert_eq!(menu.context_mouse_btn, ContextMenuMouseButton::Right);
172
            let _ = menu.get_hash();
173
        }
174
    }
175

            
176
    #[test]
177
    fn menu_create_preserves_item_order_and_contents() {
178
        let source = vec![
179
            item("File"),
180
            MenuItem::Separator,
181
            item("Edit"),
182
            MenuItem::BreakLine,
183
            item(""),
184
        ];
185
        let menu = Menu::create(source.clone().into());
186
        assert_eq!(menu.items.as_slice(), source.as_slice());
187
        assert_eq!(
188
            labels_of(&menu.items),
189
            ["File", "<sep>", "Edit", "<br>", ""]
190
        );
191
    }
192

            
193
    #[test]
194
    fn menu_create_of_empty_vec_equals_default() {
195
        // `create` documents AutoCursor + Right, which must agree with the derived Default.
196
        assert_eq!(Menu::create(MenuItemVec::new()), Menu::default());
197
        assert_eq!(
198
            Menu::create(MenuItemVec::new()).get_hash(),
199
            Menu::default().get_hash()
200
        );
201
    }
202

            
203
    #[test]
204
    fn menu_item_vec_roundtrip_through_library_owned_vec() {
205
        let source = vec![item("a"), MenuItem::Separator, item("\u{1F600}")];
206
        let decoded = MenuItemVec::from(source.clone()).into_library_owned_vec();
207
        assert_eq!(decoded, source);
208

            
209
        // The &'static (NoDestructor) backing must decode to an owned, equal Vec as well.
210
        assert!(MenuItemVec::from_const_slice(&[])
211
            .into_library_owned_vec()
212
            .is_empty());
213
    }
214

            
215
    // ---- Menu::with_position --------------------------------------------
216

            
217
    #[test]
218
    fn menu_with_position_sets_field_and_keeps_items() {
219
        for pos in ALL_POSITIONS {
220
            let menu = Menu::create(item_vec(&["a", "b"])).with_position(pos);
221
            assert_eq!(menu.position, pos);
222
            assert_eq!(menu.items.len(), 2);
223
            assert_eq!(labels_of(&menu.items), ["a", "b"]);
224
            assert_eq!(menu.context_mouse_btn, ContextMenuMouseButton::Right);
225
        }
226
    }
227

            
228
    #[test]
229
    fn menu_with_position_last_call_wins() {
230
        let menu = Menu::create(MenuItemVec::new())
231
            .with_position(MenuPopupPosition::TopOfHitRect)
232
            .with_position(MenuPopupPosition::LeftOfHitRect)
233
            .with_position(MenuPopupPosition::AutoHitRect);
234
        assert_eq!(menu.position, MenuPopupPosition::AutoHitRect);
235
    }
236

            
237
    // ---- Menu::get_hash --------------------------------------------------
238

            
239
    #[test]
240
    fn menu_get_hash_is_deterministic() {
241
        let build = || {
242
            Menu::create(item_vec(&["File", "Edit"])).with_position(MenuPopupPosition::TopOfHitRect)
243
        };
244
        let a = build();
245
        let b = build();
246
        assert_eq!(a.get_hash(), a.get_hash(), "repeated calls must agree");
247
        assert_eq!(
248
            a.get_hash(),
249
            b.get_hash(),
250
            "independently built equal menus must agree"
251
        );
252
    }
253

            
254
    #[test]
255
    fn menu_get_hash_on_empty_and_default_does_not_panic() {
256
        let heap_empty = Menu::create(MenuItemVec::new());
257
        let static_empty = Menu::create(MenuItemVec::from_const_slice(&[]));
258

            
259
        // Eq/Hash contract: the two empties compare equal, so they must hash equal.
260
        // A hash that mixed in `ptr`/`cap`/destructor would break here.
261
        assert_eq!(heap_empty, static_empty);
262
        assert_eq!(heap_empty.get_hash(), static_empty.get_hash());
263
        assert_eq!(Menu::default().get_hash(), heap_empty.get_hash());
264
    }
265

            
266
    #[test]
267
    fn menu_get_hash_reacts_to_position_and_mouse_button() {
268
        let hashes: Vec<u64> = ALL_POSITIONS
269
            .iter()
270
            .map(|p| Menu::create(item_vec(&["a"])).with_position(*p).get_hash())
271
            .collect();
272
        assert!(all_distinct(&hashes), "each popup position must hash apart");
273

            
274
        let btn_hashes: Vec<u64> = [
275
            ContextMenuMouseButton::Right,
276
            ContextMenuMouseButton::Middle,
277
            ContextMenuMouseButton::Left,
278
        ]
279
        .iter()
280
        .map(|b| {
281
            let mut menu = Menu::create(item_vec(&["a"]));
282
            menu.context_mouse_btn = *b;
283
            menu.get_hash()
284
        })
285
        .collect();
286
        assert!(all_distinct(&btn_hashes));
287
    }
288

            
289
    #[test]
290
    fn menu_get_hash_distinguishes_nesting_from_flattening() {
291
        // [a[b]] and [a, b] contain the same labels; a length-prefixed hash must separate them.
292
        let nested = Menu::create(MenuItemVec::from_item(MenuItem::String(
293
            StringMenuItem::create("a".into()).with_child(item("b")),
294
        )));
295
        let flat = Menu::create(item_vec(&["a", "b"]));
296
        assert_ne!(nested, flat);
297
        assert_ne!(nested.get_hash(), flat.get_hash());
298
    }
299

            
300
    #[test]
301
    fn menu_get_hash_distinguishes_item_kinds_and_states() {
302
        let sep = Menu::create(MenuItemVec::from_item(MenuItem::Separator));
303
        let br = Menu::create(MenuItemVec::from_item(MenuItem::BreakLine));
304
        assert_ne!(sep.get_hash(), br.get_hash());
305

            
306
        let with_state = |state: MenuItemState| {
307
            let mut s = StringMenuItem::create("x".into());
308
            s.menu_item_state = state;
309
            Menu::create(MenuItemVec::from_item(MenuItem::String(s))).get_hash()
310
        };
311
        assert!(all_distinct(&[
312
            with_state(MenuItemState::Normal),
313
            with_state(MenuItemState::Greyed),
314
            with_state(MenuItemState::Disabled),
315
        ]));
316

            
317
        let with_icon = |icon: OptionMenuItemIcon| {
318
            let mut s = StringMenuItem::create("x".into());
319
            s.icon = icon;
320
            Menu::create(MenuItemVec::from_item(MenuItem::String(s))).get_hash()
321
        };
322
        assert!(all_distinct(&[
323
            with_icon(OptionMenuItemIcon::None),
324
            with_icon(Some(MenuItemIcon::Checkbox(false)).into()),
325
            with_icon(Some(MenuItemIcon::Checkbox(true)).into()),
326
        ]));
327
    }
328

            
329
    #[test]
330
    fn menu_get_hash_separates_absent_accelerator_from_empty_one() {
331
        // `None` vs `Some(<empty combo>)` are different states and must not collide.
332
        let mut with_empty_combo = StringMenuItem::create("x".into());
333
        with_empty_combo.accelerator = Some(VirtualKeyCodeCombo {
334
            keys: VirtualKeyCodeVec::new(),
335
        })
336
        .into();
337

            
338
        let none = Menu::create(MenuItemVec::from_item(MenuItem::String(
339
            StringMenuItem::create("x".into()),
340
        )));
341
        let empty = Menu::create(MenuItemVec::from_item(MenuItem::String(with_empty_combo)));
342
        assert_ne!(none.get_hash(), empty.get_hash());
343
    }
344

            
345
    #[test]
346
    fn menu_get_hash_reacts_to_unicode_and_nul_labels() {
347
        let labels = [
348
            "",
349
            "a",
350
            "a\u{0}b",
351
            "a\u{0}",
352
            "\u{0}a",
353
            "e\u{301}",                   // combining acute
354
            "\u{e9}",                     // precomposed é — different bytes, must hash apart
355
            "\u{202e}x",                  // RTL override
356
            "\u{1F469}\u{200D}\u{1F4BB}", // ZWJ emoji sequence
357
            "\u{10FFFF}",
358
        ];
359
        let hashes: Vec<u64> = labels
360
            .iter()
361
            .map(|l| Menu::create(item_vec(&[l])).get_hash())
362
            .collect();
363
        assert!(all_distinct(&hashes), "distinct labels must hash apart");
364

            
365
        for l in labels {
366
            let a = Menu::create(item_vec(&[l]));
367
            let b = Menu::create(item_vec(&[l]));
368
            assert_eq!(a.get_hash(), b.get_hash());
369
        }
370
    }
371

            
372
    #[test]
373
    fn menu_get_hash_handles_large_menus() {
374
        let mut labels: Vec<String> = (0..10_000).map(|i| format!("item-{i}")).collect();
375
        let big: MenuItemVec = labels
376
            .iter()
377
            .map(|l| item(l.as_str()))
378
            .collect::<Vec<_>>()
379
            .into();
380
        let menu = Menu::create(big);
381
        assert_eq!(menu.items.len(), 10_000);
382
        assert_eq!(menu.get_hash(), menu.get_hash());
383

            
384
        // A single flipped label anywhere in a 10k menu must change the hash.
385
        labels[9_999] = String::from("item-flipped");
386
        let flipped = Menu::create(
387
            labels
388
                .iter()
389
                .map(|l| item(l.as_str()))
390
                .collect::<Vec<_>>()
391
                .into(),
392
        );
393
        assert_ne!(menu.get_hash(), flipped.get_hash());
394
    }
395

            
396
    #[test]
397
    fn menu_get_hash_survives_deeply_nested_submenus() {
398
        // Hash + drop glue both recurse once per level. Depth is bounded deliberately:
399
        // an unbounded depth would abort the whole test binary on stack exhaustion
400
        // rather than fail one test.
401
        const DEPTH: usize = 200;
402
        let mut nested = StringMenuItem::create("leaf".into());
403
        for i in 0..DEPTH {
404
            nested = StringMenuItem::create(format!("lvl-{i}").as_str().into())
405
                .with_child(MenuItem::String(nested));
406
        }
407
        let menu = Menu::create(MenuItemVec::from_item(MenuItem::String(nested)));
408
        assert_eq!(menu.get_hash(), menu.get_hash());
409
    }
410

            
411
    #[test]
412
    fn menu_get_hash_is_stable_across_clone_without_callbacks() {
413
        let menu = Menu::create(item_vec(&["File", "Edit"]))
414
            .with_position(MenuPopupPosition::BottomOfHitRect);
415
        let cloned = menu.clone();
416
        assert_eq!(menu, cloned);
417
        assert_eq!(menu.get_hash(), cloned.get_hash());
418
    }
419

            
420
    /// FIXED (was: "KNOWN HAZARD — pinned, not weakened"). `RefAny::clone()` still mints a
421
    /// fresh `instance_id`, but `instance_id` is no longer part of `RefAny`'s `Hash`/`Eq` —
422
    /// those now key on `sharing_info` alone (see the comment on `RefAny` in
423
    /// `core/src/refany.rs`). A menu carrying a callback is therefore equal to its own
424
    /// clone, and `get_hash()` — whose documented job is change detection for caching — no
425
    /// longer reports "changed" for a structurally identical menu.
426
    ///
427
    /// The old test asserted the broken behaviour on purpose, "so that fixing `RefAny`
428
    /// flips it loudly instead of silently". It did exactly that; this is the flip.
429
    #[test]
430
    fn menu_get_hash_is_stable_across_clone_with_callback() {
431
        let menu = Menu::create(MenuItemVec::from_item(MenuItem::String(
432
            StringMenuItem::create("Save".into()).with_callback(RefAny::new(1u32), 0xDEAD_usize),
433
        )));
434
        let cloned = menu.clone();
435
        assert_eq!(
436
            menu, cloned,
437
            "a clone shares the same RefAny data, so it must compare equal"
438
        );
439
        assert_eq!(menu.get_hash(), cloned.get_hash());
440
    }
441

            
442
    // ---- StringMenuItem::create ------------------------------------------
443

            
444
    #[test]
445
    fn string_menu_item_create_defaults() {
446
        let it = StringMenuItem::create("File".into());
447
        assert_eq!(it.label.as_str(), "File");
448
        assert!(it.accelerator.is_none());
449
        assert!(it.callback.is_none());
450
        assert_eq!(it.menu_item_state, MenuItemState::Normal);
451
        assert!(it.icon.is_none());
452
        assert!(it.children.is_empty());
453
        assert_eq!(it.children.len(), 0);
454
    }
455

            
456
    #[test]
457
    fn string_menu_item_create_preserves_extreme_labels() {
458
        let huge = "\u{1F600}".repeat(256 * 1024); // ~1 MiB of 4-byte chars
459
        for label in [
460
            String::new(),
461
            String::from("a\u{0}b"),
462
            String::from("\u{202e}\u{200d}\u{feff}"),
463
            "x".repeat(1024 * 1024),
464
            huge,
465
        ] {
466
            let it = StringMenuItem::create(label.as_str().into());
467
            assert_eq!(
468
                it.label.as_str(),
469
                label.as_str(),
470
                "label must survive byte-for-byte"
471
            );
472
            assert_eq!(it.label.as_str().len(), label.len());
473
            assert!(it.children.is_empty());
474
        }
475
    }
476

            
477
    // ---- StringMenuItem::with_children -----------------------------------
478

            
479
    #[test]
480
    fn with_children_sets_replaces_and_clears() {
481
        let it = StringMenuItem::create("File".into()).with_children(item_vec(&["New", "Open"]));
482
        assert_eq!(it.children.len(), 2);
483
        assert_eq!(labels_of(&it.children), ["New", "Open"]);
484

            
485
        // Last call wins — it is a setter, not an appender.
486
        let it = it.with_children(item_vec(&["Only"]));
487
        assert_eq!(it.children.len(), 1);
488
        assert_eq!(labels_of(&it.children), ["Only"]);
489

            
490
        let it = it.with_children(MenuItemVec::new());
491
        assert!(it.children.is_empty());
492
        assert_eq!(it.children.get(0), None);
493
    }
494

            
495
    #[test]
496
    fn with_children_keeps_other_fields_and_accepts_large_input() {
497
        let big: MenuItemVec = (0..5_000)
498
            .map(|i| item(format!("c{i}").as_str()))
499
            .collect::<Vec<_>>()
500
            .into();
501
        let it = StringMenuItem::create("root".into()).with_children(big);
502
        assert_eq!(it.label.as_str(), "root");
503
        assert_eq!(it.children.len(), 5_000);
504
        assert_eq!(it.menu_item_state, MenuItemState::Normal);
505
        assert!(it.callback.is_none());
506
        match it.children.get(4_999) {
507
            Some(MenuItem::String(s)) => assert_eq!(s.label.as_str(), "c4999"),
508
            other => panic!("unexpected tail item: {other:?}"),
509
        }
510
        assert_eq!(it.children.get(5_000), None, "index at len must be None");
511
    }
512

            
513
    // ---- StringMenuItem::with_child --------------------------------------
514

            
515
    #[test]
516
    fn with_child_copies_out_of_the_static_backing() {
517
        // `create` seeds `children` with a NoDestructor (&'static) vec; the first push must
518
        // copy out of it rather than write through the static pointer.
519
        let it = StringMenuItem::create("File".into()).with_child(item("New"));
520
        assert_eq!(it.children.len(), 1);
521
        assert_eq!(labels_of(&it.children), ["New"]);
522
        assert!(it.children.capacity() >= 1);
523

            
524
        // A freshly created sibling must still see an empty child list.
525
        assert!(StringMenuItem::create("Edit".into()).children.is_empty());
526
    }
527

            
528
    #[test]
529
    fn with_child_appends_in_order_and_after_with_children() {
530
        let it = StringMenuItem::create("File".into())
531
            .with_child(item("a"))
532
            .with_child(MenuItem::Separator)
533
            .with_child(item("b"));
534
        assert_eq!(labels_of(&it.children), ["a", "<sep>", "b"]);
535

            
536
        // with_child appends onto whatever with_children installed.
537
        let it = StringMenuItem::create("File".into())
538
            .with_children(item_vec(&["x"]))
539
            .with_child(item("y"));
540
        assert_eq!(labels_of(&it.children), ["x", "y"]);
541
    }
542

            
543
    #[test]
544
    fn with_child_does_not_alias_a_clone() {
545
        let base = StringMenuItem::create("File".into()).with_child(item("shared"));
546
        let extended = base.clone().with_child(item("extra"));
547
        assert_eq!(
548
            base.children.len(),
549
            1,
550
            "clone must not write back into the original"
551
        );
552
        assert_eq!(extended.children.len(), 2);
553
        assert_eq!(labels_of(&extended.children), ["shared", "extra"]);
554
    }
555

            
556
    #[test]
557
    fn with_child_repeated_many_times_keeps_contents() {
558
        // Every call round-trips the vec through into_library_owned_vec(); a mishandled
559
        // destructor tag here would surface as corruption/UAF (also exercised under Miri).
560
        const N: usize = 2_000;
561
        let mut it = StringMenuItem::create("root".into());
562
        for i in 0..N {
563
            it = it.with_child(item(format!("c{i}").as_str()));
564
        }
565
        assert_eq!(it.children.len(), N);
566
        assert_eq!(labels_of(&it.children)[0], "c0");
567
        assert_eq!(labels_of(&it.children)[N - 1], "c1999");
568
        assert_eq!(it.label.as_str(), "root");
569
    }
570

            
571
    // ---- StringMenuItem::with_callback -----------------------------------
572

            
573
    #[test]
574
    fn with_callback_stores_pointer_value_and_data() {
575
        for cb in [0_usize, 1, usize::MAX, usize::MAX - 1] {
576
            let mut it =
577
                StringMenuItem::create("Save".into()).with_callback(RefAny::new(42u64), cb);
578
            assert!(it.callback.is_some());
579
            {
580
                let stored = it.callback.as_ref().expect("callback set");
581
                assert_eq!(
582
                    stored.callback.cb, cb,
583
                    "raw fn-pointer usize must survive verbatim"
584
                );
585
                assert!(
586
                    stored.callback.ctx.is_none(),
587
                    "native Rust callbacks carry no FFI ctx"
588
                );
589
            }
590
            let data = it.callback.as_mut().expect("callback set");
591
            let value = data.refany.downcast_ref::<u64>().expect("payload is u64");
592
            assert_eq!(*value, 42u64);
593
        }
594
    }
595

            
596
    #[test]
597
    fn with_callback_keeps_other_fields_and_last_call_wins() {
598
        let it = StringMenuItem::create("Save".into())
599
            .with_children(item_vec(&["kid"]))
600
            .with_callback(RefAny::new(1u8), 111_usize)
601
            .with_callback(RefAny::new(2u8), 222_usize);
602

            
603
        let stored = it.callback.as_ref().expect("callback set");
604
        assert_eq!(stored.callback.cb, 222_usize);
605
        assert_eq!(it.label.as_str(), "Save");
606
        assert_eq!(it.children.len(), 1, "callback must not disturb children");
607
        assert_eq!(it.menu_item_state, MenuItemState::Normal);
608
    }
609

            
610
    #[test]
611
    fn with_callback_changes_menu_hash() {
612
        let plain = Menu::create(MenuItemVec::from_item(MenuItem::String(
613
            StringMenuItem::create("Save".into()),
614
        )));
615
        let with_cb = Menu::create(MenuItemVec::from_item(MenuItem::String(
616
            StringMenuItem::create("Save".into()).with_callback(RefAny::new(1u32), 7_usize),
617
        )));
618
        assert_ne!(plain.get_hash(), with_cb.get_hash());
619
    }
620
}