native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use crate::artprov::IconRole;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MenuId(pub u64);

impl MenuId {
    /// Returns the raw numeric identifier.
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for MenuId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "menu {}", self.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MenuItemId(pub u64);

impl MenuItemId {
    /// Returns the raw numeric identifier.
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for MenuItemId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "menu item {}", self.0)
    }
}

/// In-memory specification and descriptor of one menu item.
///
/// Models native or simulated menu items across platforms: unique [`MenuItemId`],
/// visible label text (with access-key mnemonics), optional keyboard accelerator
/// shortcut (e.g. `"Ctrl+N"`), optional stock-art icon ([`IconRole`]), enabled/checked
/// states, and visibility.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MenuItemSpec {
    /// Stable application-facing item identifier.
    pub id: MenuItemId,
    /// Visible text/label (also carries mnemonic access-key markers such as `&File`).
    pub label: String,
    /// Optional keyboard accelerator shortcut string (e.g. `"Ctrl+N"`).
    pub shortcut: Option<String>,
    /// Optional stock-art icon role resolved by the art provider.
    pub icon: Option<IconRole>,
    /// Whether the menu item can be activated.
    pub enabled: bool,
    /// Whether the menu item is visible.
    pub visible: bool,
    /// Whether the menu item supports a checked/toggle state.
    pub checkable: bool,
    /// Current checked state for checkable items.
    pub checked: bool,
    /// Optional submenu identifier attached to this item.
    pub submenu: Option<MenuId>,
}

impl MenuItemSpec {
    /// Creates an enabled, visible, plain menu item specification.
    pub fn new(id: MenuItemId, label: impl Into<String>) -> Self {
        Self {
            id,
            label: label.into(),
            shortcut: None,
            icon: None,
            enabled: true,
            visible: true,
            checkable: false,
            checked: false,
            submenu: None,
        }
    }

    /// Creates an unassigned menu item specification with a placeholder ID (0).
    pub fn unassigned(label: impl Into<String>) -> Self {
        Self::new(MenuItemId(0), label)
    }

    /// Sets the keyboard shortcut hint (e.g. `"Ctrl+N"`).
    pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    /// Sets the stock-art icon role.
    pub fn with_icon(mut self, icon: IconRole) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Sets or clears the stock-art icon role with an optional value.
    pub fn with_optional_icon(mut self, icon: Option<IconRole>) -> Self {
        self.icon = icon;
        self
    }

    /// Sets the stock-art icon role from its stable identifier (e.g. `"new"`, `"open"`).
    pub fn with_icon_identifier(mut self, identifier: &str) -> Self {
        self.icon = IconRole::ALL
            .iter()
            .copied()
            .find(|r| r.as_str() == identifier);
        self
    }

    /// Sets the enabled state.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Sets the visibility state.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Marks the menu item as checkable.
    pub fn with_checkable(mut self) -> Self {
        self.checkable = true;
        self
    }

    /// Sets the checked state (and marks the item as checkable).
    pub fn with_checked(mut self, checked: bool) -> Self {
        self.checkable = true;
        self.checked = checked;
        self
    }

    /// Sets the attached submenu id.
    pub fn with_submenu(mut self, submenu: MenuId) -> Self {
        self.submenu = Some(submenu);
        self
    }

