menubar 0.0.2

Cross-platform native menu library.
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
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use objc::rc::{autoreleasepool, AutoreleasePool, Id, Owned, Shared};
use objc::runtime::Object;
use objc::{class, msg_send, sel};
use objc_foundation::{INSString, NSString};

use super::menuitem::MenuItem;
use super::util::{NSInteger, NSUInteger};

struct MenuDelegate;

struct USize {
    height: f64,
    width: f64,
}

/// The maximum number of items a menu can hold is 65534
#[doc(alias = "NSMenu")]
#[repr(C)]
pub struct Menu {
    _priv: [u8; 0],
}

unsafe impl objc::RefEncode for Menu {
    const ENCODING_REF: objc::Encoding<'static> = objc::Encoding::Object;
}

unsafe impl objc::Message for Menu {}

unsafe impl Send for Menu {}
unsafe impl Sync for Menu {}

/// Creating menus
impl Menu {
    fn alloc() -> *mut Self {
        unsafe { msg_send![class!(NSMenu), alloc] }
    }

    pub fn new() -> Id<Self, Owned> {
        let ptr = Self::alloc();
        unsafe { Id::new(msg_send![ptr, init]) }
    }

    // Public only locally to allow for construction in Menubar
    #[doc(alias = "initWithTitle")]
    #[doc(alias = "initWithTitle:")]
    pub(super) fn new_with_title(title: &str) -> Id<Self, Owned> {
        let title = NSString::from_str(title);
        let ptr = Self::alloc();
        unsafe { Id::new(msg_send![ptr, initWithTitle: &*title]) }
    }

    // Title (only useful for MenuBar!)

    pub(super) fn title<'p>(&self, pool: &'p AutoreleasePool) -> &'p str {
        let title: &NSString = unsafe { msg_send![self, title] };
        title.as_str(pool)
    }

    #[doc(alias = "setTitle")]
    #[doc(alias = "setTitle:")]
    pub(super) fn set_title(&mut self, title: &str) {
        let title = NSString::from_str(title);
        unsafe { msg_send![self, setTitle: &*title] }
    }
}

/// Managing items
impl Menu {
    /// Insert an item at the specified index.
    ///
    /// Panics if `index > menu.len()`.
    #[doc(alias = "insertItem")]
    #[doc(alias = "insertItem:atIndex:")]
    // TODO: Reorder arguments to match `Vec::insert`?
    pub fn insert(&mut self, item: Id<MenuItem, Owned>, index: usize) -> Id<MenuItem, Shared> {
        let length = self.len();
        if index > length {
            panic!(
                "Failed inserting item: Index {} larger than number of items {}",
                index, length
            );
        }
        // SAFETY:
        // - References are valid
        // - The item must not exist in another menu!!!!!
        //     - We need to ensure this somehow, for now we'll just consume the item!
        //     - Should maybe return a reference to the menu, where the reference is now bound to self?
        // - 0 <= index <= self.len()
        // TODO: Thread safety!
        let _: () = unsafe { msg_send![self, insertItem: &*item, atIndex: index as NSInteger] };
        // The item is now shared, so it's no longer safe to hold a mutable pointer to it
        item.into()
    }

    #[doc(alias = "addItem")]
    #[doc(alias = "addItem:")]
    pub fn add(&mut self, item: Id<MenuItem, Owned>) -> Id<MenuItem, Shared> {
        // Same safety concerns as above
        let _: () = unsafe { msg_send![self, addItem: &*item] };
        // The item is now shared, so it's no longer safe to hold a mutable pointer to it
        item.into()
    }

    // There exists `addItemWithTitle_action_keyEquivalent`

    // Can't use this yet, we need to find a way to let users have references to menu items safely!
    // #[doc(alias = "removeItem")]
    // #[doc(alias = "removeItem:")]
    // fn remove(&mut self, item: &mut MenuItem) {
    //     unsafe { msg_send![self, removeItem: item] }
    // }
    // #[doc(alias = "removeItemAtIndex")]
    // #[doc(alias = "removeItemAtIndex:")]
    // fn remove_at_index(&mut self, at: isize) {
    //     unimplemented!()
    // }

    /// Does not post notifications.
    #[doc(alias = "removeAllItems")]
    pub fn remove_all(&mut self) {
        // SAFETY: Reference is valid
        unsafe { msg_send![self, removeAllItems] }
    }

    // Finding items

