1use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use ferrokit_core::kept::{UiCell, UiLocal as _};
9
10use objc2::rc::Retained;
11use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
12use objc2::{DefinedClass, MainThreadOnly, define_class, msg_send, sel};
13use objc2_app_kit::{
14 NSButton, NSControlStateValueOff, NSControlStateValueOn, NSControlTextEditingDelegate, NSLevelIndicator, NSLevelIndicatorStyle, NSPathControl,
15 NSTabView, NSTabViewDelegate, NSTabViewItem, NSTabViewType, NSTextField, NSTextFieldDelegate, NSTokenField, NSTokenFieldDelegate, NSView,
16};
17use objc2_foundation::{NSArray, NSAttributedString, NSDictionary, NSNotification, NSString, NSURL};
18
19use crate::appkit_views::ActionTarget;
20use crate::signal::{Effect, Signal, batch};
21use crate::view::{AnyView, Axis, Cx, Kind, Node, Size, View, hstack, spacer, vstack};
22
23fn as_view<T: objc2::ClassType>(v: &Retained<T>) -> Retained<NSView> {
24 unsafe { Retained::cast_unchecked(v.clone()) }
26}
27
28fn wire(control: &objc2_app_kit::NSControl, target: &ActionTarget) {
29 unsafe {
31 control.setTarget(Some(target));
32 control.setAction(Some(sel!(fire:)));
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub enum TabStyle {
42 #[default]
45 Bordered,
46 Segmented,
49}
50
51pub struct Tabs<T> {
53 value: Signal<T>,
54 pages: Vec<(String, T, AnyView)>,
55 style: TabStyle,
56}
57
58impl<T> Tabs<T> {
59 pub fn style(mut self, style: TabStyle) -> Self {
61 self.style = style;
62 self
63 }
64}
65
66struct Hosted(Vec<Retained<NSView>>);
68
69impl Drop for Hosted {
70 fn drop(&mut self) {
71 for root in &self.0 {
72 crate::drop_hosted(root);
73 }
74 }
75}
76
77define_class!(
78 #[unsafe(super(NSObject))]
80 #[thread_kind = MainThreadOnly]
81 #[name = "FerrokitTabDelegate"]
82 #[ivars = Box<dyn Fn(usize)>]
83 struct TabDelegate;
84
85 unsafe impl NSObjectProtocol for TabDelegate {}
86
87 unsafe impl NSTabViewDelegate for TabDelegate {
88 #[unsafe(method(tabView:didSelectTabViewItem:))]
89 fn did_select(&self, tab_view: &NSTabView, item: Option<&NSTabViewItem>) {
90 crate::failure::guard("a control (did_select)", (), || {
91 if let Some(item) = item {
92 let i = tab_view.indexOfTabViewItem(item);
93 if i >= 0 {
94 batch(|| (self.ivars())(i as usize));
95 }
96 }
97 })
98 }
99 }
100);
101
102struct TabView<T> {
104 value: Signal<T>,
105 pages: Vec<(String, T, AnyView)>,
106 tabless: bool,
107}
108
109impl<T: PartialEq + Clone + 'static> View for TabView<T> {
110 fn build(self, cx: &mut Cx) -> Node {
111 let mtm = cx.mtm;
112 let tab_view = NSTabView::new(mtm);
113 if self.tabless {
114 tab_view.setTabViewType(NSTabViewType::NoTabsNoBorder);
115 }
116 let mut roots = Vec::new();
117 let mut biggest = NSSizeLike::default();
118 let mut values = Vec::new();
119 for (title, value, view) in self.pages {
120 let view = AnyView::new(crate::view::zstack((view,)).alignment(crate::Align::Start, crate::Align::Start));
124 let (root, size) = crate::host_view(view);
125 biggest.w = biggest.w.max(size.width);
126 biggest.h = biggest.h.max(size.height);
127 let item = unsafe { NSTabViewItem::initWithIdentifier(objc2::AnyThread::alloc(), None) };
129 item.setLabel(&NSString::from_str(&title));
130 item.setView(Some(&root));
131 tab_view.addTabViewItem(&item);
132 roots.push(root);
133 values.push(value);
134 }
135 let values = Rc::new(values);
136 let (signal, vs) = (self.value, values.clone());
137 let delegate = TabDelegate::alloc(mtm).set_ivars(Box::new(move |i: usize| {
138 if let Some(v) = vs.get(i) {
139 signal.set_if_changed(v.clone());
140 }
141 }) as Box<dyn Fn(usize)>);
142 let delegate: Retained<TabDelegate> = unsafe { msg_send![super(delegate), init] };
144 tab_view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
145 let chrome = {
147 let frame = tab_view.frame().size;
148 let content = tab_view.contentRect().size;
149 (frame.width - content.width, frame.height - content.height)
150 };
151 let min = Size { w: biggest.w + chrome.0.max(0.0), h: biggest.h + chrome.1.max(0.0) };
152 let (mut node, _) = Node::leaf(cx, as_view(&tab_view), (true, true), min);
153 let value = self.value;
154 node.own(Effect::new(move || {
155 let current = value.get();
156 if let Some(i) = values.iter().position(|v| *v == current) {
157 let selected = tab_view.selectedTabViewItem().map(|t| tab_view.indexOfTabViewItem(&t));
158 if selected != Some(i as isize) {
159 tab_view.selectTabViewItemAtIndex(i as isize);
160 }
161 }
162 }));
163 node.keep(Retained::into_super(delegate));
164 node.hold(Rc::new(Hosted(roots)));
165 node
166 }
167}
168
169#[derive(Default)]
170struct NSSizeLike {
171 w: f64,
172 h: f64,
173}
174
175impl<T: PartialEq + Clone + 'static> View for Tabs<T> {
176 fn build(self, cx: &mut Cx) -> Node {
177 match self.style {
178 TabStyle::Bordered => TabView { value: self.value, pages: self.pages, tabless: false }.build(cx),
179 TabStyle::Segmented => {
180 let options: Vec<(String, T)> = self.pages.iter().map(|(t, v, _)| (t.clone(), v.clone())).collect();
181 let picker = crate::controls::segmented(&self.value, options.iter().map(|(t, v)| (t.as_str(), v.clone())).collect());
182 vstack((hstack((spacer(), picker, spacer())), TabView { value: self.value, pages: self.pages, tabless: true }))
183 .spacing(12.0)
184 .build(cx)
185 }
186 }
187 }
188}
189
190pub fn tabs<T: PartialEq + Clone + 'static>(value: &Signal<T>, pages: Vec<(&str, T, AnyView)>) -> Tabs<T> {
206 Tabs { value: *value, pages: pages.into_iter().map(|(t, v, p)| (t.to_string(), v, p)).collect(), style: TabStyle::default() }
207}
208
209thread_local! {
212 static GROUP_ACTIONS: UiCell<(Vec<usize>, usize)> = const { UiCell::new((Vec::new(), 0)) };
214}
215
216struct GroupAction(usize);
219
220impl GroupAction {
221 fn take() -> Self {
222 GroupAction(GROUP_ACTIONS.with_borrow_mut(|(free, made)| {
223 free.pop().unwrap_or_else(|| {
224 *made += 1;
225 *made - 1
226 })
227 }))
228 }
229
230 fn selector(&self) -> objc2::runtime::Sel {
231 use objc2::ClassType;
232 let name = std::ffi::CString::new(format!("fireGroup{}:", self.0)).unwrap_or_default();
233 let sel = objc2::runtime::Sel::register(&name);
234 let class = ActionTarget::class();
235 if class.instance_method(sel).is_none()
236 && let Some(fire) = class.instance_method(sel!(fire:))
237 {
238 unsafe { objc2::ffi::class_addMethod(std::ptr::from_ref(class).cast_mut(), sel, fire.implementation(), c"v@:@".as_ptr()) };
241 }
242 sel
243 }
244}
245
246impl Drop for GroupAction {
247 fn drop(&mut self) {
248 GROUP_ACTIONS.with_borrow_mut(|(free, _)| free.push(self.0));
249 }
250}
251
252pub struct RadioGroup<T> {
254 value: Signal<T>,
255 options: Vec<(String, T)>,
256 horizontal: bool,
257}
258
259impl<T> RadioGroup<T> {
260 pub fn horizontal(mut self) -> Self {
262 self.horizontal = true;
263 self
264 }
265}
266
267impl<T: PartialEq + Clone + 'static> View for RadioGroup<T> {
268 fn build(self, cx: &mut Cx) -> Node {
269 let mut children = Vec::new();
270 let mut buttons = Vec::new();
271 let mut targets = Vec::new();
272 let action = GroupAction::take();
276 for (title, v) in &self.options {
277 let b = unsafe { NSButton::radioButtonWithTitle_target_action(&NSString::from_str(title), None, None, cx.mtm) };
279 let (signal, v) = (self.value, v.clone());
280 let target = ActionTarget::new(cx.mtm, move || signal.set_if_changed(v.clone()));
281 unsafe {
284 b.setTarget(Some(&*target));
285 b.setAction(Some(action.selector()));
286 }
287 let (node, _) = Node::leaf(cx, as_view(&b), (false, false), Size::default());
288 children.push(node);
289 buttons.push(b);
290 targets.push(target);
291 }
292 let axis = if self.horizontal { Axis::Horizontal } else { Axis::Vertical };
293 let mut node = Node::new(Kind::Stack { axis, spacing: if self.horizontal { 14.0 } else { 6.0 }, align: Some(crate::Align::Start), children });
294 let (value, options) = (self.value, self.options);
295 node.own(Effect::new(move || {
296 let _ = &action;
298 let current = value.get();
299 for (b, (_, v)) in buttons.iter().zip(&options) {
300 let want = if *v == current { NSControlStateValueOn } else { NSControlStateValueOff };
301 if b.state() != want {
302 b.setState(want);
303 }
304 }
305 }));
306 for t in targets {
307 node.keep(Retained::into_super(t));
308 }
309 node
310 }
311}
312
313pub fn radio_group<T: PartialEq + Clone + 'static>(value: &Signal<T>, options: Vec<(&str, T)>) -> RadioGroup<T> {
316 RadioGroup { value: *value, options: options.into_iter().map(|(t, v)| (t.to_string(), v)).collect(), horizontal: false }
317}
318
319define_class!(
322 #[unsafe(super(NSTextField, objc2_app_kit::NSControl, NSView, objc2_app_kit::NSResponder, NSObject))]
325 #[thread_kind = MainThreadOnly]
326 #[name = "FerrokitLink"]
327 #[ivars = Retained<NSURL>]
328 struct LinkField;
329
330 impl LinkField {
331 #[unsafe(method_id(accessibilityRole))]
332 fn ax_role(&self) -> Option<Retained<NSString>> {
333 crate::failure::guard("a control (ax_role)", None, || {
334 Some(objc2_foundation::NSCopying::copy(unsafe { objc2_app_kit::NSAccessibilityLinkRole }))
336 })
337 }
338
339 #[unsafe(method(accessibilityPerformPress))]
340 fn ax_press(&self) -> bool {
341 crate::failure::guard("a control (ax_press)", false, || {
342 objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(self.ivars())
343 })
344 }
345 }
346);
347
348pub struct Link {
350 title: String,
351 url: String,
352}
353
354impl View for Link {
355 fn build(self, cx: &mut Cx) -> Node {
356 let Some(url) = NSURL::URLWithString(&NSString::from_str(&self.url)) else {
357 return crate::appkit_views::text(&self.title).build(cx);
358 };
359 let link = url.clone();
360 let attrs = unsafe {
362 NSDictionary::from_retained_objects(
363 &[objc2_app_kit::NSLinkAttributeName, objc2_app_kit::NSFontAttributeName],
364 &[Retained::<AnyObject>::from(Retained::into_super(link)), Retained::<AnyObject>::from(Retained::into_super(objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize())))],
365 )
366 };
367 let text = unsafe { NSAttributedString::initWithString_attributes(objc2::AnyThread::alloc(), &NSString::from_str(&self.title), Some(&attrs)) };
369 let field = LinkField::alloc(cx.mtm).set_ivars(url.clone());
370 let field: Retained<LinkField> = unsafe { msg_send![super(field), initWithFrame: objc2_foundation::NSRect::ZERO] };
372 field.setBezeled(false);
375 field.setDrawsBackground(false);
376 field.setEditable(false);
377 field.setSelectable(true);
378 field.setAllowsEditingTextAttributes(true);
379 field.setAttributedStringValue(&text);
380 Node::leaf(cx, as_view(&field), (false, false), Size::default()).0
381 }
382}
383
384pub fn link(title: &str, url: &str) -> Link {
387 Link { title: title.into(), url: url.into() }
388}
389
390pub struct Gauge {
394 value: GaugeValue,
395 max: f64,
396 style: NSLevelIndicatorStyle,
397 warning: Option<f64>,
398 critical: Option<f64>,
399}
400
401enum GaugeValue {
402 Shown(Box<dyn Fn() -> f64>),
403 Edited(Signal<f64>),
404}
405
406impl Gauge {
407 pub fn discrete(mut self) -> Self {
409 self.style = NSLevelIndicatorStyle::DiscreteCapacity;
410 self
411 }
412
413 pub fn warning(mut self, value: f64) -> Self {
416 self.warning = Some(value);
417 self
418 }
419
420 pub fn critical(mut self, value: f64) -> Self {
422 self.critical = Some(value);
423 self
424 }
425}
426
427impl View for Gauge {
428 fn build(self, cx: &mut Cx) -> Node {
429 let g = NSLevelIndicator::new(cx.mtm);
430 g.setLevelIndicatorStyle(self.style);
431 g.setMinValue(0.0);
432 g.setMaxValue(self.max);
433 if let Some(w) = self.warning {
434 g.setWarningValue(w);
435 }
436 if let Some(c) = self.critical {
437 g.setCriticalValue(c);
438 }
439 let rating = self.style == NSLevelIndicatorStyle::Rating;
440 let flex = (!rating, false);
441 let min = if rating { Size::default() } else { Size { w: 120.0, h: 0.0 } };
442 let (mut node, _) = Node::leaf(cx, as_view(&g), flex, min);
443 match self.value {
444 GaugeValue::Shown(f) => {
445 let g2 = g.clone();
446 node.own(Effect::new(move || g2.setDoubleValue(f())));
447 }
448 GaugeValue::Edited(signal) => {
449 g.setEditable(true);
450 let g2 = g.clone();
451 let target = ActionTarget::new(cx.mtm, move || signal.set_if_changed(g2.doubleValue()));
452 wire(&g, &target);
453 node.keep(Retained::into_super(target));
454 let g3 = g.clone();
455 node.own(Effect::new(move || {
456 let v = signal.get();
457 if g3.doubleValue() != v {
458 g3.setDoubleValue(v);
459 }
460 }));
461 }
462 }
463 node
464 }
465}
466
467pub fn gauge(value: impl crate::IntoValue<f64>, max: f64) -> Gauge {
472 let value = value.into_value();
473 Gauge { value: GaugeValue::Shown(Box::new(move || value.get())), max, style: NSLevelIndicatorStyle::ContinuousCapacity, warning: None, critical: None }
474}
475
476pub fn rating(value: &Signal<f64>, max: u32) -> Gauge {
479 Gauge { value: GaugeValue::Edited(*value), max: max as f64, style: NSLevelIndicatorStyle::Rating, warning: None, critical: None }
480}
481
482struct TokenState {
486 value: Signal<Vec<String>>,
487 suggestions: Vec<String>,
488}
489
490define_class!(
491 #[unsafe(super(NSObject))]
493 #[thread_kind = MainThreadOnly]
494 #[name = "FerrokitTokenDelegate"]
495 #[ivars = TokenState]
496 struct TokenDelegate;
497
498 unsafe impl NSObjectProtocol for TokenDelegate {}
499
500 unsafe impl NSControlTextEditingDelegate for TokenDelegate {
501 #[unsafe(method(controlTextDidChange:))]
502 fn did_change(&self, notification: &NSNotification) {
503 crate::failure::guard("a control (did_change)", (), || {
504 self.read(notification);
505 })
506 }
507
508 #[unsafe(method(controlTextDidEndEditing:))]
509 fn did_end(&self, notification: &NSNotification) {
510 crate::failure::guard("a control (did_end)", (), || {
511 self.read(notification);
512 })
513 }
514 }
515
516 unsafe impl NSTextFieldDelegate for TokenDelegate {}
517
518 unsafe impl NSTokenFieldDelegate for TokenDelegate {
519 #[unsafe(method_id(tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:))]
520 fn completions(&self, _field: &NSTokenField, substring: &NSString, _index: isize, _selected: *mut isize) -> Option<Retained<NSArray>> {
521 crate::failure::guard("a control (completions)", None, || {
522 let typed = substring.to_string().to_lowercase();
523 let matches: Vec<Retained<NSString>> =
524 self.ivars().suggestions.iter().filter(|s| s.to_lowercase().starts_with(&typed)).map(|s| NSString::from_str(s)).collect();
525 Retained::into_super(NSArray::from_retained_slice(&matches)).downcast().ok()
526 })
527 }
528 }
529);
530
531impl TokenDelegate {
532 fn read(&self, notification: &NSNotification) {
533 let Some(field) = notification.object().and_then(|o| o.downcast::<NSTokenField>().ok()) else { return };
534 let tokens = tokens_of(&field);
535 let signal = self.ivars().value;
536 batch(|| signal.set_if_changed(tokens));
537 }
538}
539
540fn tokens_of(field: &NSTokenField) -> Vec<String> {
543 let Some(value) = field.objectValue() else { return Vec::new() };
544 match value.downcast::<NSArray>() {
545 Ok(array) => array.iter().filter_map(|o| o.downcast::<NSString>().ok()).map(|s| s.to_string()).filter(|s| !s.is_empty()).collect(),
546 Err(other) => other.downcast::<NSString>().ok().map(|s| s.to_string()).filter(|s| !s.is_empty()).into_iter().collect(),
547 }
548}
549
550pub struct TokenField {
552 value: Signal<Vec<String>>,
553 suggestions: Vec<String>,
554 placeholder: Option<String>,
555}
556
557impl TokenField {
558 pub fn suggestions(mut self, suggestions: &[&str]) -> Self {
561 self.suggestions = suggestions.iter().map(|s| s.to_string()).collect();
562 self
563 }
564
565 pub fn placeholder(mut self, text: &str) -> Self {
567 self.placeholder = Some(text.into());
568 self
569 }
570}
571
572impl View for TokenField {
573 fn build(self, cx: &mut Cx) -> Node {
574 let field = NSTokenField::new(cx.mtm);
575 if let Some(p) = &self.placeholder {
576 field.setPlaceholderString(Some(&NSString::from_str(p)));
577 }
578 let delegate = TokenDelegate::alloc(cx.mtm).set_ivars(TokenState { value: self.value, suggestions: self.suggestions });
579 let delegate: Retained<TokenDelegate> = unsafe { msg_send![super(delegate), init] };
581 unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
583 let (mut node, handle) = Node::leaf(cx, as_view(&field), (true, false), Size { w: 160.0, h: 0.0 });
584 handle.content.set(Some(Size { w: 160.0, h: field.fittingSize().height }));
586 let value = self.value;
587 node.own(Effect::new(move || {
588 let tokens = value.get();
589 if tokens_of(&field) != tokens {
590 let strings: Vec<Retained<NSString>> = tokens.iter().map(|t| NSString::from_str(t)).collect();
591 unsafe { field.setObjectValue(Some(&NSArray::from_retained_slice(&strings))) };
593 }
594 }));
595 node.keep(Retained::into_super(delegate));
596 node
597 }
598}
599
600pub fn token_field(value: &Signal<Vec<String>>) -> TokenField {
603 TokenField { value: *value, suggestions: Vec::new(), placeholder: None }
604}
605
606pub struct PathControl(Signal<PathBuf>);
610
611impl View for PathControl {
612 fn build(self, cx: &mut Cx) -> Node {
613 let control = NSPathControl::new(cx.mtm);
614 let signal = self.0;
615 let c = control.clone();
616 let target = ActionTarget::new(cx.mtm, move || {
618 let url = c.clickedPathItem().and_then(|i| i.URL()).or_else(|| c.URL());
619 if let Some(path) = url.and_then(|u| u.path()) {
620 signal.set_if_changed(PathBuf::from(path.to_string()));
621 }
622 });
623 wire(&control, &target);
624 control.setURL(Some(&file_url(&crate::signal::untrack(|| signal.get()))));
626 let (mut node, handle) = Node::leaf(cx, as_view(&control), (true, false), Size { w: 160.0, h: 0.0 });
627 handle.content.set(Some(Size { w: 160.0, h: control.fittingSize().height }));
630 node.own(Effect::new(move || {
631 let path = signal.get();
632 let current = control.URL().and_then(|u| u.path()).map(|p| PathBuf::from(p.to_string()));
633 if current.as_deref() != Some(path.as_path()) {
634 control.setURL(Some(&file_url(&path)));
635 }
636 }));
637 node.keep(Retained::into_super(target));
638 node
639 }
640}
641
642fn file_url(path: &Path) -> Retained<NSURL> {
643 NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
644}
645
646pub fn path_control(path: &Signal<PathBuf>) -> PathControl {
649 PathControl(*path)
650}