    /// Sets the visible label.
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Sets the visible text (alias for [`Self::with_label`]).
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.label = text.into();
        self
    }

    /// Returns the item's identifier.
    pub const fn id(&self) -> MenuItemId {
        self.id
    }

    /// Returns the item's visible label.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the item's text (alias for [`Self::label`]).
    pub fn text(&self) -> &str {
        &self.label
    }

    /// Sets the item's visible label.
    pub fn set_label(&mut self, label: impl Into<String>) {
        self.label = label.into();
    }

    /// Sets the item's visible text (alias for [`Self::set_label`]).
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.label = text.into();
    }

    /// Returns the optional keyboard shortcut hint.
    pub fn shortcut(&self) -> Option<&str> {
        self.shortcut.as_deref()
    }

    /// Sets the optional keyboard shortcut.
    pub fn set_shortcut(&mut self, shortcut: Option<String>) {
        self.shortcut = shortcut;
    }

    /// Returns the assigned stock-art icon role, if any.
    pub const fn icon(&self) -> Option<IconRole> {
        self.icon
    }

    /// Returns the stable string identifier of the icon, if one is set.
    pub fn icon_identifier(&self) -> Option<&'static str> {
        self.icon.map(|r| r.as_str())
    }

    /// Sets or clears the stock-art icon role.
    pub fn set_icon(&mut self, icon: Option<IconRole>) {
        self.icon = icon;
    }

    /// Returns true if this menu item has an assigned stock-art icon.
    pub const fn has_icon(&self) -> bool {
        self.icon.is_some()
    }

    /// Returns true if this item is enabled.
    pub const fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Sets the enabled state.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Returns true if this item is checkable.
    pub const fn is_checkable(&self) -> bool {
        self.checkable
    }

    /// Returns true if this item is currently checked.
    pub const fn is_checked(&self) -> bool {
        self.checked
    }

    /// Sets the checked state.
    pub fn set_checked(&mut self, checked: bool) {
        self.checked = checked;
    }

    /// Returns the attached submenu id, if any.
    pub const fn submenu(&self) -> Option<MenuId> {
        self.submenu
    }

    /// Returns the label translated to the specified lane access-key style.
    pub fn translated_label(&self, style: AccessKeyStyle) -> String {
        translate_access_keys(&self.label, style)
    }
}

impl Default for MenuItemSpec {
    fn default() -> Self {
        Self {
            id: MenuItemId(0),
            label: String::new(),
            shortcut: None,
            icon: None,
            enabled: true,
            visible: true,
            checkable: false,
            checked: false,
            submenu: None,
        }
    }
}

/// Type alias for [`MenuItemSpec`], serving as a descriptor for menu items.
pub type MenuItemDescriptor = MenuItemSpec;

/// An item or divider within a menu structure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuItem {
    /// An actionable or checkable menu command.
    Item(MenuItemSpec),
    /// A visual divider separating item groups.
    Separator,
    /// A nested submenu grouping child items.
    Submenu {
        id: MenuId,
        label: String,
        icon: Option<IconRole>,
        items: Vec<MenuItem>,
    },
}

impl MenuItem {
    /// Wraps a [`MenuItemSpec`] as a menu item.
    pub fn item(spec: MenuItemSpec) -> Self {
        Self::Item(spec)
    }

    /// Creates a visual separator item.
    pub const fn separator() -> Self {
        Self::Separator
    }

    /// Creates a submenu entry.
    pub fn submenu(id: MenuId, label: impl Into<String>, items: Vec<MenuItem>) -> Self {
        Self::Submenu {
            id,
            label: label.into(),
            icon: None,
            items,
        }
    }

    /// Sets or replaces the icon role for an item or submenu.
    pub fn with_icon(mut self, icon: IconRole) -> Self {
        match &mut self {
            Self::Item(spec) => {
                spec.icon = Some(icon);
            }
            Self::Submenu { icon: sub_icon, .. } => {
                *sub_icon = Some(icon);
            }
            Self::Separator => {}
        }
        self
    }

    /// Returns the icon role if present.
    pub fn icon(&self) -> Option<IconRole> {
        match self {
            Self::Item(spec) => spec.icon,
            Self::Submenu { icon, .. } => *icon,
            Self::Separator => None,
        }
    }
}

impl From<MenuItemSpec> for MenuItem {
    fn from(spec: MenuItemSpec) -> Self {
        Self::Item(spec)
    }
}

/// Specification for a menu or submenu hierarchy.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MenuSpec {
    /// Unique menu identifier, if registered.
    pub id: Option<MenuId>,
    /// Optional menu title (for submenus or top-level bar items).
    pub title: Option<String>,
    /// Items contained within this menu.
    pub items: Vec<MenuItemSpec>,
}

