1use 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
20define_class!(
23 #[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; }
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 #[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 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 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 collapsed.set_if_changed(split.isSubviewCollapsed(&pane) || pane.isHidden() || (size < 1.0 && !crate::in_layout()));
100 }
101 }
102 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 key: Option<Retained<NSString>>,
118 collapsible: Vec<(usize, Signal<bool>)>,
120 applying: std::cell::Cell<bool>,
123 on_resize: RefCell<Option<OnResize>>,
125}
126
127type OnResize = Box<dyn Fn(&NSSplitView)>;
128
129pub 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 pub fn collapsible(mut self, index: usize, collapsed: &Signal<bool>) -> Self {
161 self.collapsible.push((index, *collapsed));
162 self
163 }
164
165 pub fn trailing(mut self, points: f64) -> Self {
168 self.trailing = Some(points);
169 self
170 }
171
172 pub fn stacked(mut self) -> Self {
175 self.stacked = true;
176 self
177 }
178
179 pub fn position(mut self, points: f64) -> Self {
182 self.position = Some(points);
183 self
184 }
185
186 pub fn remember(mut self, name: &str) -> Self {
190 self.remember = Some(name.into());
191 self
192 }
193}
194
195pub(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 let delegate: Retained<SplitDelegate> = unsafe { msg_send![super(delegate), init] };
212 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 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 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 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 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 for pane in typed {
282 *pane.ivars().borrow_mut() = Rc::downgrade(&node.meta);
283 }
284 node
285 }
286}
287
288fn 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
297pub 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
302define_class!(
305 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub enum Modifier {
345 Command,
347 Shift,
349 Option,
351 Control,
353}
354
355pub 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 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 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 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 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 pub fn key(self, key: &str) -> Self {
409 self.key_with(key, &[])
410 }
411
412 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
430pub 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
440pub 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 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
485pub 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 unsafe { t.runCustomizationPalette(None) };
497 }
498 })
499 .disabled(move || toolbar().is_none())
500}
501
502pub fn menu_separator() -> MenuItem {
504 MenuItem(Entry::Separator)
505}
506
507pub fn submenu(title: &str, items: Vec<MenuItem>) -> MenuItem {
509 MenuItem(Entry::Submenu { title: title.into(), items })
510}
511
512pub 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 targets: RefCell<Vec<Retained<NSObject>>>,
522}
523
524define_class!(
525 #[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
558pub(crate) fn build_menu(mtm: MainThreadMarker, items: Vec<MenuItem>) -> (Retained<NSMenu>, Vec<Retained<NSObject>>) {
560 build_titled_menu(mtm, "", items)
561}
562
563pub(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 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 let delegate: Retained<DynamicMenu> = unsafe { msg_send![super(delegate), init] };
592 delegate.refill(&sub);
593 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 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 unsafe { ns.setTarget(Some(&target)) };
609 menu.addItem(&ns);
610 keep.push(Retained::into_super(target));
611 }
612 }
613 }
614 (menu, keep)
615}
616
617pub(crate) fn plain_item(mtm: MainThreadMarker, title: &str, action: Option<objc2::runtime::Sel>, key: &str) -> Retained<NSMenuItem> {
619 unsafe {
621 NSMenuItem::initWithTitle_action_keyEquivalent(NSMenuItem::alloc(mtm), &NSString::from_str(title), action, &NSString::from_str(key))
622 }
623}
624
625pub(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
635pub struct ToolbarItem(pub(crate) Item);
641
642pub(crate) enum Item {
645 Button {
647 id: String,
649 label: String,
651 symbol: String,
653 action: Box<dyn Fn()>,
655 disabled: Option<Box<dyn Fn() -> bool>>,
657 },
658 FlexibleSpace,
660 Space,
662 Search {
664 id: String,
666 query: Signal<String>,
668 },
669 Group {
672 id: String,
674 label: String,
676 buttons: Vec<ToolbarItem>,
679 },
680 Picker {
682 id: String,
684 label: String,
686 choices: Vec<(String, String)>,
688 selected: Box<dyn Fn() -> usize>,
690 choose: Box<dyn Fn(usize)>,
692 },
693 Optional(Box<ToolbarItem>),
696}
697
698impl ToolbarItem {
699 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 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 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
732pub 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
737pub fn toolbar_space() -> ToolbarItem {
739 ToolbarItem(Item::FlexibleSpace)
740}
741
742pub fn toolbar_fixed_space() -> ToolbarItem {
744 ToolbarItem(Item::Space)
745}
746
747pub fn toolbar_search(id: &str, query: &Signal<String>) -> ToolbarItem {
749 ToolbarItem(Item::Search { id: id.into(), query: *query })
750}
751
752pub fn toolbar_group(id: &str, label: &str, buttons: Vec<ToolbarItem>) -> ToolbarItem {
767 ToolbarItem(Item::Group { id: id.into(), label: label.into(), buttons })
768}
769
770pub 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
801enum 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 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
855pub(crate) struct ToolbarAction {
857 action: Rc<dyn Fn(isize)>,
859 disabled: Option<Rc<dyn Fn() -> bool>>,
860 window: objc2::rc::Weak<NSWindow>,
861}
862
863define_class!(
864 #[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 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 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#[derive(Default)]
908struct Live {
909 keep: Vec<Retained<NSObject>>,
910 effects: Vec<Effect>,
911}
912
913pub(crate) struct ToolbarState {
914 entries: Vec<ToolbarEntry>,
915 live: RefCell<std::collections::HashMap<String, Live>>,
918 window: objc2::rc::Weak<NSWindow>,
920 spacer: RefCell<Option<Retained<objc2_app_kit::NSLayoutConstraint>>>,
923 tracks_sidebar: std::cell::Cell<bool>,
925 remember: Option<String>,
927 shell: (bool, bool),
930}
931
932fn shell_ids(shell: (bool, bool)) -> (Vec<String>, Vec<String>) {
934 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
943const 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 ids.extend([unsafe { objc2_app_kit::NSToolbarSpaceItemIdentifier }.to_string(), unsafe { objc2_app_kit::NSToolbarFlexibleSpaceItemIdentifier }.to_string()]);
979 self.with_spacer(ids)
980 }
981
982 #[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 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 fn saved(&self) -> Option<Vec<String>> {
1025 let list = NSUserDefaults::standardUserDefaults().stringArrayForKey(&*self.key()?)?;
1026 let known = |id: &str| {
1027 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 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 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 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 unsafe { NSUserDefaults::standardUserDefaults().setObject_forKey(Some(&list), &key) };
1063 },
1064 );
1065 }
1066
1067 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 item.setBordered(false);
1083 objc2_app_kit::NSAccessibility::setAccessibilityElement(&*view, false);
1084 item
1085 }
1086
1087 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 unsafe {
1102 item.setTarget(Some(&t));
1103 item.setAction(Some(sel!(fire:)));
1104 }
1105 if disabled.is_some() {
1106 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 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
1162fn 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 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
1190pub(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 let delegate: Retained<ToolbarDelegate> = unsafe { msg_send![super(delegate), init] };
1201 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 toolbar.setDisplayMode(objc2_app_kit::NSToolbarDisplayMode::IconOnly);
1216 window.setToolbar(Some(&toolbar));
1217 window.setToolbarStyle(NSWindowToolbarStyle::Unified);
1218 Retained::into_super(delegate)
1219}
1220
1221pub(crate) fn track_sidebar(window: &NSWindow, delegate: &NSObject, split: &NSSplitView) {
1228 let info = split.delegate().filter(|d| {
1229 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 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
1251const MIN_SPACE: f64 = 1.0;
1254
1255fn 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 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
1282fn 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 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}