    #[doc(alias = "itemWithTag")]
    #[doc(alias = "itemWithTag:")]
    fn find_by_tag<'p>(&self, pool: &'p AutoreleasePool, tag: isize) -> Option<&'p MenuItem> {
        unimplemented!()
    }

    #[doc(alias = "itemWithTitle")]
    #[doc(alias = "itemWithTitle:")]
    fn find_by_title<'p>(&self, pool: &'p AutoreleasePool, title: &str) -> Option<&'p MenuItem> {
        unimplemented!()
    }

    #[doc(alias = "itemAtIndex")]
    #[doc(alias = "itemAtIndex:")]
    unsafe fn get_at_index<'p>(&self, pool: &'p AutoreleasePool, at: isize) -> &'p MenuItem {
        unimplemented!()
    }

    // Getting all items

    /// Number of items in this menu, including separators
    #[doc(alias = "numberOfItems")]
    pub fn len(&self) -> usize {
        let number_of_items: NSInteger = unsafe { msg_send![self, numberOfItems] };
        number_of_items as usize
    }

    #[doc(alias = "itemArray")]
    fn get_all_items<'p>(&self, pool: &'p AutoreleasePool) -> &'p [&'p MenuItem] {
        unimplemented!()
    }

    #[doc(alias = "itemArray")]
    pub fn iter<'p>(&self, pool: &'p AutoreleasePool) -> impl Iterator<Item = &'p MenuItem> + 'p {
        let array: *const Object = unsafe { msg_send![self, itemArray] };
        let enumerator: *mut Object = unsafe { msg_send![array, objectEnumerator] };
        Iter {
            array,
            enumerator,
            _p: PhantomData,
        }
    }

    // Finding indices of elements

    #[doc(alias = "indexOfItem")]
    #[doc(alias = "indexOfItem:")]
    fn index_of(&self, item: &MenuItem) -> Option<isize> {
        unimplemented!()
    }

    #[doc(alias = "indexOfItemWithTitle")]
    #[doc(alias = "indexOfItemWithTitle:")]
    fn index_of_by_title(&self, title: &str) -> Option<isize> {
        unimplemented!()
    }

    #[doc(alias = "indexOfItemWithTag")]
    #[doc(alias = "indexOfItemWithTag:")]
    fn index_of_by_tag(&self, tag: isize) -> Option<isize> {
        unimplemented!()
    }

    // fn index_of_by_action_and_target(&self, ...) -> isize {}
    // fn index_of_item_by_represented_object(&self, ...) -> isize {}

    #[doc(alias = "indexOfItemWithSubmenu")]
    #[doc(alias = "indexOfItemWithSubmenu:")]
    fn index_of_submenu(&self, submenu: &Menu) -> Option<isize> {
        unimplemented!()
    }

    // Managing submenus

    #[doc(alias = "setSubmenu")]
    #[doc(alias = "setSubmenu:forItem:")]
    // Unsure about this!
    fn set_submenu(&self, submenu: &mut Menu, for_item: &mut MenuItem) {
        unimplemented!()
    }

    // fn submenuAction(&self) {} // Overridable!

    #[doc(alias = "supermenu")]
    fn get_parent<'p>(&self, pool: &'p AutoreleasePool) -> Option<&'p Menu> {
        unimplemented!()
    }

    // Has more deprecated methods!

    // Enable/disable items

    /// Default on
    #[doc(alias = "autoenablesItems")]
    fn autoenables_items(&self) -> bool {
        unimplemented!()
    }

    #[doc(alias = "setAutoenablesItems")]
    #[doc(alias = "setAutoenablesItems:")]
    fn set_autoenables_items(&mut self, state: bool) {
        unimplemented!()
    }

    #[doc(alias = "update")]
    fn update_enabled_state_of_items(&self) {
        unimplemented!()
    }

    // Control fonts for this and subitems

    // fn font() -> Font {}

    // #[doc(alias = "setFont")]
    // #[doc(alias = "setFont:")]
    // fn set_font(&mut self, font: Font) {}

    // Handling keyboard events

    // #[doc(alias = "performKeyEquivalent")]
    // #[doc(alias = "performKeyEquivalent:")]
    // fn perform_key_equivalent(&self, event: KeyEvent) -> bool {}

    // Simulating mouse clicks

    // #[doc(alias = "performActionForItemAtIndex")]
    // #[doc(alias = "performActionForItemAtIndex:")]
    // fn perform_action_for_item_at(&self, index: isize) {}

    // Size

    #[doc(alias = "minimumWidth")]
    fn min_width(&self) -> Option<f64> {
        // None / zero when not set
        unimplemented!()
    }

    #[doc(alias = "setMinimumWidth")]
    #[doc(alias = "setMinimumWidth:")]
    fn set_min_width(&mut self, width: Option<f64>) {
        // None ~= zero
        unimplemented!()
    }

    fn size(&self) -> USize {
        unimplemented!()
    }

    #[doc(alias = "setSize")]
    #[doc(alias = "setSize:")]
    fn set_size(&mut self, size: USize) {
        // Might change the size if too big (or small?)
        unimplemented!()
    }

    // propertiesToUpdate - for efficiency when updating items

    #[doc(alias = "allowsContextMenuPlugIns")]
    fn allows_context_menu_plug_ins(&self) -> bool {
        unimplemented!()
    }

    #[doc(alias = "setAllowsContextMenuPlugIns")]
    #[doc(alias = "setAllowsContextMenuPlugIns:")]
    fn set_allows_context_menu_plug_ins(&mut self, state: bool) {
        unimplemented!()
    }

    // #[doc(alias = "popUpContextMenu:withEvent:forView:")]
    // fn displayPopUpContextMenu(&mut self, event: Event, view: Option<&View>) {}
    // #[doc(alias = "popUpContextMenu:withEvent:forView:withFont:")]
    // fn displayPopUpContextMenuWithFont(&mut self, event: Event, view: Option<&View>, font: Font) {}
    // #[doc(alias = "popUpMenuPositioningItem:atLocation:inView:")]
    // fn displayPopUpAtMenuPositioningItem(&mut self, position_item: Option<&MenuItem>, event: Event, view: Option<&View>)

    // Whether the menu displays the state column (the "Checkmark" column for items?)
    #[doc(alias = "showsStateColumn")]
    fn show_state_column(&self) -> bool {
        unimplemented!()
    }

    #[doc(alias = "setShowsStateColumn")]
    #[doc(alias = "setShowsStateColumn:")]
    fn set_show_state_column(&mut self, show: bool) {
        unimplemented!()
    }

    #[doc(alias = "highlightedItem")]
    fn currently_highlighted_item<'p>(&self, pool: &'p AutoreleasePool) -> Option<&'p MenuItem> {
        unimplemented!()
    }

    // Should honestly probably not be changed! (userInterfaceLayoutDirection)
    // fn layout_direction() {}
    // fn set_layout_direction() {}

    // You can use the delegate to populate a menu just before it is drawn
    // and to check for key equivalents without creating a menu item.
    fn delegate(&self) -> &MenuDelegate {
        // Tied to a pool or the current item?
        unimplemented!()

        // Events / things this delegate can respond to
        // - menuHasKeyEquivalent:forEvent:target:action:
        // - menu:updateItem:atIndex:shouldCancel: (update_item_before_displayed)
        // - confinementRectForMenu:onScreen: (display_location)
        // - menu:willHighlightItem: (before_highlight_item)
        // - menuWillOpen: (before_open)
        // - menuDidClose: (after_close)
        // - numberOfItemsInMenu: // Works together with updateItemBeforeDisplayed
        //     Newly created items are blank, and then updateItemBeforeDisplayed populates them
        // - menuNeedsUpdate: // Alternatively, if the population can happen basically instantly
        //     (and don't need to do a lot of processing beforehand), this can just be used
    }

    #[doc(alias = "setDelegate")]
    #[doc(alias = "setDelegate:")]
    fn set_delegate(&mut self, delegate: &mut MenuDelegate) {
        unimplemented!()
    }

    // Handling tracking? Perhaps just means closing/dismissing the menu?

    #[doc(alias = "cancelTracking")]
    fn cancel_tracking(&mut self) {
        unimplemented!()
    }

    #[doc(alias = "cancelTrackingWithoutAnimation")]
    #[doc(alias = "cancelTrackingWithoutAnimation:")]
    fn cancel_tracking_without_animation(&mut self) {
        unimplemented!()
    }

    // "Notifications" - not sure what these are yet!
    // - https://developer.apple.com/documentation/foundation/nsnotificationcenter?language=objc
    // - https://developer.apple.com/documentation/foundation/nsnotificationname?language=objc
    // - https://developer.apple.com/documentation/foundation/nsnotification?language=objc

    // Conforms to protocols:
    //     NSAccessibility - wow big guy [...]
    //     NSAccessibilityElement
    //     NSAppearanceCustomization - we should probably not allow editing this?
    //     NSCoding
    //     NSCopying
    //     NSUserInterfaceItemIdentification - May become important!
}

