1
//! Menu system for context menus, dropdown menus, and application menus.
2
//!
3
//! This module provides a cross-platform menu abstraction modeled after the Windows API,
4
//! supporting hierarchical menus with separators, icons, keyboard accelerators, and callbacks.
5
//!
6
//! # Core vs Layout Types
7
//!
8
//! This module uses `CoreMenuCallback` with `usize` placeholders instead of function pointers
9
//! to avoid circular dependencies between `azul-core` and `azul-layout`. The actual function
10
//! pointers are stored in `azul-layout` and converted via unsafe code with identical memory
11
//! layout.
12

            
13
extern crate alloc;
14

            
15
use alloc::vec::Vec;
16
use core::hash::Hash;
17

            
18
use azul_css::AzString;
19

            
20
use crate::{
21
    callbacks::{CoreCallback, CoreCallbackType},
22
    refany::RefAny,
23
    resources::ImageRef,
24
    window::{
25
        ContextMenuMouseButton, KeyboardState, OptionVirtualKeyCodeCombo, VirtualKeyCode,
26
        VirtualKeyCodeCombo,
27
    },
28
};
29

            
30
/// Does `combo` describe the chord the keyboard is in, with `pressed` as the
31
/// key that just went down?
32
///
33
/// THE shared accelerator rule, used by every platform that dispatches menu
34
/// accelerators itself (Windows, X11, Wayland, headless; macOS's menu bar
35
/// uses `AppKit` key equivalents, its context menus this).
36
///
37
/// * The combo names its modifiers with the modifier keys (`LControl`, `LShift`, `LAlt`, `LWin`;
38
///   the right-hand twins are equivalent) and exactly ONE non-modifier key, which must be
39
///   `pressed`.
40
/// * `LWin` / `RWin` mean the platform's PRIMARY shortcut modifier — Cmd on macOS, Ctrl everywhere
41
///   else — so `[LWin, S]` is Cmd+S on a Mac and Ctrl+S on Windows/Linux from one definition (the
42
///   MWA-A2 rule behind `KeyboardState::primary_down`). `LControl` stays the Control key on every
43
///   platform.
44
/// * The match is EXACT: `Ctrl+S` does not fire while Shift is also held, so `Ctrl+S` and
45
///   `Ctrl+Shift+S` can coexist in one menu.
46
#[must_use]
47
12
pub fn accelerator_matches(
48
12
    combo: &VirtualKeyCodeCombo,
49
12
    keyboard: &KeyboardState,
50
12
    pressed: VirtualKeyCode,
51
12
) -> bool {
52
12
    let mut want_ctrl = false;
53
12
    let mut want_shift = false;
54
12
    let mut want_alt = false;
55
12
    let mut want_primary = false;
56
12
    let mut main_key: Option<VirtualKeyCode> = None;
57
27
    for key in combo.keys.as_ref() {
58
27
        match key {
59
            VirtualKeyCode::LControl | VirtualKeyCode::RControl => want_ctrl = true,
60
3
            VirtualKeyCode::LShift | VirtualKeyCode::RShift => want_shift = true,
61
            VirtualKeyCode::LAlt | VirtualKeyCode::RAlt => want_alt = true,
62
11
            VirtualKeyCode::LWin | VirtualKeyCode::RWin => want_primary = true,
63
13
            other => {
64
13
                if main_key.is_some() {
65
                    // Two non-modifier keys: not a chord this rule can match.
66
1
                    return false;
67
12
                }
68
12
                main_key = Some(*other);
69
            }
70
        }
71
    }
72
11
    if main_key != Some(pressed) {
73
2
        return false;
74
9
    }
75
9
    if want_shift != keyboard.shift_down() || want_alt != keyboard.alt_down() {
76
2
        return false;
77
7
    }
78
7
    if cfg!(target_os = "macos") {
79
        want_ctrl == keyboard.ctrl_down() && want_primary == keyboard.super_down()
80
    } else {
81
        // Ctrl IS the primary modifier here; the Super/Windows key never
82
        // takes part in an application chord.
83
7
        (want_ctrl || want_primary) == keyboard.ctrl_down() && !keyboard.super_down()
84
    }
85
12
}
86

            
87
/// Depth-first search of `items` for the first enabled entry whose
88
/// accelerator matches the chord (see [`accelerator_matches`]).
89
11
fn find_accelerated_in<'a>(
90
11
    items: &'a [MenuItem],
