Skip to main content

ferrokit/
chrome.rs

1//! Window furniture: split views, the toolbar, context menus and menu-bar
2//! menus.
3
4use std::cell::RefCell;
5use std::rc::{Rc, Weak};
6
7use objc2::rc::Retained;
8use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
9use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
10use objc2_app_kit::{
11    NSControlStateValueOff, NSControlStateValueOn, NSEventModifierFlags, NSImage, NSMenu, NSMenuDelegate, NSMenuItem, NSResponder, NSSearchToolbarItem, NSSplitView, NSSplitViewDelegate, NSSplitViewDividerStyle, NSToolbar,
12    NSToolbarDelegate, NSToolbarItem, NSView, NSWindow, NSWindowToolbarStyle,
13};
14use objc2_foundation::{NSArray, NSNotification, NSSize, NSString, NSUserDefaults};
15
16use crate::controls::FieldDelegate;
17use crate::signal::{Effect, Signal, batch};
18use crate::view::{AnyView, Cx, Kind, Meta, Node, View};
19
20// ---- split view ----
21
22define_class!(
23    // One pane of a split view: flipped, and it re-lays out its content when
24    // AppKit resizes it (window resize, divider drag).
25    #[unsafe(super(NSView, NSResponder, NSObject))]
26    #[thread_kind = MainThreadOnly]
27    #[name = "FerrokitSplitPane"]
28    #[ivars = RefCell<Weak<Meta>>]
29    pub(crate) struct SplitPane;
30
31    impl SplitPane {
32        #[unsafe(method(isFlipped))]
33        fn is_flipped(&self) -> bool {
34            true
35        }
36
37        #[unsafe(method(setFrameSize:))]
38        fn set_frame_size(&self, size: NSSize) {
39            crate::failure::guard("a window's chrome (set_frame_size)", (), || {
40                let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
41                if crate::in_layout() {
42                    return; // the layout pass in progress places the content next
43                }
44                if let Some(meta) = self.ivars().borrow().upgrade() {
45                    meta.mark();
46                    crate::relayout_now();
47                }
48            })
49        }
50    }
51);
52
53define_class!(
54    // Keeps the first pane's width when the split view resizes (holding
55    // priorities only apply under Auto Layout; this layout sets frames), and
56    // saves the divider position the user chose under its defaults key.
57    #[unsafe(super(NSObject))]
58    #[thread_kind = MainThreadOnly]
59    #[name = "FerrokitSplitDelegate"]
60    #[ivars = SplitInfo]
61    pub(crate) struct SplitDelegate;
62
63    unsafe impl NSObjectProtocol for SplitDelegate {}
64
65    unsafe impl NSSplitViewDelegate for SplitDelegate {
66        #[unsafe(method(splitView:shouldAdjustSizeOfSubview:))]
67        fn should_adjust(&self, split: &NSSplitView, view: &NSView) -> bool {
68            crate::failure::guard("a window's chrome (should_adjust)", true, || {
69                // The first pane (a sidebar) and collapsible ones (an inspector)
70                // keep their size; the others take the change.
71                let panes = split.arrangedSubviews();
72                let index = panes.iter().position(|p| std::ptr::eq(&*p, view));
73                panes.count() < 2 || !index.is_some_and(|i| i == 0 || self.ivars().collapsible.iter().any(|(c, _)| *c == i))
74            })
75        }
76
77        #[unsafe(method(splitView:canCollapseSubview:))]
78        fn can_collapse(&self, split: &NSSplitView, view: &NSView) -> bool {
79            crate::failure::guard("a window's chrome (can_collapse)", false, || {
80                let index = split.arrangedSubviews().iter().position(|p| std::ptr::eq(&*p, view));
81                index.is_some_and(|i| self.ivars().collapsible.iter().any(|(c, _)| *c == i))
82            })
83        }
84
85        #[unsafe(method(splitViewDidResizeSubviews:))]
86        fn did_resize(&self, notification: &NSNotification) {
87            crate::failure::guard("a window's chrome (did_resize)", (), || {
88                let Some(split) = notification.object().and_then(|o| o.downcast::<NSSplitView>().ok()) else { return };
89                if let Some(f) = &*self.ivars().on_resize.borrow() {
90                    f(&split);
91                }
92                // A pane the user dragged shut (or open) updates its signal.
93                let panes = split.arrangedSubviews();
94                for (i, collapsed) in self.ivars().collapsible.iter().filter(|_| !self.ivars().applying.get()) {
95                    if let Some(pane) = (*i < panes.count()).then(|| panes.objectAtIndex(*i)) {
96                        let size = if split.isVertical() { pane.frame().size.width } else { pane.frame().size.height };
97                        // Zero size counts only outside layout: a pane is zero
98                        // wide in the first tiling, before its size is set.
99                        collapsed.set_if_changed(split.isSubviewCollapsed(&pane) || pane.isHidden() || (size < 1.0 && !crate::in_layout()));
100                    }
101                }
102                // Layout passes place the divider themselves; only a drag (or a
103                // programmatic move outside layout) is the user's choice.
104                let (Some(key), false) = (&self.ivars().key, crate::in_layout()) else { return };
105                if let Some(first) = panes.firstObject().filter(|f| !f.isHidden())
106                {
107                    let size = first.frame().size;
108                    NSUserDefaults::standardUserDefaults().setDouble_forKey(if split.isVertical() { size.width } else { size.height }, key);
109                }
110            })
111        }
112    }
113);
114
115pub(crate) struct SplitInfo {
116    /// The defaults key the first divider's position is saved under.
117    key: Option<Retained<NSString>>,
118    /// Pane indices that collapse, with their signals.
119    collapsible: Vec<(usize, Signal<bool>)>,
120    /// Set while a signal's change is applied (the resizes it causes aren't
121    /// the user's).
122    applying: std::cell::Cell<bool>,
123    /// Called as the panes resize (the toolbar's title follows a sidebar).
124    on_resize: RefCell<Option<OnResize>>,
125}
126
127type OnResize = Box<dyn Fn(&NSSplitView)>;
128
129/// Side-by-side panes with draggable dividers (`NSSplitView`). The first
130/// pane keeps its width when the window resizes (a sidebar); the others
131/// share the change. [`stacked`](Self::stacked) puts them top to bottom.
132/// [`collapsible`](Self::collapsible) panes (a sidebar, an inspector) hide
133/// and show with a signal, or when dragged shut.
134pub struct Split {
135    panes: Vec<AnyView>,
136    position: Option<f64>,
137    remember: Option<String>,
138    stacked: bool,
139    collapsible: Vec<(usize, Signal<bool>)>,
140    trailing: Option<f64>,
141}
142
143impl Split {
144    /// Pane `index` collapses while `collapsed` is true, and can be dragged
145    /// shut (which sets it). Like the first pane, it keeps its size when
146    /// the window resizes. For a sidebar (`0`) or an inspector (the last):
147    ///
148    /// ```no_run
149    /// use ferrokit::*;
150    ///
151    /// let (no_sidebar, no_inspector) = (Signal::new(false), Signal::new(true));
152    /// let view = split((text("Sidebar"), text("Content"), text("Inspector")))
153    ///     .collapsible(0, &no_sidebar)
154    ///     .collapsible(2, &no_inspector)
155    ///     .position(200.0)
156    ///     .trailing(260.0);
157    /// let menu = menu_item("Toggle Sidebar", move || no_sidebar.update(|c| *c = !*c));
158    /// # let _ = (view, menu);
159    /// ```
160    pub fn collapsible(mut self, index: usize, collapsed: &Signal<bool>) -> Self {
161        self.collapsible.push((index, *collapsed));
162        self
163    }
164
165    /// The last pane's initial width (height when stacked), in points: an
166    /// inspector's.
167    pub fn trailing(mut self, points: f64) -> Self {
168        self.trailing = Some(points);
169        self
170    }
171
172    /// Panes top to bottom, with dividers across (an editor over its
173    /// results). The first pane keeps its height when the window resizes.
174    pub fn stacked(mut self) -> Self {
175        self.stacked = true;
176        self
177    }
178
179    /// Initial position of the first divider, in points from the left (from
180    /// the top when [`stacked`](Self::stacked)).
181    pub fn position(mut self, points: f64) -> Self {
182        self.position = Some(points);
183        self
184    }
185
186    /// Saves the divider position the user drags to under `name` (in user
187    /// defaults) and starts there next time, instead of at
188    /// [`position`](Self::position).
189    pub fn remember(mut self, name: &str) -> Self {
190        self.remember = Some(name.into());
191        self
192    }
193}
194
195/// The defaults key a remembered split's position is kept under.
196pub(crate) fn split_key(name: &str) -> Retained<NSString> {
197    NSString::from_str(&format!("ferrokit split {name}"))
198}
199
200impl View for Split {
201    fn build(self, cx: &mut Cx) -> Node {
202        let mtm = cx.mtm;
203        let split = NSSplitView::new(mtm);
204        split.setVertical(!self.stacked);
205        split.setDividerStyle(NSSplitViewDividerStyle::Thin);
206        let key = self.remember.as_deref().map(split_key);
207        let defaults = NSUserDefaults::standardUserDefaults();
208        let saved = key.as_ref().filter(|k| defaults.objectForKey(k).is_some()).map(|k| defaults.doubleForKey(k));
209        let delegate = SplitDelegate::alloc(mtm).set_ivars(SplitInfo { key, collapsible: self.collapsible.clone(), applying: std::cell::Cell::new(false), on_resize: RefCell::default() });
210        // SAFETY: NSObject's designated initialiser.
211        let delegate: Retained<SplitDelegate> = unsafe { msg_send![super(delegate), init] };
212        // Weak in AppKit; the node keeps the delegate.
213        split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
214        cx.container.addSubview(&split);
215        let (mut panes, mut typed) = (Vec::new(), Vec::new());
216        for child in self.panes {
217            let pane = SplitPane::alloc(mtm).set_ivars(RefCell::new(Weak::new()));
218            // SAFETY: NSView's designated initialiser.
219            let pane: Retained<SplitPane> = unsafe { msg_send![super(pane), init] };
220            split.addArrangedSubview(&pane);
221            let node = child.build_node(&mut Cx::new(Retained::into_super(pane.clone())));
222            panes.push((Retained::into_super(pane.clone()), node));
223            typed.push(pane);
224        }
225        let mut node = Node::new(Kind::Split {
226            split,
227            panes,
228            position: std::cell::Cell::new(saved.map(|p| (p, false)).or(self.position.map(|p| (p, true)))),
229            trailing: std::cell::Cell::new(self.trailing),
230            stacked: self.stacked,
231        });
232        node.keep(Retained::into_super(delegate.clone()));
233        // Collapsible panes follow their signals, reopening at the size they
234        // had (or the size given for them).
235        let count = typed.len();
236        for (i, collapsed) in self.collapsible {
237            let Some(pane) = typed.get(i).cloned() else { continue };
238            let meta = Rc::downgrade(&node.meta);
239            let given = if i == 0 { self.position } else if i + 1 == count { self.trailing } else { None };
240            let size = std::cell::Cell::new(given.unwrap_or(220.0));
241            let stacked = self.stacked;
242            let delegate = delegate.clone();
243            node.own(Effect::new(move || {
244                let hide = collapsed.get();
245                if pane.isHidden() != hide {
246                    delegate.ivars().applying.set(true);
247                    let along = |r: objc2_foundation::NSRect| if stacked { r.size.height } else { r.size.width };
248                    if hide && along(pane.frame()) > 20.0 {
249                        size.set(along(pane.frame()));
250                    }
251                    pane.setHidden(hide);
252                    // SAFETY: reading the view hierarchy on the main thread.
253                    if let Some(split) = unsafe { pane.superview() }.and_then(|s| s.downcast::<NSSplitView>().ok()) {
254                        split.adjustSubviews();
255                        if !hide && along(pane.frame()) < 20.0 {
256                            if i == 0 {
257                                split.setPosition_ofDividerAtIndex(size.get(), 0);
258                            } else if i + 1 == count {
259                                let total = along(split.bounds());
260                                split.setPosition_ofDividerAtIndex(total - size.get() - split.dividerThickness(), (count - 2) as isize);
261                            }
262                        }
263                    }
264                    delegate.ivars().applying.set(false);
265                    // The panes that grew or shrank keep a stale strip where
266                    // their old edge was (a line across a table) until they're
267                    // laid out again: AppKit's views inside (a scroll view's
268                    // background) don't follow the new size by themselves.
269                    // SAFETY: reading the view hierarchy on the main thread.
270                    if let Some(split) = unsafe { pane.superview() } {
271                        relayout_all(&split);
272                    }
273                    if let Some(meta) = meta.upgrade() {
274                        meta.mark();
275                    }
276                    crate::view::invalidate_layout();
277                }
278            }));
279        }
280        // Each pane re-lays out its subtree when AppKit resizes it.
281        for pane in typed {
282            *pane.ivars().borrow_mut() = Rc::downgrade(&node.meta);
283        }
284        node
285    }
286}
287
288/// Marks `view` and everything inside it as needing layout and display.
289fn relayout_all(view: &NSView) {
290    view.setNeedsLayout(true);
291    view.setNeedsDisplay(true);
292    for sub in view.subviews().iter() {
293        relayout_all(&sub);
294    }
295}
296
297/// Panes side by side with draggable dividers (see [`Split`]).
298pub fn split(panes: impl crate::view::Views) -> Split {
299    Split { panes: panes.into_views(), position: None, remember: None, stacked: false, collapsible: Vec::new(), trailing: None }
300}
301
302// ---- context menus ----
303
304define_class!(
305    // Action and validation for one menu item.
306    #[unsafe(super(NSObject))]
307    #[thread_kind = MainThreadOnly]
308    #[name = "FerrokitMenuTarget"]
309    #[ivars = MenuAction]
310    pub(crate) struct MenuTarget;
311
312    impl MenuTarget {
313        #[unsafe(method(fire:))]
314        fn fire(&self, _sender: Option<&AnyObject>) {
315            crate::models::flush();
316            crate::failure::entry("a menu item's action", (), || (self.ivars().action)());
317        }
318
319        #[unsafe(method(validateMenuItem:))]
320        fn validate(&self, item: &NSMenuItem) -> bool {
321            crate::failure::guard("a window's chrome (validate)", false, || {
322                if let Some(checked) = &self.ivars().checked {
323                    item.setState(if checked() { NSControlStateValueOn } else { NSControlStateValueOff });
324                }
325                if let Some(titled) = &self.ivars().titled {
326                    item.setTitle(&NSString::from_str(&titled()));
327                }
328                self.ivars().enabled.as_ref().is_none_or(|f| f())
329            })
330        }
331    }
332);
333
334pub(crate) struct MenuAction {
335    action: Box<dyn Fn()>,
336    enabled: Option<Box<dyn Fn() -> bool>>,
337    checked: Option<Box<dyn Fn() -> bool>>,
338    titled: Option<Box<dyn Fn() -> String>>,
339}
340
341/// A modifier key: of a menu item's shortcut (where Command is always
342/// included), and of the keys and clicks [`testing::input`](crate::testing::input) posts.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub enum Modifier {
345    /// ⌘ (a menu item's shortcut has it anyway).
346    Command,
347    /// ⇧ (an uppercase key implies it too).
348    Shift,
349    /// ⌥
350    Option,
351    /// ⌃
352    Control,
353}
354
355/// An item of a menu: a command, a separator or a submenu. Used for context
356/// menus and the menu bar (see [`App::menu`](crate::App::menu)).
357pub struct MenuItem(Entry);
358
359enum Entry {
360    Action {
361        title: String,
362        action: Box<dyn Fn()>,
363        enabled: Option<Box<dyn Fn() -> bool>>,
364        checked: Option<Box<dyn Fn() -> bool>>,
365        titled: Option<Box<dyn Fn() -> String>>,
366        key: Option<(String, NSEventModifierFlags)>,
367    },
368    Separator,
369    /// One of AppKit's own actions, sent along the responder chain (or to
370    /// the font manager): Bold, Show Fonts, Align Left…
371    Standard { title: String, action: objc2::runtime::Sel, key: &'static str, modifiers: NSEventModifierFlags, tag: isize, font_manager: bool },
372    Submenu { title: String, items: Vec<MenuItem> },
373    Dynamic { title: String, items: Rc<dyn Fn() -> Vec<MenuItem>> },
374}
375
376impl MenuItem {
377    /// Whether this item's shortcut is ⌘`key` alone (the File menu's Close
378    /// gives ⌘W to an app item that takes it).
379    pub(crate) fn has_command_key(&self, key: &str) -> bool {
380        matches!(&self.0, Entry::Action { key: Some((k, flags)), .. } if k == key && *flags == NSEventModifierFlags::Command)
381    }
382
383    /// Disabled: `true`, or a closure (read when the menu opens, and before
384    /// the item's key equivalent fires).
385    pub fn disabled(mut self, when: impl crate::IntoValue<bool>) -> Self {
386        if let Entry::Action { enabled, .. } = &mut self.0 {
387            let when = when.into_value();
388            *enabled = Some(Box::new(move || !when.get()));
389        }
390        self
391    }
392
393    /// A checkmark: `true`, or a closure (read when the menu opens).
394    pub fn checked(mut self, when: impl crate::IntoValue<bool>) -> Self {
395        if let Entry::Action { checked, .. } = &mut self.0 {
396            let when = when.into_value();
397            *checked = Some(Box::new(move || when.get()));
398        }
399        self
400    }
401
402    /// A ⌘ shortcut: `"n"` is ⌘N, `"N"` is ⇧⌘N, `","` is ⌘,.
403    ///
404    /// Keys without a letter are their characters: `"\u{8}"` is ⌘⌫
405    /// (Delete), `"\u{7f}"` ⌘⌦ (Forward Delete), `"\r"` ⌘↩, `"\u{1b}"`
406    /// ⌘⎋, `"\t"` ⌘⇥, `" "` ⌘Space, and the arrows `"\u{f700}"` ↑,
407    /// `"\u{f701}"` ↓, `"\u{f702}"` ←, `"\u{f703}"` →.
408    pub fn key(self, key: &str) -> Self {
409        self.key_with(key, &[])
410    }
411
412    /// A shortcut with more modifiers than ⌘, e.g. `key_with("n", &[Modifier::Option])` for ⌥⌘N.
413    pub fn key_with(mut self, key: &str, modifiers: &[Modifier]) -> Self {
414        let mut flags = NSEventModifierFlags::Command;
415        for m in modifiers {
416            flags |= match m {
417                Modifier::Command => NSEventModifierFlags::Command,
418                Modifier::Shift => NSEventModifierFlags::Shift,
419                Modifier::Option => NSEventModifierFlags::Option,
420                Modifier::Control => NSEventModifierFlags::Control,
421            };
422        }
423        if let Entry::Action { key: k, .. } = &mut self.0 {
424            *k = Some((key.into(), flags));
425        }
426        self
427    }
428}
429
430/// A menu command. The title is fixed, or a closure read each time the
431/// menu opens ("Show Sidebar" or "Hide Sidebar").
432pub fn menu_item(title: impl crate::IntoValue<String>, action: impl Fn() + 'static) -> MenuItem {
433    let (title, titled): (String, Option<Box<dyn Fn() -> String>>) = match title.into_value() {
434        crate::Value::Fixed(t) => (t, None),
435        crate::Value::Computed(f) => (crate::signal::untrack(|| f()), Some(Box::new(move || f()))),
436    };
437    MenuItem(Entry::Action { title, action: Box::new(action), enabled: None, checked: None, titled, key: None })
438}
439
440/// TextEdit's Format menu, for rich text editors
441/// ([`TextEditor::rich`](crate::TextEditor::rich)): Font (Show Fonts, Bold,
442/// Italic, Underline, Bigger, Smaller, Show Colors, Copy and Paste Style)
443/// and Text (alignment, Show Ruler, Copy and Paste Ruler), with their usual
444/// shortcuts. AppKit enables what applies to the focused editor.
445///
446/// ```no_run
447/// use ferrokit::*;
448///
449/// let app = App::new("Journal").menu("Format", format_menu());
450/// # let _ = app;
451/// ```
452pub fn format_menu() -> Vec<MenuItem> {
453    use objc2_app_kit::NSEventModifierFlags as M;
454    let item = |title: &str, action, key, modifiers, tag, font_manager| MenuItem(Entry::Standard { title: crate::t(title), action, key, modifiers, tag, font_manager });
455    let (cmd, shift, opt, ctrl) = (M::Command, M::Shift, M::Option, M::Control);
456    vec![
457        submenu(&crate::t("Font"), vec![
458            item("Show Fonts", sel!(orderFrontFontPanel:), "t", cmd, 0, true),
459            // NSFontManager's traits: italic 1, bold 2; sizes: bigger 3, smaller 4.
460            item("Bold", sel!(addFontTrait:), "b", cmd, 2, true),
461            item("Italic", sel!(addFontTrait:), "i", cmd, 1, true),
462            item("Underline", sel!(underline:), "u", cmd, 0, false),
463            menu_separator(),
464            item("Bigger", sel!(modifyFont:), "+", cmd, 3, true),
465            item("Smaller", sel!(modifyFont:), "-", cmd, 4, true),
466            menu_separator(),
467            item("Show Colors", sel!(orderFrontColorPanel:), "C", cmd | shift, 0, false),
468            menu_separator(),
469            item("Copy Style", sel!(copyFont:), "c", cmd | opt, 0, false),
470            item("Paste Style", sel!(pasteFont:), "v", cmd | opt, 0, false),
471        ]),
472        submenu(&crate::t("Text"), vec![
473            item("Align Left", sel!(alignLeft:), "{", cmd, 0, false),
474            item("Center", sel!(alignCenter:), "|", cmd, 0, false),
475            item("Justify", sel!(alignJustified:), "", cmd, 0, false),
476            item("Align Right", sel!(alignRight:), "}", cmd, 0, false),
477            menu_separator(),
478            item("Show Ruler", sel!(toggleRuler:), "r", cmd | ctrl, 0, false),
479            item("Copy Ruler", sel!(copyRuler:), "c", cmd | ctrl, 0, false),
480            item("Paste Ruler", sel!(pasteRuler:), "v", cmd | ctrl, 0, false),
481        ]),
482    ]
483}
484
485/// Customize Toolbar…, for a View menu: opens the main window's toolbar
486/// customisation sheet; enabled when that toolbar is customisable (see
487/// [`Window::customizable_toolbar`](crate::Window::customizable_toolbar)).
488pub fn customize_toolbar_item() -> MenuItem {
489    let toolbar = || {
490        let mtm = MainThreadMarker::new()?;
491        objc2_app_kit::NSApplication::sharedApplication(mtm).mainWindow()?.toolbar().filter(|t| t.allowsUserCustomization())
492    };
493    menu_item(crate::t("Customize Toolbar…"), move || {
494        if let Some(t) = toolbar() {
495            // SAFETY: opening the sheet AppKit's own menu item opens.
496            unsafe { t.runCustomizationPalette(None) };
497        }
498    })
499    .disabled(move || toolbar().is_none())
500}
501
502/// A separator line.
503pub fn menu_separator() -> MenuItem {
504    MenuItem(Entry::Separator)
505}
506
507/// A submenu.
508pub fn submenu(title: &str, items: Vec<MenuItem>) -> MenuItem {
509    MenuItem(Entry::Submenu { title: title.into(), items })
510}
511
512/// A submenu whose items `items` builds each time it opens (Open Recent, a
513/// list of servers…), so it always shows the current state.
514pub fn dynamic_submenu(title: &str, items: impl Fn() -> Vec<MenuItem> + 'static) -> MenuItem {
515    MenuItem(Entry::Dynamic { title: title.into(), items: Rc::new(items) })
516}
517
518pub(crate) struct DynamicItems {
519    items: Rc<dyn Fn() -> Vec<MenuItem>>,
520    /// The current items' targets.
521    targets: RefCell<Vec<Retained<NSObject>>>,
522}
523
524define_class!(
525    // Rebuilds a dynamic submenu before it's shown (and before its items'
526    // key equivalents are matched).
527    #[unsafe(super(NSObject))]
528    #[thread_kind = MainThreadOnly]
529    #[name = "FerrokitDynamicMenu"]
530    #[ivars = DynamicItems]
531    pub(crate) struct DynamicMenu;
532
533    unsafe impl NSObjectProtocol for DynamicMenu {}
534
535    unsafe impl NSMenuDelegate for DynamicMenu {
536        #[unsafe(method(menuNeedsUpdate:))]
537        fn menu_needs_update(&self, menu: &NSMenu) {
538            crate::failure::guard("a window's chrome (menu_needs_update)", (), || {
539                self.refill(menu);
540            })
541        }
542    }
543);
544
545impl DynamicMenu {
546    pub(crate) fn refill(&self, menu: &NSMenu) {
547        let mtm = MainThreadMarker::new().expect("main thread");
548        let (built, targets) = build_menu(mtm, (self.ivars().items)());
549        menu.removeAllItems();
550        for item in built.itemArray().iter() {
551            built.removeItem(&item);
552            menu.addItem(&item);
553        }
554        *self.ivars().targets.borrow_mut() = targets;
555    }
556}
557
558/// Builds an `NSMenu`; the returned targets must be kept alive with it.
559pub(crate) fn build_menu(mtm: MainThreadMarker, items: Vec<MenuItem>) -> (Retained<NSMenu>, Vec<Retained<NSObject>>) {
560    build_titled_menu(mtm, "", items)
561}
562
563/// As [`build_menu`], with a title (menu-bar menus and submenus).
564pub(crate) fn build_titled_menu(mtm: MainThreadMarker, title: &str, items: Vec<MenuItem>) -> (Retained<NSMenu>, Vec<Retained<NSObject>>) {
565    let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title));
566    let mut keep = Vec::new();
567    for item in items {
568        match item.0 {
569            Entry::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
570            Entry::Standard { title, action, key, modifiers, tag, font_manager } => {
571                let ns = plain_item(mtm, &title, Some(action), key);
572                ns.setKeyEquivalentModifierMask(modifiers);
573                ns.setTag(tag);
574                if font_manager {
575                    // SAFETY: the shared font manager lives as long as the app.
576                    unsafe { ns.setTarget(Some(&objc2_app_kit::NSFontManager::sharedFontManager(mtm))) };
577                }
578                menu.addItem(&ns);
579            }
580            Entry::Submenu { title, items } => {
581                let (sub, targets) = build_titled_menu(mtm, &title, items);
582                let holder = plain_item(mtm, &title, None, "");
583                holder.setSubmenu(Some(&sub));
584                menu.addItem(&holder);
585                keep.extend(targets);
586            }
587            Entry::Dynamic { title, items } => {
588                let sub = NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(&title));
589                let delegate = DynamicMenu::alloc(mtm).set_ivars(DynamicItems { items, targets: RefCell::default() });
590                // SAFETY: NSObject's designated initialiser.
591                let delegate: Retained<DynamicMenu> = unsafe { msg_send![super(delegate), init] };
592                delegate.refill(&sub);
593                // Weak in AppKit; the caller keeps the delegate.
594                sub.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
595                let holder = plain_item(mtm, &title, None, "");
596                holder.setSubmenu(Some(&sub));
597                menu.addItem(&holder);
598                keep.push(Retained::into_super(delegate));
599            }
600            Entry::Action { title, action, enabled, checked, titled, key } => {
601                let target = MenuTarget::alloc(mtm).set_ivars(MenuAction { action, enabled, checked, titled });
602                // SAFETY: NSObject's designated initialiser.
603                let target: Retained<MenuTarget> = unsafe { msg_send![super(target), init] };
604                let (k, flags) = key.unwrap_or((String::new(), NSEventModifierFlags::Command));
605                let ns = plain_item(mtm, &title, Some(sel!(fire:)), &k);
606                ns.setKeyEquivalentModifierMask(flags);
607                // SAFETY: the target outlives the item (kept by the caller).
608                unsafe { ns.setTarget(Some(&target)) };
609                menu.addItem(&ns);
610                keep.push(Retained::into_super(target));
611            }
612        }
613    }
614    (menu, keep)
615}
616
617/// A menu item with a nil target (or one set later).
618pub(crate) fn plain_item(mtm: MainThreadMarker, title: &str, action: Option<objc2::runtime::Sel>, key: &str) -> Retained<NSMenuItem> {
619    // SAFETY: plain menu item construction.
620    unsafe {
621        NSMenuItem::initWithTitle_action_keyEquivalent(NSMenuItem::alloc(mtm), &NSString::from_str(title), action, &NSString::from_str(key))
622    }
623}
624
625/// The view that should carry a context menu for this leaf (a scroll view's
626/// document view, so right-clicks on the content reach it).
627pub(crate) fn menu_host(view: &NSView) -> Retained<NSView> {
628    use objc2::Message as _;
629    match view.downcast_ref::<objc2_app_kit::NSScrollView>() {
630        Some(s) => s.documentView().unwrap_or_else(|| view.retain()),
631        None => view.retain(),
632    }
633}
634
635// ---- toolbar ----
636
637/// An item of a window's toolbar: made by [`toolbar_button`],
638/// [`toolbar_group`], [`toolbar_picker`], [`toolbar_search`],
639/// [`toolbar_space`] or [`toolbar_fixed_space`].
640pub struct ToolbarItem(pub(crate) Item);
641
642/// What a [`ToolbarItem`] is (kept inside, so items can gain options
643/// without breaking apps).
644pub(crate) enum Item {
645    /// A button with an SF Symbol and a label.
646    Button {
647        /// Stable identifier.
648        id: String,
649        /// The label (also the tooltip and VoiceOver name).
650        label: String,
651        /// SF Symbol name.
652        symbol: String,
653        /// What it does (runs in a batch).
654        action: Box<dyn Fn()>,
655        /// Disabled while this (reading signals) returns true.
656        disabled: Option<Box<dyn Fn() -> bool>>,
657    },
658    /// Flexible space between items.
659    FlexibleSpace,
660    /// A fixed space between items.
661    Space,
662    /// A search field bound to a signal.
663    Search {
664        /// Stable identifier.
665        id: String,
666        /// The query.
667        query: Signal<String>,
668    },
669    /// Buttons side by side in one capsule, as one item (see
670    /// [`toolbar_group`]).
671    Group {
672        /// Stable identifier.
673        id: String,
674        /// The group's label (the overflow menu and customisation sheet).
675        label: String,
676        /// Its buttons, each made by [`toolbar_button`] (their own
677        /// identifiers and disabled states aren't used).
678        buttons: Vec<ToolbarItem>,
679    },
680    /// A choice of one, shown as segments (see [`toolbar_picker`]).
681    Picker {
682        /// Stable identifier.
683        id: String,
684        /// The picker's label.
685        label: String,
686        /// Each choice's label and SF Symbol.
687        choices: Vec<(String, String)>,
688        /// The chosen index (reading signals).
689        selected: Box<dyn Fn() -> usize>,
690        /// Called with the index the user chose.
691        choose: Box<dyn Fn(usize)>,
692    },
693    /// An item the user can add from the customisation sheet, not in the
694    /// toolbar at first (see [`Item::optional`]).
695    Optional(Box<ToolbarItem>),
696}
697
698impl ToolbarItem {
699    /// Disabled: `true`, or a closure reading signals.
700    pub fn disabled(self, when: impl crate::IntoValue<bool>) -> Self {
701        ToolbarItem(match self.0 {
702            Item::Button { id, label, symbol, action, .. } => {
703                let when = when.into_value();
704                Item::Button { id, label, symbol, action, disabled: Some(Box::new(move || when.get())) }
705            }
706            Item::Optional(item) => Item::Optional(Box::new(item.disabled(when))),
707            other => other,
708        })
709    }
710
711    /// Offered in the customisation sheet (with
712    /// [`Window::customizable_toolbar`](crate::Window::customizable_toolbar)),
713    /// but not in the toolbar until the user adds it.
714    pub fn optional(self) -> Self {
715        match self.0 {
716            Item::Optional(_) => self,
717            other => ToolbarItem(Item::Optional(Box::new(ToolbarItem(other)))),
718        }
719    }
720
721    fn id(&self) -> String {
722        // SAFETY: AppKit's identifier constants.
723        match &self.0 {
724            Item::Button { id, .. } | Item::Search { id, .. } | Item::Group { id, .. } | Item::Picker { id, .. } => id.clone(),
725            Item::FlexibleSpace => unsafe { objc2_app_kit::NSToolbarFlexibleSpaceItemIdentifier }.to_string(),
726            Item::Space => unsafe { objc2_app_kit::NSToolbarSpaceItemIdentifier }.to_string(),
727            Item::Optional(item) => item.id(),
728        }
729    }
730}
731
732/// A toolbar button: identifier, label, SF Symbol, action.
733pub fn toolbar_button(id: &str, label: &str, symbol: &str, action: impl Fn() + 'static) -> ToolbarItem {
734    ToolbarItem(Item::Button { id: id.into(), label: label.into(), symbol: symbol.into(), action: Box::new(action), disabled: None })
735}
736
737/// Flexible space in the toolbar.
738pub fn toolbar_space() -> ToolbarItem {
739    ToolbarItem(Item::FlexibleSpace)
740}
741
742/// A fixed space in the toolbar.
743pub fn toolbar_fixed_space() -> ToolbarItem {
744    ToolbarItem(Item::Space)
745}
746
747/// A toolbar search field bound two ways to `query`.
748pub fn toolbar_search(id: &str, query: &Signal<String>) -> ToolbarItem {
749    ToolbarItem(Item::Search { id: id.into(), query: *query })
750}
751
752/// Related buttons in one capsule (zoom out and in, back and forward), made
753/// by [`toolbar_button`]; one item to the overflow menu and the
754/// customisation sheet, under `label`.
755///
756/// ```no_run
757/// use ferrokit::*;
758///
759/// let zoom = Signal::new(1.0);
760/// let item = toolbar_group("zoom", "Zoom", vec![
761///     toolbar_button("out", "Zoom Out", "minus.magnifyingglass", move || zoom.update(|z| *z /= 1.25)),
762///     toolbar_button("in", "Zoom In", "plus.magnifyingglass", move || zoom.update(|z| *z *= 1.25)),
763/// ]);
764/// # let _ = item;
765/// ```
766pub fn toolbar_group(id: &str, label: &str, buttons: Vec<ToolbarItem>) -> ToolbarItem {
767    ToolbarItem(Item::Group { id: id.into(), label: label.into(), buttons })
768}
769
770/// A choice of one in the toolbar, as segments with SF Symbols (Finder's
771/// view modes): `value` is set to the chosen choice's value, and the
772/// segment follows it. Each choice is a label (for VoiceOver, tooltips and
773/// the overflow menu), a symbol and a value.
774///
775/// ```no_run
776/// use ferrokit::*;
777///
778/// #[derive(Clone, Copy, PartialEq)]
779/// enum Mode { List, Grid }
780/// let mode = Signal::new(Mode::List);
781/// let item = toolbar_picker("mode", "View", &mode, vec![("List", "list.bullet", Mode::List), ("Grid", "square.grid.2x2", Mode::Grid)]);
782/// # let _ = item;
783/// ```
784pub fn toolbar_picker<T: Clone + PartialEq + 'static>(id: &str, label: &str, value: &Signal<T>, choices: Vec<(&str, &str, T)>) -> ToolbarItem {
785    let value = *value;
786    let values: Rc<Vec<T>> = Rc::new(choices.iter().map(|c| c.2.clone()).collect());
787    let v2 = values.clone();
788    ToolbarItem(Item::Picker {
789        id: id.into(),
790        label: label.into(),
791        choices: choices.iter().map(|(l, s, _)| (l.to_string(), s.to_string())).collect(),
792        selected: Box::new(move || value.with(|v| values.iter().position(|c| c == v).unwrap_or(0))),
793        choose: Box::new(move |i| {
794            if let Some(v) = v2.get(i) {
795                value.set(v.clone());
796            }
797        }),
798    })
799}
800
801/// A toolbar item as the delegate keeps it, to make it again (for the
802/// customisation sheet, and when the user adds it back).
803enum Spec {
804    Button { label: String, symbol: String, action: Rc<dyn Fn(isize)>, disabled: Option<Rc<dyn Fn() -> bool>> },
805    Search { query: Signal<String> },
806    Group { label: String, buttons: Vec<(String, String)>, action: Rc<dyn Fn(isize)> },
807    Picker { label: String, choices: Vec<(String, String)>, selected: Rc<dyn Fn() -> usize>, choose: Rc<dyn Fn(isize)> },
808    Standard,
809}
810
811struct ToolbarEntry {
812    id: String,
813    spec: Spec,
814    optional: bool,
815}
816
817impl ToolbarEntry {
818    fn new(item: ToolbarItem) -> ToolbarEntry {
819        let id = item.id();
820        // Actions run with the owner of the window being built.
821        let act = |f: Box<dyn Fn()>| -> Rc<dyn Fn(isize)> {
822            let f = crate::signal::with_current_owner(f);
823            Rc::new(move |_| f())
824        };
825        let (spec, optional) = match item.0 {
826            Item::Optional(item) => (ToolbarEntry::new(*item).spec, true),
827            Item::Button { label, symbol, action, disabled, .. } => (Spec::Button { label, symbol, action: act(action), disabled: disabled.map(Rc::from) }, false),
828            Item::Search { query, .. } => (Spec::Search { query }, false),
829            Item::Group { label, buttons, .. } => {
830                let (mut shown, mut actions) = (Vec::new(), Vec::new());
831                for b in buttons {
832                    if let Item::Button { label, symbol, action, .. } = b.0 {
833                        shown.push((label, symbol));
834                        actions.push(action);
835                    }
836                }
837                let actions: Vec<Box<dyn Fn()>> = actions.into_iter().map(|a| Box::new(crate::signal::with_current_owner(a)) as Box<dyn Fn()>).collect();
838                let action = move |i: isize| {
839                    if let Some(a) = usize::try_from(i).ok().and_then(|i| actions.get(i)) {
840                        a();
841                    }
842                };
843                (Spec::Group { label, buttons: shown, action: Rc::new(action) }, false)
844            }
845            Item::Picker { label, choices, selected, choose, .. } => {
846                let choose: Rc<dyn Fn(usize)> = Rc::from(choose);
847                (Spec::Picker { label, choices, selected: Rc::from(selected), choose: Rc::new(move |i| choose(i.max(0) as usize)) }, false)
848            }
849            Item::FlexibleSpace | Item::Space => (Spec::Standard, false),
850        };
851        ToolbarEntry { id, spec, optional }
852    }
853}
854
855/// A toolbar item's action and its enabled state, both in its own window.
856pub(crate) struct ToolbarAction {
857    /// Called with the segment clicked (a group's), else 0.
858    action: Rc<dyn Fn(isize)>,
859    disabled: Option<Rc<dyn Fn() -> bool>>,
860    window: objc2::rc::Weak<NSWindow>,
861}
862
863define_class!(
864    // Action and validation for one toolbar button. AppKit asks
865    // `validateToolbarItem:` as events arrive, so the enabled state follows
866    // what the window can do (it was only known once its content was in).
867    #[unsafe(super(NSObject))]
868    #[thread_kind = MainThreadOnly]
869    #[name = "FerrokitToolbarTarget"]
870    #[ivars = ToolbarAction]
871    pub(crate) struct ToolbarTarget;
872
873    impl ToolbarTarget {
874        #[unsafe(method(fire:))]
875        fn fire(&self, sender: Option<&AnyObject>) {
876            crate::models::flush();
877            let index = sender.and_then(|s| s.downcast_ref::<objc2_app_kit::NSToolbarItemGroup>()).map_or(0, |g| g.selectedIndex());
878            // Kept for the call (an action may close its own window).
879            let _keep = objc2::Message::retain(self);
880            let a = self.ivars();
881            crate::failure::guard("a toolbar item's action", (), || crate::commands::acting_in(a.window.load(), || batch(|| (a.action)(index))));
882        }
883
884        #[unsafe(method(validateToolbarItem:))]
885        fn validate(&self, _item: &NSToolbarItem) -> bool {
886            crate::failure::guard("a window's chrome (validate)", false, || {
887                self.enabled()
888            })
889        }
890    }
891);
892
893impl ToolbarTarget {
894    fn new(mtm: MainThreadMarker, action: Rc<dyn Fn(isize)>, disabled: Option<Rc<dyn Fn() -> bool>>, window: objc2::rc::Weak<NSWindow>) -> Retained<Self> {
895        let this = Self::alloc(mtm).set_ivars(ToolbarAction { action, disabled, window });
896        // SAFETY: NSObject's designated initialiser.
897        unsafe { msg_send![super(this), init] }
898    }
899
900    fn enabled(&self) -> bool {
901        let a = self.ivars();
902        a.disabled.as_ref().is_none_or(|d| !crate::commands::acting_in(a.window.load(), || d()))
903    }
904}
905
906/// What an item in the toolbar keeps alive and up to date.
907#[derive(Default)]
908struct Live {
909    keep: Vec<Retained<NSObject>>,
910    effects: Vec<Effect>,
911}
912
913pub(crate) struct ToolbarState {
914    entries: Vec<ToolbarEntry>,
915    /// What each item in the toolbar needs, by identifier (replaced when
916    /// the user adds it again).
917    live: RefCell<std::collections::HashMap<String, Live>>,
918    /// The toolbar's window: its buttons act there.
919    window: objc2::rc::Weak<NSWindow>,
920    /// The width of the space before the title, over a sidebar (see
921    /// [`track_sidebar`]).
922    spacer: RefCell<Option<Retained<objc2_app_kit::NSLayoutConstraint>>>,
923    /// Whether the toolbar has that space.
924    tracks_sidebar: std::cell::Cell<bool>,
925    /// Where a customisable toolbar's layout is remembered.
926    remember: Option<String>,
927    /// The window's shell has a sidebar, an inspector: their toggles and
928    /// tracking separators lead and end the toolbar.
929    shell: (bool, bool),
930}
931
932/// AppKit's own items for a shell's sidebar and inspector.
933fn shell_ids(shell: (bool, bool)) -> (Vec<String>, Vec<String>) {
934    // SAFETY: AppKit's identifier constants.
935    unsafe {
936        use objc2_app_kit::*;
937        let lead = if shell.0 { vec![NSToolbarToggleSidebarItemIdentifier.to_string(), NSToolbarSidebarTrackingSeparatorItemIdentifier.to_string()] } else { Vec::new() };
938        let end = if shell.1 { vec![NSToolbarInspectorTrackingSeparatorItemIdentifier.to_string(), NSToolbarFlexibleSpaceItemIdentifier.to_string(), NSToolbarToggleInspectorItemIdentifier.to_string()] } else { Vec::new() };
939        (lead, end)
940    }
941}
942
943/// The toolbar item that keeps the title beside a sidebar.
944const SIDEBAR_SPACER: &str = "ferrokit.sidebar-spacer";
945
946define_class!(
947    #[unsafe(super(NSObject))]
948    #[thread_kind = MainThreadOnly]
949    #[name = "FerrokitToolbarDelegate"]
950    #[ivars = ToolbarState]
951    pub(crate) struct ToolbarDelegate;
952
953    unsafe impl NSObjectProtocol for ToolbarDelegate {}
954
955    unsafe impl NSToolbarDelegate for ToolbarDelegate {
956        #[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
957        fn item_for(&self, _toolbar: &NSToolbar, id: &NSString, insert: bool) -> Option<Retained<NSToolbarItem>> {
958            crate::failure::guard("a window's chrome (item_for)", None, || {
959                if id.to_string() == SIDEBAR_SPACER {
960                    Some(self.spacer_item(id))
961                } else {
962                    self.make_item(&id.to_string(), insert)
963                }
964            })
965        }
966
967        #[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
968        fn default_ids(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
969            let saved = self.saved();
970            let ids = saved.unwrap_or_else(|| self.ivars().entries.iter().filter(|e| !e.optional).map(|e| e.id.clone()).collect());
971            self.with_spacer(ids)
972        }
973
974        #[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
975        fn allowed_ids(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
976            let mut ids: Vec<String> = self.ivars().entries.iter().filter(|e| !matches!(e.spec, Spec::Standard)).map(|e| e.id.clone()).collect();
977            // SAFETY: AppKit's identifier constants.
978            ids.extend([unsafe { objc2_app_kit::NSToolbarSpaceItemIdentifier }.to_string(), unsafe { objc2_app_kit::NSToolbarFlexibleSpaceItemIdentifier }.to_string()]);
979            self.with_spacer(ids)
980        }
981
982        // The space that keeps the title beside a sidebar stays first.
983        #[unsafe(method_id(toolbarImmovableItemIdentifiers:))]
984        fn immovable_ids(&self, _toolbar: &NSToolbar) -> Retained<objc2_foundation::NSSet<NSString>> {
985            objc2_foundation::NSSet::from_retained_slice(&[NSString::from_str(SIDEBAR_SPACER)])
986        }
987
988        #[unsafe(method(toolbarWillAddItem:))]
989        fn will_add(&self, _notification: &NSNotification) {
990            crate::failure::guard("a window's chrome (will_add)", (), || {
991                self.save_soon();
992            })
993        }
994
995        #[unsafe(method(toolbarDidRemoveItem:))]
996        fn did_remove(&self, notification: &NSNotification) {
997            crate::failure::guard("a window's chrome (did_remove)", (), || {
998                // A removed item's effects and targets go with it.
999                let item = notification.userInfo().and_then(|u| u.objectForKey(&NSString::from_str("item"))).and_then(|i| i.downcast::<NSToolbarItem>().ok());
1000                if let Some(item) = item {
1001                    self.ivars().live.borrow_mut().remove(&item.itemIdentifier().to_string());
1002                }
1003                self.save_soon();
1004            })
1005        }
1006    }
1007);
1008
1009impl ToolbarDelegate {
1010    fn with_spacer(&self, ids: Vec<String>) -> Retained<NSArray<NSString>> {
1011        let (lead, end) = shell_ids(self.ivars().shell);
1012        let mut ids: Vec<Retained<NSString>> = lead.iter().chain(ids.iter()).chain(end.iter()).map(|s| NSString::from_str(s)).collect();
1013        if self.ivars().tracks_sidebar.get() {
1014            ids.insert(0, NSString::from_str(SIDEBAR_SPACER));
1015        }
1016        NSArray::from_retained_slice(&ids)
1017    }
1018
1019    fn key(&self) -> Option<Retained<NSString>> {
1020        self.ivars().remember.as_ref().map(|n| NSString::from_str(&format!("ferrokit.toolbar.{n}")))
1021    }
1022
1023    /// The layout the user saved, without items the app no longer has.
1024    fn saved(&self) -> Option<Vec<String>> {
1025        let list = NSUserDefaults::standardUserDefaults().stringArrayForKey(&*self.key()?)?;
1026        let known = |id: &str| {
1027            // SAFETY: AppKit's identifier constants.
1028            let standard = [unsafe { objc2_app_kit::NSToolbarSpaceItemIdentifier }.to_string(), unsafe { objc2_app_kit::NSToolbarFlexibleSpaceItemIdentifier }.to_string()];
1029            standard.iter().any(|s| s == id) || self.ivars().entries.iter().any(|e| e.id == id)
1030        };
1031        Some(list.iter().map(|s| s.to_string()).filter(|s| known(s)).collect())
1032    }
1033
1034    /// Saves a customisable toolbar's layout once the change is in.
1035    fn save_soon(&self) {
1036        let Some(key) = self.key() else { return };
1037        let Some(window) = self.ivars().window.load() else { return };
1038        let defaults: Vec<String> = self.ivars().entries.iter().filter(|e| !e.optional).map(|e| e.id.clone()).collect();
1039        let shell = self.ivars().shell;
1040        let had = NSUserDefaults::standardUserDefaults().stringArrayForKey(&key).map(|l| l.iter().map(|s| s.to_string()).collect::<Vec<_>>());
1041        let window = objc2::rc::Weak::from(&*window);
1042        crate::spawn(
1043            || (),
1044            move |()| {
1045                let Some(toolbar) = window.load().and_then(|w| w.toolbar()) else { return };
1046                // The shell's own items come back with it: not saved.
1047                let (lead, end) = shell_ids(shell);
1048                let mut ids: Vec<String> = toolbar.items().iter().map(|i| i.itemIdentifier().to_string()).filter(|i| i != SIDEBAR_SPACER).collect();
1049                if ids.starts_with(&lead) {
1050                    ids.drain(..lead.len());
1051                }
1052                if ids.ends_with(&end) {
1053                    ids.truncate(ids.len() - end.len());
1054                }
1055                // The app's own layout isn't saved (a later version's would
1056                // then show), only the user's.
1057                if had.as_ref() == Some(&ids) || (had.is_none() && ids == defaults) {
1058                    return;
1059                }
1060                let list = NSArray::from_retained_slice(&ids.iter().map(|s| NSString::from_str(s)).collect::<Vec<_>>());
1061                // SAFETY: an array of strings is a property list.
1062                unsafe { NSUserDefaults::standardUserDefaults().setObject_forKey(Some(&list), &key) };
1063            },
1064        );
1065    }
1066
1067    /// An empty navigational item (those come before the title), as wide
1068    /// as its constraint says.
1069    fn spacer_item(&self, id: &NSString) -> Retained<NSToolbarItem> {
1070        let mtm = MainThreadMarker::from(self);
1071        let view = NSView::new(mtm);
1072        view.setTranslatesAutoresizingMaskIntoConstraints(false);
1073        let before = self.ivars().spacer.borrow().as_ref().map_or(MIN_SPACE, |w| w.constant());
1074        let width = view.widthAnchor().constraintEqualToConstant(before);
1075        width.setActive(true);
1076        view.heightAnchor().constraintEqualToConstant(1.0).setActive(true);
1077        self.ivars().spacer.replace(Some(width));
1078        let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(mtm), id);
1079        item.setView(Some(&view));
1080        item.setNavigational(true);
1081        // No glass capsule around the space (macOS 26 gives items one).
1082        item.setBordered(false);
1083        objc2_app_kit::NSAccessibility::setAccessibilityElement(&*view, false);
1084        item
1085    }
1086
1087    /// Makes the item `id`: live (acting, following its signals) when it's
1088    /// going into the toolbar, a picture of itself for the customisation
1089    /// sheet otherwise.
1090    fn make_item(&self, id: &str, insert: bool) -> Option<Retained<NSToolbarItem>> {
1091        let mtm = MainThreadMarker::from(self);
1092        let state = self.ivars();
1093        let entry = state.entries.iter().find(|e| e.id == id)?;
1094        let ns_id = NSString::from_str(id);
1095        let mut live = Live::default();
1096        let symbol = |name: &str, label: &str| NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), Some(&NSString::from_str(label)));
1097        use objc2::Message as _;
1098        let target = |live: &mut Live, item: &NSToolbarItem, action: &Rc<dyn Fn(isize)>, disabled: Option<Rc<dyn Fn() -> bool>>| {
1099            let t = ToolbarTarget::new(mtm, action.clone(), disabled.clone(), state.window.clone());
1100            // SAFETY: the target responds to `fire:`; kept alive in `live`.
1101            unsafe {
1102                item.setTarget(Some(&t));
1103                item.setAction(Some(sel!(fire:)));
1104            }
1105            if disabled.is_some() {
1106                // Validated as events arrive, and at once when signals it reads change.
1107                let (i, t) = (item.retain(), t.clone());
1108                live.effects.push(Effect::new(move || i.setEnabled(t.enabled())));
1109            }
1110            live.keep.push(Retained::into_super(t));
1111        };
1112        let item: Retained<NSToolbarItem> = match &entry.spec {
1113            Spec::Button { label, symbol: name, action, disabled } => {
1114                let ti = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(mtm), &ns_id);
1115                ti.setLabel(&NSString::from_str(label));
1116                ti.setToolTip(Some(&NSString::from_str(label)));
1117                ti.setImage(symbol(name, label).as_deref());
1118                target(&mut live, &ti, action, disabled.clone());
1119                ti
1120            }
1121            Spec::Search { query } => {
1122                let si = NSSearchToolbarItem::initWithItemIdentifier(NSSearchToolbarItem::alloc(mtm), &ns_id);
1123                if insert {
1124                    let query = *query;
1125                    let field = si.searchField();
1126                    let delegate = FieldDelegate::new(mtm, query);
1127                    // SAFETY: the delegate is weak in AppKit; kept alive in `live`.
1128                    unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
1129                    live.effects.push(Effect::new(move || {
1130                        let v = query.get();
1131                        if field.stringValue().to_string() != v {
1132                            field.setStringValue(&NSString::from_str(&v));
1133                        }
1134                    }));
1135                    live.keep.push(Retained::into_super(delegate));
1136                }
1137                Retained::into_super(si)
1138            }
1139            Spec::Group { label, buttons, action } => {
1140                let group = group_item(mtm, &ns_id, label, buttons, objc2_app_kit::NSToolbarItemGroupSelectionMode::Momentary);
1141                target(&mut live, &group, action, None);
1142                group
1143            }
1144            Spec::Picker { label, choices, selected, choose } => {
1145                let group = group_item(mtm, &ns_id, label, choices, objc2_app_kit::NSToolbarItemGroupSelectionMode::SelectOne);
1146                target(&mut live, &group, choose, None);
1147                if let Some(g) = group.downcast_ref::<objc2_app_kit::NSToolbarItemGroup>().map(|g| g.retain()) {
1148                    let selected = selected.clone();
1149                    live.effects.push(Effect::new(move || g.setSelectedIndex(selected() as isize)));
1150                }
1151                group
1152            }
1153            Spec::Standard => return None,
1154        };
1155        if insert {
1156            state.live.borrow_mut().insert(id.to_string(), live);
1157        }
1158        Some(item)
1159    }
1160}
1161
1162/// A group of segments with SF Symbols, each labelled (VoiceOver, tooltips,
1163/// the overflow menu), under `label`.
1164fn group_item(mtm: MainThreadMarker, id: &NSString, label: &str, parts: &[(String, String)], mode: objc2_app_kit::NSToolbarItemGroupSelectionMode) -> Retained<NSToolbarItem> {
1165    let images: Vec<Retained<NSImage>> = parts
1166        .iter()
1167        .map(|(l, s)| NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(s), Some(&NSString::from_str(l))).unwrap_or_default())
1168        .collect();
1169    let labels: Vec<Retained<NSString>> = parts.iter().map(|(l, _)| NSString::from_str(l)).collect();
1170    // SAFETY: images and labels match in count; the target and action are
1171    // set by the caller.
1172    let group = unsafe {
1173        objc2_app_kit::NSToolbarItemGroup::groupWithItemIdentifier_images_selectionMode_labels_target_action(
1174            id,
1175            &NSArray::from_retained_slice(&images),
1176            mode,
1177            Some(&NSArray::from_retained_slice(&labels)),
1178            None,
1179            None,
1180            mtm,
1181        )
1182    };
1183    group.setLabel(&NSString::from_str(label));
1184    for (sub, (l, _)) in group.subitems().iter().zip(parts) {
1185        sub.setToolTip(Some(&NSString::from_str(l)));
1186    }
1187    Retained::into_super(group)
1188}
1189
1190/// Gives `window` a unified toolbar with `items` (kept alive by the window
1191/// list for the app's lifetime); `remember` makes it customisable, its
1192/// layout saved under that name.
1193pub(crate) fn install_toolbar(window: &NSWindow, items: Vec<ToolbarItem>, remember: Option<String>, shell: (bool, bool)) -> Retained<NSObject> {
1194    let mtm = MainThreadMarker::from(window);
1195    let entries = items.into_iter().map(ToolbarEntry::new).collect();
1196    let customizable = remember.is_some();
1197    let state = ToolbarState { entries, live: RefCell::default(), window: objc2::rc::Weak::from(window), spacer: RefCell::default(), tracks_sidebar: std::cell::Cell::new(false), remember, shell };
1198    let delegate = ToolbarDelegate::alloc(mtm).set_ivars(state);
1199    // SAFETY: NSObject's designated initialiser.
1200    let delegate: Retained<ToolbarDelegate> = unsafe { msg_send![super(delegate), init] };
1201    // One identifier per toolbar: toolbars sharing one keep their items in
1202    // sync across windows, and each window's title spacer is its own.
1203    thread_local! {
1204        static TOOLBARS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1205    }
1206    let n = TOOLBARS.with(|t| {
1207        t.set(t.get() + 1);
1208        t.get()
1209    });
1210    let toolbar = NSToolbar::initWithIdentifier(NSToolbar::alloc(mtm), &NSString::from_str(&format!("ferrokit.toolbar.{n}")));
1211    toolbar.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
1212    toolbar.setAllowsUserCustomization(customizable);
1213    // Symbols alone, as Apple's apps show them (the labels stay for
1214    // VoiceOver, tooltips and the overflow menu).
1215    toolbar.setDisplayMode(objc2_app_kit::NSToolbarDisplayMode::IconOnly);
1216    window.setToolbar(Some(&toolbar));
1217    window.setToolbarStyle(NSWindowToolbarStyle::Unified);
1218    Retained::into_super(delegate)
1219}
1220
1221/// Keeps `window`'s title and toolbar items beside the sidebar (`split`'s
1222/// first pane), as Apple's apps with a sidebar have them, instead of over
1223/// it: a navigational space before the title, as wide as the sidebar,
1224/// following its divider. (AppKit's own tracking separator needs a split
1225/// view controller, whose title-bar sections kept every closed window's
1226/// frame alive when hosted in Ferrokit's views.)
1227pub(crate) fn track_sidebar(window: &NSWindow, delegate: &NSObject, split: &NSSplitView) {
1228    let info = split.delegate().filter(|d| {
1229        // SAFETY: reading the class of an object AppKit holds.
1230        let obj: &AnyObject = unsafe { &*Retained::as_ptr(d).cast::<AnyObject>() };
1231        obj.class().name().to_str() == Ok("FerrokitSplitDelegate")
1232    });
1233    let (Some(toolbar), Some(delegate), Some(info)) = (window.toolbar(), delegate.downcast_ref::<ToolbarDelegate>(), info) else {
1234        return;
1235    };
1236    // SAFETY: checked above that it's a `SplitDelegate`.
1237    let info: Retained<SplitDelegate> = unsafe { Retained::cast_unchecked(info) };
1238    delegate.ivars().tracks_sidebar.set(true);
1239    toolbar.insertItemWithItemIdentifier_atIndex(&NSString::from_str(SIDEBAR_SPACER), 0);
1240    let Some(width) = delegate.ivars().spacer.borrow().clone() else { return };
1241    let window = objc2::rc::Weak::from(window);
1242    let fit = move |split: &NSSplitView| {
1243        if let Some(window) = window.load() {
1244            fit_title(&window, split, &width);
1245        }
1246    };
1247    fit(split);
1248    info.ivars().on_resize.replace(Some(Box::new(fit)));
1249}
1250
1251/// The space's narrowest width: AppKit warns about toolbar item views of
1252/// zero width.
1253const MIN_SPACE: f64 = 1.0;
1254
1255/// Sizes the space before the title so the title starts 18 points past the
1256/// sidebar's edge (none while the sidebar is hidden). Measured, not
1257/// computed: AppKit's spacing around toolbar items varies by version.
1258fn fit_title(window: &NSWindow, split: &NSSplitView, width: &objc2_app_kit::NSLayoutConstraint) {
1259    let sidebar = split.arrangedSubviews().firstObject().filter(|p| !p.isHidden()).map_or(0.0, |p| p.frame().size.width);
1260    let Some(frame) = window.contentView().and_then(|c| unsafe { c.superview() }) else { return };
1261    let title = window.title().to_string();
1262    for _ in 0..3 {
1263        if sidebar < 1.0 {
1264            width.setConstant(MIN_SPACE);
1265            return;
1266        }
1267        frame.layoutSubtreeIfNeeded();
1268        let Some(label) = title_label(&frame, &title) else {
1269            // No title shown: start the items past the traffic lights' area.
1270            width.setConstant((sidebar - 80.0).max(MIN_SPACE));
1271            return;
1272        };
1273        let x = label.convertRect_toView(label.bounds(), None).origin.x;
1274        let want = (width.constant() + sidebar + 18.0 - x).max(MIN_SPACE);
1275        if (want - width.constant()).abs() < 0.5 {
1276            return;
1277        }
1278        width.setConstant(want);
1279    }
1280}
1281
1282/// The text field in the title bar showing `title`.
1283fn title_label(view: &NSView, title: &str) -> Option<Retained<objc2_app_kit::NSTextField>> {
1284    for sub in view.subviews().iter() {
1285        if let Some(f) = sub.clone().downcast::<objc2_app_kit::NSTextField>().ok().filter(|f| f.stringValue().to_string() == title && !f.isHidden()) {
1286            return Some(f);
1287        }
1288        // Not into the window's content.
1289        if sub.class().name().to_str() != Ok("FerrokitRootView")
1290            && let Some(f) = title_label(&sub, title)
1291        {
1292            return Some(f);
1293        }
1294    }
1295    None
1296}