impl PartialEq for Menu {
    /// Pointer equality
    fn eq(&self, other: &Self) -> bool {
        self as *const Self == other as *const Self
    }
}

impl fmt::Debug for Menu {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        autoreleasepool(|pool| {
            f.debug_struct("Menu")
                .field("id", &(self as *const Self))
                .field("title", &self.title(pool))
                // TODO: parent?
                // TODO: size and stuff
                .field("items", &self.iter(pool).collect::<Vec<_>>())
                .finish()
        })
    }
}

struct Iter<'p> {
    array: *const Object,
    enumerator: *mut Object,
    _p: PhantomData<&'p [&'p MenuItem]>,
}

impl<'p> Iterator for Iter<'p> {
    type Item = &'p MenuItem;

    fn next(&mut self) -> Option<Self::Item> {
        let item: *const MenuItem = unsafe { msg_send![self.enumerator, nextObject] };

        if item.is_null() {
            None
        } else {
            Some(unsafe { &*item })
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let length: NSUInteger = unsafe { msg_send![self.array, count] };
        (length as usize, Some(length as usize))
    }
}

impl ExactSizeIterator for Iter<'_> {}

impl std::iter::FusedIterator for Iter<'_> {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::STRINGS;

    #[test]
    fn test_title() {
        autoreleasepool(|pool| {
            let mut menu = Menu::new();
            assert_eq!(menu.title(pool), "");
            STRINGS.iter().for_each(|&title| {
                menu.set_title(title);
                assert_eq!(menu.title(pool), title);
            });
        });
    }