impl MenuSpec {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_id(mut self, id: MenuId) -> Self {
        self.id = Some(id);
        self
    }

    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn with_item(mut self, item: MenuItemSpec) -> Self {
        self.items.push(item);
        self
    }

    pub fn add_item(&mut self, item: MenuItemSpec) {
        self.items.push(item);
    }
}

/// How a shared menu label renders its access-key marker.
///
/// The portable convention is the Win32-native spelling: a `&` before the
/// mnemonic character, for example `"&File"` or `"New &Folder"`. `&&`
/// escapes a literal ampersand. Backends translate the marker to their
/// toolkit's spelling before creating the native menu item:
///
/// - Win32 supports the marker as written ([`AccessKeyStyle::Ampersand`])
///   and Windows underlines the key and opens the menu with `Alt`.
/// - GTK underlines the character after `_`, so the marker is rewritten
///   ([`AccessKeyStyle::Underscore`]).
/// - macOS menus carry no mnemonic underlines; the marker is stripped so a
///   stray `&` never reaches the title ([`AccessKeyStyle::Plain`]).
///
/// A label without a marker passes through every style unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AccessKeyStyle {
    /// Keep the `&` marker as written (Win32 menus).
    Ampersand,
    /// Rewrite `&X` to `_X` (GTK menus).
    Underscore,
    /// Strip the marker (macOS menus).
    Plain,
}