91
11
    keyboard: &KeyboardState,
92
11
    pressed: VirtualKeyCode,
93
11
) -> Option<&'a StringMenuItem> {
94
21
    for item in items {
95
12
        let MenuItem::String(s) = item else {
96
3
            continue;
97
        };
98
9
        if s.menu_item_state == MenuItemState::Normal {
99
6
            if let OptionVirtualKeyCodeCombo::Some(combo) = &s.accelerator {
100
3
                if accelerator_matches(combo, keyboard, pressed) {
101
1
                    return Some(s);
102
2
                }
103
3
            }
104
3
        }
105
8
        if let Some(found) = find_accelerated_in(s.children.as_ref(), keyboard, pressed) {
106
1
            return Some(found);
107
7
        }
108
    }
109
9
    None
110
11
}
111

            
112
/// Represents a menu (context menu, dropdown menu, or application menu).
113
///
114
/// A menu consists of a list of items that can be displayed as a popup or
115
/// attached to a window's menu bar. Modeled after the Windows API for
116
/// cross-platform consistency.
117
///
118
/// # Fields
119
///
120
/// * `items` - The menu items to display
121
/// * `position` - Where the menu should appear (for popups)
122
/// * `context_mouse_btn` - Which mouse button triggers the context menu
123
#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
124
#[repr(C)]
125
pub struct Menu {
126
    pub items: MenuItemVec,
127
    pub position: MenuPopupPosition,
128
    pub context_mouse_btn: ContextMenuMouseButton,
129
}
130

            
131
impl_option!(
132
    Menu,
133
    OptionMenu,
134
    copy = false,
135
    [Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord]
136
);
137

            
138
impl Menu {
139
    /// The first enabled item anywhere in this menu whose accelerator
140
    /// matches the chord the keyboard is in, `pressed` being the key that
141
    /// just went down. Greyed / disabled items never match.
142
    #[must_use]
143
3
    pub fn find_accelerated_item<'a>(
144
3
        &'a self,
145
3
        keyboard: &KeyboardState,
146
3
        pressed: VirtualKeyCode,
147
3
    ) -> Option<&'a StringMenuItem> {
148
3
        find_accelerated_in(self.items.as_ref(), keyboard, pressed)
149
3
    }
150

            
151
    /// Creates a new menu with the given items.
152
    ///
153
    /// Uses default position (`AutoCursor`) and right mouse button for context menus.
154
    #[must_use]
155
15945
    pub const fn create(items: MenuItemVec) -> Self {
156
15945
        Self {
157
15945
            items,
158
15945
            position: MenuPopupPosition::AutoCursor,
159
15945
            context_mouse_btn: ContextMenuMouseButton::Right,
160
15945
        }
161
15945
    }
162

            
163
    /// Builder method to set the popup position.
164
    #[must_use]
165
26
    pub const fn with_position(mut self, position: MenuPopupPosition) -> Self {
166
26
        self.position = position;
167
26
        self
168
26
    }
169

            
170
    /// Computes a 64-bit hash of this menu using the `HighwayHash` algorithm.
171
    ///
172
    /// This is used to detect changes in menu structure for caching and optimization.
173
    #[must_use]
174
81
    pub fn get_hash(&self) -> u64 {
175
        use core::hash::Hasher;
176
81
        let mut hasher = crate::hash::DefaultHasher::new();
177
81
        self.hash(&mut hasher);
178
81
        hasher.finish()
179
81
    }