    #[test]
    fn test_title_init() {
        autoreleasepool(|pool| {
            STRINGS.iter().for_each(|&title| {
                let menu = Menu::new_with_title(title);
                assert_eq!(menu.title(pool), title);
            });
        });
    }

    #[test]
    fn test_length() {
        autoreleasepool(|pool| {
            let mut menu = Menu::new();
            assert_eq!(menu.len(), 0);
            menu.add(MenuItem::new_empty());
            assert_eq!(menu.len(), 1);
            menu.add(MenuItem::new_separator());
            assert_eq!(menu.len(), 2);
            menu.add(MenuItem::new("test", "", None));
            assert_eq!(menu.len(), 3);
            menu.insert(MenuItem::new("test", "", None), 2);
            assert_eq!(menu.len(), 4);
            menu.remove_all();
            assert_eq!(menu.len(), 0);
        });
    }

    #[test]
    fn test_iter() {
        autoreleasepool(|pool| {
            let mut menu = Menu::new();
            assert!(menu.iter(pool).next().is_none());

            // A few different iterations
            menu.add(MenuItem::new_empty());
            menu.add(MenuItem::new_empty());
            menu.add(MenuItem::new_separator());
            let mut iter = menu.iter(pool);
            assert_eq!(iter.size_hint(), (3, Some(3)));
            assert!(!iter.next().unwrap().separator());
            assert!(!iter.next().unwrap().separator());
            assert!(iter.next().unwrap().separator());
            assert!(iter.next().is_none());

            // Modifying after creating the iterator (the iterator is unaffected)
            let mut iter = menu.iter(pool);

            menu.add(MenuItem::new_empty());
            assert_eq!(iter.size_hint(), (3, Some(3)));
            assert!(!iter.next().unwrap().separator());

            menu.add(MenuItem::new_separator());
            assert_eq!(iter.size_hint(), (3, Some(3)));
            assert!(!iter.next().unwrap().separator());

            menu.remove_all();
            assert_eq!(iter.size_hint(), (3, Some(3)));
            assert!(iter.next().unwrap().separator());

            menu.add(MenuItem::new_separator());
            assert_eq!(iter.size_hint(), (3, Some(3)));
            assert!(iter.next().is_none());

            // Test fused-ness
            assert!(iter.next().is_none());
            assert!(iter.next().is_none());
            assert!(iter.next().is_none());
            assert!(iter.next().is_none());
        });
    }

    #[test]
    fn test_max_count() {
        autoreleasepool(|_| {
            let mut menu = Menu::new();
            const COUNT: usize = 65534;
            for i in 1..=COUNT {
                menu.add(MenuItem::new(&format!("item {}", i), "", None));
            }
            assert_eq!(menu.len(), COUNT);

            // The menu, if we could render it at this point, should render fine

            menu.add(MenuItem::new(&format!("item {}", COUNT + 1), "", None));

            // The menu item should fail rendering, and we should get an error similar to the following logged:
            // 2021-01-01 00:00:00.000 my_program[12345:678901] InsertMenuItemTextWithCFString(_principalMenuRef, (useAccessibilityTitleDescriptionTrick ? CFSTR("") : (CFStringRef)title), carbonIndex - 1, attributes, [self _menuItemCommandID]) returned error -108 on line 2638 in -[NSCarbonMenuImpl _carbonMenuInsertItem:atCarbonIndex:]
        });
    }
}