/// Translates a shared menu label's access-key marker to a lane style.
///
/// See [`AccessKeyStyle`] for the convention. The translation is
/// deliberately total: labels without a marker are returned unchanged, `&&`
/// always renders a literal `&`, and a trailing `&` stays as written.
pub fn translate_access_keys(label: &str, style: AccessKeyStyle) -> String {
    let marker = match style {
        AccessKeyStyle::Ampersand => return label.to_owned(),
        AccessKeyStyle::Underscore => Some('_'),
        AccessKeyStyle::Plain => None,
    };

    let mut out = String::with_capacity(label.len());
    let mut chars = label.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch != '&' {
            out.push(ch);
            continue;
        }
        match chars.peek() {
            Some('&') => {
                // `&&` is the escape for a literal ampersand.
                out.push('&');
                chars.next();
            }
            Some(next) => {
                if let Some(marker) = marker {
                    out.push(marker);
                }
                let next = *next;
                chars.next();
                out.push(next);
            }
            None => out.push('&'),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{translate_access_keys, AccessKeyStyle};

    #[test]
    fn access_key_markers_translate_per_lane_style() {
        assert_eq!(
            translate_access_keys("&File", AccessKeyStyle::Ampersand),
            "&File"
        );
        assert_eq!(
            translate_access_keys("&File", AccessKeyStyle::Underscore),
            "_File"
        );
        assert_eq!(
            translate_access_keys("&File", AccessKeyStyle::Plain),
            "File"
        );
        assert_eq!(
            translate_access_keys("New &Folder", AccessKeyStyle::Underscore),
            "New _Folder"
        );
        assert_eq!(
            translate_access_keys("New &Folder", AccessKeyStyle::Plain),
            "New Folder"
        );
    }

    #[test]
    fn access_key_translation_handles_escapes_and_plain_labels() {
        // `&&` stays a literal ampersand in every style.
        assert_eq!(
            translate_access_keys("Find && Replace", AccessKeyStyle::Underscore),
            "Find & Replace"
        );
        assert_eq!(
            translate_access_keys("Find && Replace", AccessKeyStyle::Plain),
            "Find & Replace"
        );
        // Labels without markers pass through untouched.
        assert_eq!(
            translate_access_keys("Refresh", AccessKeyStyle::Underscore),
            "Refresh"
        );
        assert_eq!(
            translate_access_keys("Refresh", AccessKeyStyle::Ampersand),
            "Refresh"
        );
        // A trailing marker cannot reference a character; keep it literal.
        assert_eq!(
            translate_access_keys("Odd &", AccessKeyStyle::Underscore),
            "Odd &"
        );
    }

    #[test]
    fn menu_item_spec_builder_and_icon_metadata() {
        use crate::artprov::IconRole;
        use crate::menus::{MenuItemId, MenuItemSpec};

        let spec = MenuItemSpec::new(MenuItemId(1), "&New")
            .with_shortcut("Ctrl+N")
            .with_icon(IconRole::New)
            .with_enabled(true)
            .with_checkable()
            .with_checked(false);

        assert_eq!(spec.id(), MenuItemId(1));
        assert_eq!(spec.label(), "&New");
        assert_eq!(spec.text(), "&New");
        assert_eq!(spec.shortcut(), Some("Ctrl+N"));
        assert_eq!(spec.icon(), Some(IconRole::New));
        assert_eq!(spec.icon_identifier(), Some("new"));
        assert!(spec.has_icon());
        assert!(spec.is_enabled());
        assert!(spec.is_checkable());
        assert!(!spec.is_checked());
        assert_eq!(spec.translated_label(AccessKeyStyle::Underscore), "_New");
        assert_eq!(spec.translated_label(AccessKeyStyle::Plain), "New");
    }

    #[test]
    fn menu_item_descriptor_alias_and_icon_mutation() {
        use crate::artprov::IconRole;
        use crate::menus::{MenuItemDescriptor, MenuItemId};

        let mut desc: MenuItemDescriptor = MenuItemDescriptor::new(MenuItemId(2), "Save");
        assert_eq!(desc.icon(), None);
        assert!(!desc.has_icon());
        assert_eq!(desc.icon_identifier(), None);

        desc.set_icon(Some(IconRole::Save));
        assert_eq!(desc.icon(), Some(IconRole::Save));
        assert_eq!(desc.icon_identifier(), Some("save"));
        assert!(desc.has_icon());

        desc.set_icon(None);
        assert_eq!(desc.icon(), None);
        assert!(!desc.has_icon());

        let desc2 = desc.with_icon_identifier("open");
        assert_eq!(desc2.icon(), Some(IconRole::Open));
        assert_eq!(desc2.icon_identifier(), Some("open"));
    }

    #[test]
    fn menu_item_all_stock_icon_roles_supported() {
        use crate::artprov::IconRole;
        use crate::menus::{MenuItemId, MenuItemSpec};

        for &role in &IconRole::ALL {
            let spec = MenuItemSpec::new(MenuItemId(100), "Action").with_icon(role);
            assert_eq!(spec.icon(), Some(role));
            assert_eq!(spec.icon_identifier(), Some(role.as_str()));
            assert!(spec.has_icon());
        }
    }

    #[test]
    fn menu_structure_composition_with_icons() {
        use crate::artprov::IconRole;
        use crate::menus::{MenuId, MenuItem, MenuItemId, MenuItemSpec, MenuSpec};

        let item1 = MenuItemSpec::new(MenuItemId(10), "Cut")
            .with_shortcut("Ctrl+X")
            .with_icon(IconRole::Delete);
        let item2 = MenuItemSpec::new(MenuItemId(11), "Copy")
            .with_shortcut("Ctrl+C")
            .with_icon(IconRole::Copy);

        let menu_item1 = MenuItem::item(item1.clone());
        assert_eq!(menu_item1.icon(), Some(IconRole::Delete));

        let sep = MenuItem::separator();
        assert_eq!(sep.icon(), None);

        let submenu = MenuItem::submenu(MenuId(2), "More", vec![MenuItem::item(item2.clone())])
            .with_icon(IconRole::Preferences);
        assert_eq!(submenu.icon(), Some(IconRole::Preferences));

        let menu_spec = MenuSpec::new()
            .with_id(MenuId(1))
            .with_title("Edit")
            .with_item(item1)
            .with_item(item2);
        assert_eq!(menu_spec.items.len(), 2);
        assert_eq!(menu_spec.items[0].icon, Some(IconRole::Delete));
        assert_eq!(menu_spec.items[1].icon, Some(IconRole::Copy));
    }
}