180
}
181

            
182
/// Specifies where a popup menu should appear relative to the cursor or clicked element.
183
///
184
/// This positioning information is ignored for application-level menus (menu bars)
185
/// and only applies to context menus and dropdowns.
186
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash, Eq, Ord, Default)]
187
#[repr(C)]
188
pub enum MenuPopupPosition {
189
    /// Position menu below and to the left of the cursor
190
    BottomLeftOfCursor,
191
    /// Position menu below and to the right of the cursor
192
    BottomRightOfCursor,
193
    /// Position menu above and to the left of the cursor
194
    TopLeftOfCursor,
195
    /// Position menu above and to the right of the cursor
196
    TopRightOfCursor,
197
    /// Position menu below the rectangle that was clicked
198
    BottomOfHitRect,
199
    /// Position menu to the left of the rectangle that was clicked
200
    LeftOfHitRect,
201
    /// Position menu above the rectangle that was clicked
202
    TopOfHitRect,
203
    /// Position menu to the right of the rectangle that was clicked
204
    RightOfHitRect,
205
    /// Automatically calculate position based on available screen space near cursor
206
    #[default]
207
    AutoCursor,
208
    /// Automatically calculate position based on available screen space near clicked rect
209
    AutoHitRect,
210
}
211

            
212
/// Describes the interactive state of a menu item.
213
///
214
/// Menu items can be in different states that affect their appearance and behavior:
215
///
216
/// - Normal items are clickable and render normally
217
/// - Greyed items are visually disabled (greyed out) and non-clickable
218
/// - Disabled items are non-clickable but retain normal appearance
219
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
220
#[repr(C)]
221
pub enum MenuItemState {
222
    /// Normal menu item (default)
223
    Normal,
224
    /// Menu item is greyed out and clicking it does nothing
225
    Greyed,
226
    /// Menu item is disabled, but NOT greyed out
227
    Disabled,
228
}
229
#[allow(variant_size_differences)]
230
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
231
// disparity accepted
232
/// Represents a single item in a menu.
233
///
234
/// Menu items can be regular text items with labels and callbacks,
235
/// visual separators, or line breaks for horizontal menu layouts.
236
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
237
#[repr(C, u8)]
238
#[allow(clippy::large_enum_variant)] // #[repr(C,u8)] FFI enum: boxing a variant changes the C
239
                                     // ABI/api.json
240
pub enum MenuItem {
241
    /// A regular menu item with a label, optional icon, callback, and sub-items
242
    String(StringMenuItem),
243
    /// A visual separator line (only rendered in vertical layouts)
244
    Separator,
245
    /// Forces a line break when the menu is laid out horizontally
246
    BreakLine,
247
}
248

            
249
impl_option!(
250
    MenuItem,
251
    OptionMenuItem,
252
    copy = false,
253
    [Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord]
254
);
255

            
256
impl_vec!(
257
    MenuItem,
258
    MenuItemVec,
259
    MenuItemVecDestructor,
260
    MenuItemVecDestructorType,
261
    MenuItemVecSlice,
262
    OptionMenuItem
263
);
264
impl_vec_clone!(MenuItem, MenuItemVec, MenuItemVecDestructor);
265
impl_vec_debug!(MenuItem, MenuItemVec);
266
impl_vec_partialeq!(MenuItem, MenuItemVec);
267
impl_vec_partialord!(MenuItem, MenuItemVec);
268
impl_vec_hash!(MenuItem, MenuItemVec);
269
impl_vec_eq!(MenuItem, MenuItemVec);
270
impl_vec_ord!(MenuItem, MenuItemVec);
271

            
272
/// A menu item with a text label and optional features.
273
///
274
/// `StringMenuItem` represents a clickable menu entry that can have:
275
///
276
/// - A text label
277
/// - An optional keyboard accelerator (e.g., Ctrl+C)
278
/// - An optional callback function
279
/// - An optional icon (checkbox or image)
280
/// - A state (normal, greyed, or disabled)
281
/// - Child menu items (for sub-menus)
282
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
283
#[repr(C)]
284
pub struct StringMenuItem {
285
    /// Label of the menu
286
    /// (ex. "File", "Edit", "View")
287
    pub label: AzString,
288
    /// Optional accelerator combination
289
    /// (ex. "CTRL + X" = [`VirtualKeyCode::Ctrl`, `VirtualKeyCode::X`]) for keyboard shortcut
290
    pub accelerator: OptionVirtualKeyCodeCombo,
291
    /// Optional callback to call
292
    pub callback: OptionCoreMenuCallback,
293
    /// State (normal, greyed, disabled)
294
    pub menu_item_state: MenuItemState,
295
    /// Optional icon for the menu entry
296
    pub icon: OptionMenuItemIcon,
297
    /// Sub-menus of this item (separators and line-breaks can't have sub-menus)
298
    pub children: MenuItemVec,
299
}
300

            
301
impl StringMenuItem {
302
    /// Creates a new menu item with the given label.
303
    /// All optional fields default to `None` / `Normal`.
304
    #[must_use]
305
49412
    pub const fn create(label: AzString) -> Self {
306
49412
        Self {
307
49412
            label,
308
49412
            accelerator: OptionVirtualKeyCodeCombo::None,
309
49412
            callback: OptionCoreMenuCallback::None,
310
49412
            menu_item_state: MenuItemState::Normal,
311
49412
            icon: OptionMenuItemIcon::None,
312
49412
            children: MenuItemVec::from_const_slice(&[]),
313
49412
        }
314
49412
    }
315

            
316
    /// Sets the child menu items for this item, creating a sub-menu.
317
    #[must_use]
318
295
    pub fn with_children(mut self, children: MenuItemVec) -> Self {
319
295
        self.children = children;
320
295
        self
321
295
    }
322

            
323
    /// Adds a single child menu item to this item.
324
    #[must_use]
325
3036
    pub fn with_child(mut self, child: MenuItem) -> Self {
326
3036
        let mut children = self.children.into_library_owned_vec();
327
3036
        children.push(child);
328
3036
        self.children = children.into();
329
3036
        self
330
3036
    }
331

            
332
    /// Attaches a callback function to this menu item.
333
    ///
334
    /// # Parameters
335
    ///
336
    /// * `data` - User data passed to the callback
337
    /// * `callback` - Function pointer (as usize) to invoke when item is clicked
338
    ///
339
    /// # Note
340
    ///
341
    /// This uses `CoreCallbackType` (usize) instead of a real function pointer
342
    /// to avoid circular dependencies. The conversion happens in azul-layout.
343
    #[must_use]
344
59
    pub fn with_callback<I: Into<CoreCallback>>(mut self, data: RefAny, callback: I) -> Self {
345
59
        self.callback = Some(CoreMenuCallback {
346
59
            refany: data,
347
59
            callback: callback.into(),
348
59
        })
349
59
        .into();
350
59
        self
351
59
    }
352
}
353

            
354
/// Optional icon displayed next to a menu item.
355
///
356
/// Icons can be either:
357
/// - A checkbox (checked or unchecked)
358
/// - A custom image (typically 16x16 pixels)
359
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
360
#[repr(C, u8)]
361
pub enum MenuItemIcon {
362
    /// Displays a checkbox, with `true` = checked, `false` = unchecked
363
    Checkbox(bool),
364
    /// Displays a custom image (typically 16x16 format)
365
    Image(ImageRef),
366
}
367

            
368
impl_option!(
369
    MenuItemIcon,
370
    OptionMenuItemIcon,
371
    copy = false,
372
    [Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord]
373
);
374

            
375
// Core menu callback types (usize-based placeholders)
376
//
377
// Similar to CoreCallback, these use usize instead of function pointers
378
// to avoid circular dependencies. Will be converted to real function
379
// pointers in azul-layout.
380
//
381
// IMPORTANT: Memory layout must be identical to the real callback types!
382
// Tests for this are in azul-layout/src/callbacks.rs
383

            
384
/// Menu callback using usize placeholder for function pointer.
385
///
386
/// This type is used in `azul-core` to represent menu item callbacks without
387
/// creating circular dependencies with `azul-layout`. The actual function pointer
388
/// is stored as a `usize` and converted via unsafe code in `azul-layout`.
389
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
390
#[repr(C)]
391
pub struct CoreMenuCallback {
392
    /// User data passed to the callback when the menu item is clicked
393
    pub refany: RefAny,
394
    /// Callback function pointer stored as usize (converted to real fn pointer in azul-layout)
395
    pub callback: CoreCallback,
396
}
397

            
398
impl_option!(
399
    CoreMenuCallback,
400
    OptionCoreMenuCallback,
401
    copy = false,
402
    [Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord]
403
);
404

            
405
#[cfg(test)]
406
#[path = "menu_test.rs"]
407
mod menu_test;