1#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{NSObjectProtocol, ProtocolObject};
27use objc2::{
28 AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSUserInterfaceItemIdentification as _;
36use objc2_app_kit::{
37 NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
38 NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
39};
40use objc2_app_kit::{
41 NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
42 NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
43 NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
44 NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
45 NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
46 NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
47 NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
48 NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
49 NSWindowDelegate, NSWindowStyleMask,
50};
51use objc2_app_kit::{
52 NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
53 NSApplicationWillTerminateNotification,
54};
55use objc2_app_kit::{
56 NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
57};
58use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
59use objc2_core_foundation::CGAffineTransform;
60use objc2_foundation::{
61 NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
62 NSNumber, NSObject, NSPoint, NSRect, NSSize, NSString,
63};
64use objc2_quartz_core::{
65 CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
66 kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
67 kCAMediaTimingFunctionLinear,
68};
69
70use day_spec::ffi_guard;
71use day_spec::present;
72use day_spec::props::*;
73use day_spec::sidetable::SideTable;
74use day_spec::{
75 A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
76 InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
77 Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
78 WindowOptions, kinds, props_of,
79};
80
81pub type Handle = Retained<NSView>;
82
83pub use toolbar::image_for as toolbar_image;
85
86mod dock;
88mod documents;
89mod frame;
90mod picker;
91mod status_item;
92mod textarea;
93mod toolbar;
94mod transfer;
95mod window_chrome;
96use objc2_app_kit::NSDraggingSource;
97
98pub mod ext;
99pub use ext::*;
100
101type Sink = Rc<dyn Fn(NodeId, Event)>;
107
108day_core::tls_group! {
109 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
110 static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
112 static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
117 RefCell::new(HashMap::new());
118 static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
120 static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
124
125 static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
128 static APP_LABELED: SideTable<()> = SideTable::new();
131 static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
137 static TRANSFORMS: SideTable<Transform> = SideTable::new();
141 static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
144 static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
145 static SHEET_NODES: SideTable<NodeId> = SideTable::new();
147 static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
148 static PAN_NODES: SideTable<NodeId> = SideTable::new();
151 static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
152 static HOVER_NODES: SideTable<NodeId> = SideTable::new();
156 static KEY_NODES: SideTable<NodeId> = SideTable::new();
160 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
165
166 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
168 RefCell::new(HashMap::new());
169
170 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
171 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
173 RefCell::new(std::collections::HashSet::new());
174 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
180
181 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
182 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
185
186 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
188 static SPLIT_PANES: SideTable<bool> = SideTable::new();
190
191 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
195
196 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
197 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
199
200 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
205 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
208
209 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
211
212 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
214 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
215 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
216 const { std::cell::RefCell::new(None) };
217
218 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
220 RefCell::new(HashMap::new());
221 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
223 RefCell::new(HashMap::new());
224
225 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
228 const { std::cell::RefCell::new(None) };
229 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
233 const { std::cell::RefCell::new(None) };
234
235}
236
237pub fn emit(id: NodeId, ev: Event) {
239 let sink = SINK.with(|s| s.borrow().clone());
240 if let Some(sink) = sink {
241 sink(id, ev);
242 }
243}
244
245fn ptr_of(v: &NSView) -> usize {
246 (v as *const NSView).cast::<()>() as usize
247}
248
249#[derive(Clone, Copy)]
251struct ImageMode {
252 template: bool,
253 tinted: bool,
254}
255
256impl ImageMode {
257 fn renders_template(self) -> bool {
260 self.template || self.tinted
261 }
262}
263
264struct AppKitBitmap {
271 image: Retained<objc2_app_kit::NSImage>,
272 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
273 info: day_spec::BitmapInfo,
274}
275
276fn scaled_rep(
282 image: &objc2_app_kit::NSImage,
283 pixels: Size,
284 scale: f64,
285) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
286 use objc2::AllocAnyThread as _;
287 let w = (pixels.width * scale).round().max(1.0);
288 let h = (pixels.height * scale).round().max(1.0);
289 let rep = unsafe {
290 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
291 objc2_app_kit::NSBitmapImageRep::alloc(),
292 std::ptr::null_mut(),
293 w as isize,
294 h as isize,
295 8,
296 4,
297 true,
298 false,
299 objc2_app_kit::NSDeviceRGBColorSpace,
300 0,
301 0,
302 )
303 }?;
304 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
305 NSGraphicsContext::saveGraphicsState_class();
306 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
307 unsafe {
308 image.drawInRect_fromRect_operation_fraction(
309 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
310 NSRect::ZERO,
311 objc2_app_kit::NSCompositingOperation::SourceOver,
312 1.0,
313 );
314 }
315 NSGraphicsContext::restoreGraphicsState_class();
316 Some(rep)
317}
318
319fn encode_bitmap(
324 id: day_spec::BitmapId,
325 spec: &day_spec::EncodeSpec,
326) -> Result<Vec<u8>, day_spec::ImageError> {
327 use day_spec::ImageFormat as F;
328 use objc2_app_kit::NSBitmapImageFileType as T;
329 let file_type = match spec.format {
330 F::Png => T::PNG,
331 F::Jpeg => T::JPEG,
332 F::Tiff => T::TIFF,
333 F::Bmp => T::BMP,
334 F::Gif => T::GIF,
335 _ => return Err(day_spec::ImageError::Encode),
339 };
340 let held = BITMAPS.with(|m| {
341 m.borrow()
342 .get(&id.0)
343 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
344 });
345 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
346 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
347
348 let rep = match spec.fit {
351 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
352 let scale = (fit.width / info.pixels.width)
353 .min(fit.height / info.pixels.height)
354 .min(1.0);
355 if scale < 1.0 {
356 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
357 } else {
358 rep
359 }
360 }
361 _ => rep,
362 };
363
364 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
365 Some(q) => {
367 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
368 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
369 let value: &objc2::runtime::AnyObject = &number;
370 NSDictionary::from_slices::<NSString>(&[key], &[value])
371 }
372 None => NSDictionary::new(),
373 };
374 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
375 .ok_or(day_spec::ImageError::Encode)?;
376 Ok(data.to_vec())
377}
378
379fn paint_ops(ops: &[DrawOp]) {
383 for op in ops {
384 draw_op(op);
385 }
386}
387
388fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
396 use objc2_core_graphics::CGContext;
397 CGContext::save_g_state(Some(cg));
398 CGContext::translate_ctm(Some(cg), 0.0, height);
399 CGContext::scale_ctm(Some(cg), scale, -scale);
400 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
401 NSGraphicsContext::saveGraphicsState_class();
402 NSGraphicsContext::setCurrentContext(Some(&ns));
403 paint_ops(ops);
404 NSGraphicsContext::restoreGraphicsState_class();
405 CGContext::restore_g_state(Some(cg));
406}
407
408fn render_bitmap_image(
416 ops: &[DrawOp],
417 size: Size,
418 scale: f64,
419) -> Result<AppKitBitmap, day_spec::ExportError> {
420 use objc2::AllocAnyThread as _;
421 use objc2_core_graphics::{
422 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
423 };
424 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
425 let (pw, ph) = day_spec::export_pixels(size, scale);
426 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
428 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
429 let cg = unsafe {
432 CGBitmapContextCreate(
433 std::ptr::null_mut(),
434 pw as usize,
435 ph as usize,
436 8,
437 0,
438 Some(&space),
439 CGImageAlphaInfo::PremultipliedLast.0,
440 )
441 }
442 .ok_or_else(|| {
443 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
444 })?;
445 paint_flipped(&cg, ph as f64, scale, ops);
447 let cg_image = CGBitmapContextCreateImage(Some(&cg))
448 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
449 let rep = unsafe {
450 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
451 objc2_app_kit::NSBitmapImageRep::alloc(),
452 &cg_image,
453 )
454 };
455 let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
458 unsafe { rep.setSize(points) };
459 let image =
460 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
461 unsafe { image.addRepresentation(&rep) };
462 Ok(AppKitBitmap {
463 image,
464 rep: Some(rep),
465 info: day_spec::BitmapInfo {
466 pixels: Size::new(pw as f64, ph as f64),
467 scale,
468 format: None,
469 has_alpha: true,
470 },
471 })
472}
473
474fn render_pdf_bytes(
479 pages: &[day_spec::PdfPage],
480 info: &day_spec::PdfInfo,
481) -> Result<Vec<u8>, day_spec::ExportError> {
482 use objc2_core_foundation::{
483 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
484 };
485 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
486 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
487 let media =
488 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
489 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
490 let data = CFMutableData::new(None, 0)
491 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
492 let consumer = CGDataConsumer::with_cf_data(Some(&data))
493 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
494
495 let mut keys: Vec<&CFString> = Vec::new();
496 let mut values: Vec<CFRetained<CFString>> = Vec::new();
497 let (title_key, author_key) = unsafe {
499 (
500 objc2_core_graphics::kCGPDFContextTitle,
501 objc2_core_graphics::kCGPDFContextAuthor,
502 )
503 };
504 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
505 if let Some(value) = value {
506 keys.push(key);
507 values.push(CFString::from_str(value));
508 }
509 }
510 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
511 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
512
513 let first_box = media(first.size);
514 let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
517 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
518 for page in pages {
519 let page_box = media(page.size);
520 unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
522 paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
523 CGContext::end_page(Some(&pdf));
524 }
525 CGPDFContextClose(Some(&pdf));
527 drop(pdf);
528 drop(consumer);
529 Ok(data.to_vec())
530}
531
532thread_local! {
533 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
536 std::cell::RefCell::new(std::collections::HashMap::new());
537}
538
539fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
552 use objc2_app_kit::{
553 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
554 };
555 let label = |text: &str, size: f64, secondary: bool| {
556 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
557 unsafe {
558 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
559 if secondary {
560 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
561 }
562 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
563 }
564 tf
565 };
566 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
567 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
568 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
569 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
570 const STRETCH: f32 = 1.0;
573 const HOLD: f32 = 750.0;
574 let stack = NSStackView::new(mtm);
575 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
576 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
577 stack.setAlignment(NSLayoutAttribute::CenterY);
578 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
579 stack.setSpacing(6.0);
580 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
582 top: 4.0,
583 left: 0.0,
584 bottom: 4.0,
585 right: 0.0,
586 });
587 let icon = unsafe { NSImageView::new(mtm) };
588 unsafe {
589 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
590 icon.widthAnchor()
591 .constraintEqualToConstant(16.0)
592 .setActive(true);
593 icon.heightAnchor()
594 .constraintEqualToConstant(16.0)
595 .setActive(true);
596 }
597 stack.addArrangedSubview(&icon);
598 let texts = NSStackView::new(mtm);
601 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
602 texts.setAlignment(NSLayoutAttribute::Width);
603 texts.setSpacing(1.0);
604 texts.setHuggingPriority_forOrientation(
607 HOLD,
608 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
609 );
610 let title = label("", size, false);
611 let subtitle = label("", small, true);
612 for line in [&title, &subtitle] {
614 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
615 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
616 }
617 texts.addArrangedSubview(&title);
618 texts.addArrangedSubview(&subtitle);
619 stack.addArrangedSubview(&texts);
620 let detail = label("", size, true);
621 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
622 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
623 stack.addArrangedSubview(&detail);
624 let check = unsafe { NSImageView::new(mtm) };
625 unsafe {
626 check.setImage(
627 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
628 &NSString::from_str("checkmark"),
629 None,
630 )
631 .as_deref(),
632 );
633 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
634 }
635 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
636 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
637 stack.addArrangedSubview(&check);
638 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
639 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
640 dress_list_item(&view, p, mtm);
641 view
642}
643
644fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
646 use objc2_app_kit::{NSImageView, NSStackView};
647 let Some(stack) = view.downcast_ref::<NSStackView>() else {
648 return;
649 };
650 let parts = stack.arrangedSubviews();
651 if parts.len() < 4 {
652 return;
653 }
654 let icon = parts.objectAtIndex(0);
655 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
656 let image = p
657 .icon
658 .as_ref()
659 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
660 unsafe {
661 iv.setImage(image.as_deref());
662 iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
663 }
664 }
665 icon.setHidden(p.icon.is_none());
666 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
667 let lines = texts.arrangedSubviews();
668 if lines.len() == 2 {
669 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
670 tf.setStringValue(&NSString::from_str(&p.title));
671 }
672 let sub = lines.objectAtIndex(1);
673 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
674 tf.setStringValue(&NSString::from_str(&p.subtitle));
675 }
676 sub.setHidden(p.subtitle.is_empty());
677 }
678 }
679 let detail = parts.objectAtIndex(2);
680 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
681 tf.setStringValue(&NSString::from_str(&p.detail));
682 }
683 detail.setHidden(p.detail.is_empty());
684 parts.objectAtIndex(3).setHidden(!p.checked);
685 let words = [&p.title, &p.subtitle, &p.detail]
686 .into_iter()
687 .filter(|w| !w.is_empty())
688 .map(String::as_str)
689 .collect::<Vec<_>>()
690 .join(", ");
691 unsafe {
692 view.setAccessibilityElement(true);
693 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
694 view.setAccessibilitySelected(p.checked);
695 }
696}
697
698fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
704 use objc2::AllocAnyThread as _;
705 match source {
706 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
711 .or_else(|| day_spec::resource::resolve_image_file(name))
712 .and_then(|path| unsafe {
713 objc2_app_kit::NSImage::initWithContentsOfFile(
714 objc2_app_kit::NSImage::alloc(),
715 &NSString::from_str(&path.to_string_lossy()),
716 )
717 }),
718 day_spec::ImageSource::Bytes(bytes) => unsafe {
721 objc2_app_kit::NSImage::initWithData(
722 objc2_app_kit::NSImage::alloc(),
723 &NSData::with_bytes(bytes),
724 )
725 },
726 day_spec::ImageSource::Decoded(id) => {
728 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
729 }
730 }
731}
732
733fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
736 use day_spec::Role;
737 use objc2_app_kit::{
738 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
739 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
740 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
741 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
742 };
743 unsafe {
744 Some(match role {
745 Role::Button => NSAccessibilityButtonRole,
746 Role::Toggle => NSAccessibilityCheckBoxRole,
747 Role::Tab => NSAccessibilityRadioButtonRole,
750 Role::TabList => NSAccessibilityTabGroupRole,
751 Role::Slider => NSAccessibilitySliderRole,
752 Role::TextInput => NSAccessibilityTextFieldRole,
753 Role::Heading(_) => NSAccessibilityHeadingRole,
758 Role::Image => NSAccessibilityImageRole,
759 Role::Meter => NSAccessibilityLevelIndicatorRole,
760 Role::Group => NSAccessibilityGroupRole,
761 Role::Tree => NSAccessibilityOutlineRole,
764 Role::TreeItem => NSAccessibilityRowRole,
765 Role::None => return None,
766 })
767 }
768}
769
770fn day_role_from_ns(ax: &str) -> day_spec::Role {
772 use day_spec::Role;
773 match ax {
774 "AXButton" => Role::Button,
775 "AXCheckBox" => Role::Toggle,
776 "AXSlider" => Role::Slider,
777 "AXTextField" => Role::TextInput,
778 "AXStaticText" | "AXHeading" => Role::Heading(0),
781 "AXOutline" => Role::Tree,
782 "AXImage" => Role::Image,
783 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
784 "AXGroup" => Role::Group,
785 "AXRadioButton" => Role::Tab,
786 "AXTabGroup" => Role::TabList,
787 _ => Role::None,
788 }
789}
790
791struct TargetIvars {
796 node: NodeId,
797}
798
799define_class!(
800 #[unsafe(super(NSObject))]
801 #[thread_kind = MainThreadOnly]
802 #[name = "DayTarget"]
803 #[ivars = TargetIvars]
804 struct DayTarget;
805
806 unsafe impl NSObjectProtocol for DayTarget {}
807 unsafe impl NSTextFieldDelegate for DayTarget {}
808
809 unsafe impl NSTabViewDelegate for DayTarget {
814 #[unsafe(method(tabView:didSelectTabViewItem:))]
815 fn tab_view_did_select(
816 &self,
817 tab_view: &objc2_app_kit::NSTabView,
818 item: Option<&objc2_app_kit::NSTabViewItem>,
819 ) {
820 ffi_guard::contain((), || {
821 if TAB_PICK_SUPPRESS.with(|s| s.get()) {
822 return;
823 }
824 if let Some(item) = item {
825 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
826 if idx >= 0 {
827 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
828 }
829 }
830 })
831 }
832 }
833
834 impl DayTarget {
835 #[unsafe(method(action:))]
840 fn action(&self, sender: &NSControl) {
841 ffi_guard::contain((), || {
842 let node = self.ivars().node;
843 if sender.downcast_ref::<NSSwitch>().is_some() {
844 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
845 } else if sender.downcast_ref::<NSSlider>().is_some() {
846 let value = unsafe { sender.doubleValue() };
847 emit(node, Event::ValueChanged(value));
849 if slider_value_settled() {
855 emit(node, Event::ValueCommitted(value));
856 }
857 } else {
858 emit(node, Event::Pressed);
859 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
862 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
863 unsafe {
864 btn.setState(if on {
865 NSControlStateValueOn
866 } else {
867 NSControlStateValueOff
868 })
869 };
870 }
871 }
872 })
873 }
874
875 #[unsafe(method(navBack:))]
878 fn nav_back(&self, _sender: &NSControl) {
879 ffi_guard::contain((), || {
880 emit(
881 self.ivars().node,
882 Event::NavBack {
883 already_popped: false,
884 },
885 );
886 })
887 }
888 }
889
890 unsafe impl NSControlTextEditingDelegate for DayTarget {
891 #[unsafe(method(controlTextDidChange:))]
892 fn control_text_did_change(&self, notification: &NSNotification) {
893 ffi_guard::contain((), || {
894 let node = self.ivars().node;
895 if let Some(obj) = unsafe { notification.object() }
896 && let Ok(tf) = obj.downcast::<NSTextField>() {
897 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
898 }
899 })
900 }
901
902 #[unsafe(method(controlTextDidEndEditing:))]
906 fn control_text_did_end_editing(&self, notification: &NSNotification) {
907 ffi_guard::contain((), || {
908 let node = self.ivars().node;
909 let movement = unsafe { notification.userInfo() }
910 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
911 .and_then(|n| n.downcast::<NSNumber>().ok())
912 .map(|n| NSTextMovement(n.integerValue()))
913 .unwrap_or(NSTextMovement::Other);
914 if movement == NSTextMovement::Return {
915 emit(node, Event::Submitted);
916 } else {
917 emit(node, Event::FocusChanged(false));
918 }
919 })
920 }
921 }
922);
923
924impl DayTarget {
925 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
926 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
927 unsafe { msg_send![super(this), init] }
928 }
929}
930
931struct CursorIvars {
936 cursor: RefCell<Option<Retained<NSCursor>>>,
938 hidden: Cell<bool>,
940 hiding: Cell<bool>,
942}
943
944define_class!(
950 #[unsafe(super(NSObject))]
951 #[thread_kind = MainThreadOnly]
952 #[name = "DayCursorOwner"]
953 #[ivars = CursorIvars]
954 struct DayCursorOwner;
955
956 unsafe impl NSObjectProtocol for DayCursorOwner {}
957
958 impl DayCursorOwner {
959 #[unsafe(method(cursorUpdate:))]
960 fn cursor_update(&self, _event: &NSEvent) {
961 let iv = self.ivars();
962 if iv.hidden.get() {
963 if !iv.hiding.replace(true) {
964 NSCursor::hide();
965 }
966 return;
967 }
968 if let Some(c) = iv.cursor.borrow().as_ref() {
969 c.set();
970 }
971 }
972
973 #[unsafe(method(mouseExited:))]
974 fn mouse_exited(&self, _event: &NSEvent) {
975 if self.ivars().hiding.replace(false) {
976 NSCursor::unhide();
977 }
978 }
979 }
980);
981
982impl DayCursorOwner {
983 fn new(mtm: MainThreadMarker) -> Retained<Self> {
984 let this = Self::alloc(mtm).set_ivars(CursorIvars {
985 cursor: RefCell::new(None),
986 hidden: Cell::new(false),
987 hiding: Cell::new(false),
988 });
989 unsafe { msg_send![super(this), init] }
990 }
991}
992
993#[allow(deprecated)]
1001fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1002 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1003 Some(match c {
1004 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1005 Cursor::Pointer => NSCursor::pointingHandCursor(),
1006 Cursor::Text => NSCursor::IBeamCursor(),
1007 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1008 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1009 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1010 Cursor::Grabbing => NSCursor::closedHandCursor(),
1011 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1012 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1013 Cursor::Copy => NSCursor::dragCopyCursor(),
1014 Cursor::Alias => NSCursor::dragLinkCursor(),
1015 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1016 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1017 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1018 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1019 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1020 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1021 NSCursor::frameResizeCursorFromPosition_inDirections(
1022 NSCursorFrameResizePosition::TopRight,
1023 NSCursorFrameResizeDirections::All,
1024 )
1025 }
1026 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1027 NSCursor::frameResizeCursorFromPosition_inDirections(
1028 NSCursorFrameResizePosition::TopLeft,
1029 NSCursorFrameResizeDirections::All,
1030 )
1031 }
1032 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1033 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1034 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1035 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1036 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1037 Cursor::None => return None,
1038 Cursor::Native(name) => match &**name {
1039 "disappearingItem" => NSCursor::disappearingItemCursor(),
1040 "dragCopy" => NSCursor::dragCopyCursor(),
1041 "dragLink" => NSCursor::dragLinkCursor(),
1042 "contextualMenu" => NSCursor::contextualMenuCursor(),
1043 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1044 _ => return None,
1045 },
1046 })
1047}
1048
1049fn slider_value_settled() -> bool {
1056 let Some(mtm) = MainThreadMarker::new() else {
1057 return false;
1058 };
1059 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1060 return false;
1061 };
1062 matches!(
1063 unsafe { event.r#type() },
1064 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1065 )
1066}
1067
1068struct FieldIvars {
1073 node: NodeId,
1074}
1075
1076define_class!(
1077 #[unsafe(super(NSTextField))]
1078 #[thread_kind = MainThreadOnly]
1079 #[name = "DayTextField"]
1080 #[ivars = FieldIvars]
1081 struct DayTextField;
1082
1083 impl DayTextField {
1084 #[unsafe(method(becomeFirstResponder))]
1089 fn become_first_responder(&self) -> bool {
1090 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1091 if ok {
1092 field_gained_focus(self.ivars().node);
1093 }
1094 ok
1095 }
1096 }
1097);
1098
1099impl DayTextField {
1100 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1101 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1102 unsafe { msg_send![super(this), init] }
1103 }
1104}
1105
1106define_class!(
1111 #[unsafe(super(NSSecureTextField))]
1112 #[thread_kind = MainThreadOnly]
1113 #[name = "DaySecureTextField"]
1114 #[ivars = FieldIvars]
1115 struct DaySecureTextField;
1116
1117 impl DaySecureTextField {
1118 #[unsafe(method(becomeFirstResponder))]
1120 fn become_first_responder(&self) -> bool {
1121 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1122 if ok {
1123 field_gained_focus(self.ivars().node);
1124 }
1125 ok
1126 }
1127 }
1128);
1129
1130impl DaySecureTextField {
1131 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1132 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1133 unsafe { msg_send![super(this), init] }
1134 }
1135}
1136
1137thread_local! {
1138 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1141}
1142
1143fn field_gained_focus(node: NodeId) {
1146 if FIELD_SWAP.with(|s| s.get()) {
1147 return;
1148 }
1149 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1152}
1153
1154fn text_field_node(v: &NSView) -> Option<NodeId> {
1157 v.downcast_ref::<DayTextField>()
1158 .map(|f| f.ivars().node)
1159 .or_else(|| {
1160 v.downcast_ref::<DaySecureTextField>()
1161 .map(|f| f.ivars().node)
1162 })
1163}
1164
1165fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1169 let target = DayTarget::new(mtm, node);
1170 let tf: Retained<NSTextField> = if secure {
1173 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1174 } else {
1175 Retained::into_super(DayTextField::new(mtm, node))
1176 };
1177 unsafe {
1178 tf.setEditable(true);
1179 tf.setBezeled(true);
1180 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1181 }
1182 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1183 tf
1184}
1185
1186fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1190 window.firstResponder().is_some_and(|fr| {
1191 if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1192 return true;
1193 }
1194 fr.downcast::<NSText>().is_ok_and(|text| {
1195 unsafe { text.delegate() }
1196 .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1197 })
1198 })
1199}
1200
1201fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1206 unsafe extern "C" {
1207 fn dlsym(
1208 handle: *mut std::ffi::c_void,
1209 symbol: *const std::ffi::c_char,
1210 ) -> *mut std::ffi::c_void;
1211 }
1212 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1214 unsafe {
1218 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1219 if slot.is_null() {
1220 None
1221 } else {
1222 (*slot).as_ref()
1223 }
1224 }
1225}
1226
1227fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1229 if let Some(v) = table.take(old) {
1230 table.insert(new, v);
1231 }
1232}
1233
1234struct LabelIvars {
1239 node: NodeId,
1240 has_links: Cell<bool>,
1241 has_runs: Cell<bool>,
1242 selectable: Cell<bool>,
1243}
1244
1245define_class!(
1246 #[unsafe(super(NSTextField))]
1247 #[thread_kind = MainThreadOnly]
1248 #[name = "DayLabel"]
1249 #[ivars = LabelIvars]
1250 struct DayLabel;
1251
1252 impl DayLabel {
1253 #[unsafe(method_id(menuForEvent:))]
1254 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1255 ffi_guard::contain(None, || {
1256 if !self.isSelectable()
1257 && let Some(menu) = inherited_context_menu(self, event)
1258 {
1259 return menu;
1260 }
1261 unsafe { msg_send![super(self), menuForEvent: event] }
1262 })
1263 }
1264
1265 #[unsafe(method(drawRect:))]
1266 fn draw_rect(&self, dirty: NSRect) {
1267 let mut ancestor = unsafe { self.superview() };
1271 let mut selection_color = None;
1272 if !self.ivars().has_runs.get() {
1273 while let Some(view) = ancestor {
1274 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1275 if unsafe { row.isSelected() } {
1276 selection_color = Some(unsafe {
1277 if row.isEmphasized() {
1278 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1279 } else {
1280 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1281 }
1282 });
1283 }
1284 break;
1285 }
1286 ancestor = unsafe { view.superview() };
1287 }
1288 }
1289 let cell = unsafe { self.cell() }
1290 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1291 if let (Some(color), Some(cell)) = (selection_color, cell) {
1292 let original = unsafe { cell.textColor() };
1293 unsafe {
1296 cell.setTextColor(Some(&color));
1297 let _: () = msg_send![super(self), drawRect: dirty];
1298 cell.setTextColor(original.as_deref());
1299 }
1300 } else {
1301 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1302 }
1303 }
1304 }
1305
1306 unsafe impl NSObjectProtocol for DayLabel {}
1307 unsafe impl NSTextDelegate for DayLabel {}
1308
1309 unsafe impl NSTextViewDelegate for DayLabel {
1310 #[unsafe(method(textView:clickedOnLink:atIndex:))]
1311 fn clicked_on_link(
1312 &self,
1313 _tv: &NSTextView,
1314 link: &objc2::runtime::AnyObject,
1315 _index: usize,
1316 ) -> bool {
1317 ffi_guard::contain(true, || {
1318 let url: Retained<NSString> = unsafe { msg_send![link, description] };
1320 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1321 true })
1323 }
1324 }
1325);
1326
1327impl DayLabel {
1328 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1329 let this = Self::alloc(mtm).set_ivars(LabelIvars {
1330 node,
1331 has_links: Cell::new(false),
1332 has_runs: Cell::new(false),
1333 selectable: Cell::new(false),
1334 });
1335 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1336 unsafe {
1337 this.setStringValue(&NSString::from_str(text));
1338 this.setEditable(false);
1339 this.setSelectable(false);
1340 this.setBordered(false);
1341 this.setBezeled(false);
1342 this.setDrawsBackground(false);
1343 }
1344 this
1345 }
1346
1347 fn set_links(&self, has_links: bool) {
1348 self.ivars().has_links.set(has_links);
1349 unsafe {
1350 self.setSelectable(has_links || self.ivars().selectable.get());
1351 self.setAllowsEditingTextAttributes(has_links);
1352 }
1353 }
1354}
1355
1356struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1357impl Drop for PanMonitor {
1358 fn drop(&mut self) {
1359 unsafe { NSEvent::removeMonitor(&self.0) };
1360 }
1361}
1362
1363fn install_sheet_escape_monitor() {
1368 SHEET_ESCAPE_MONITOR.with(|slot| {
1369 if slot.borrow().is_some() {
1370 return;
1371 }
1372 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1373 let event = unsafe { raw.as_ref() };
1374 ffi_guard::contain(raw.as_ptr(), || {
1375 let Some(mtm) = MainThreadMarker::new() else {
1376 return raw.as_ptr();
1377 };
1378 let escape = unsafe { event.charactersIgnoringModifiers() }
1379 .is_some_and(|s| s.to_string() == "\u{1b}");
1380 let Some(window) = event.window(mtm).filter(|_| escape) else {
1381 return raw.as_ptr();
1382 };
1383 let app = NSApplication::sharedApplication(mtm);
1384 if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1385 return raw.as_ptr();
1386 }
1387 match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1388 Some(node) => {
1389 emit(
1390 node,
1391 Event::NavBack {
1392 already_popped: false,
1393 },
1394 );
1395 std::ptr::null_mut()
1396 }
1397 None => raw.as_ptr(),
1398 }
1399 })
1400 });
1401 let monitor = unsafe {
1402 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1403 objc2_app_kit::NSEventMask::KeyDown,
1404 &block,
1405 )
1406 };
1407 *slot.borrow_mut() = monitor.map(PanMonitor);
1408 });
1409}
1410
1411fn install_container_pan_monitor() {
1414 PAN_MONITOR.with(|slot| {
1415 if slot.borrow().is_some() {
1416 return;
1417 }
1418 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1419 let event = unsafe { raw.as_ref() };
1420 ffi_guard::contain(raw.as_ptr(), || {
1421 let dx = unsafe { event.scrollingDeltaX() };
1422 let dy = unsafe { event.scrollingDeltaY() };
1423 if dx.abs() <= dy.abs() {
1424 return raw.as_ptr();
1425 }
1426 let Some(mtm) = MainThreadMarker::new() else {
1427 return raw.as_ptr();
1428 };
1429 let Some(window) = event.window(mtm) else {
1430 return raw.as_ptr();
1431 };
1432 let Some(content) = window.contentView() else {
1433 return raw.as_ptr();
1434 };
1435 let point =
1436 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1437 let mut view = content.hitTest(point);
1438 while let Some(v) = view {
1439 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1440 if v.downcast_ref::<DayCanvas>().is_some() {
1441 return raw.as_ptr();
1442 }
1443 let raw_phase = unsafe { event.phase() };
1444 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1445 day_spec::DragPhase::Began
1446 } else if raw_phase.intersects(
1447 objc2_app_kit::NSEventPhase::Ended
1448 | objc2_app_kit::NSEventPhase::Cancelled,
1449 ) {
1450 day_spec::DragPhase::Ended
1451 } else {
1452 day_spec::DragPhase::Changed
1453 };
1454 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1455 emit(
1456 node,
1457 Event::Pan {
1458 phase,
1459 delta: Point::new(dx, dy),
1460 location: Point::new(p.x, p.y),
1461 },
1462 );
1463 return std::ptr::null_mut();
1464 }
1465 view = unsafe { v.superview() };
1466 }
1467 raw.as_ptr()
1468 })
1469 });
1470 *slot.borrow_mut() = unsafe {
1471 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1472 objc2_app_kit::NSEventMask::ScrollWheel,
1473 &block,
1474 )
1475 }
1476 .map(PanMonitor);
1477 });
1478}
1479
1480type Surface = (f64, f64, f64, f64, f64);
1486
1487#[derive(Default)]
1488struct FlippedIvars {
1489 surface: Cell<Option<Surface>>,
1490 section_card: Cell<Option<f64>>,
1493 pane_backdrop: Cell<bool>,
1500}
1501
1502define_class!(
1503 #[unsafe(super(NSView))]
1504 #[thread_kind = MainThreadOnly]
1505 #[name = "DayFlipped"]
1506 #[ivars = FlippedIvars]
1507 struct DayFlipped;
1508
1509 impl DayFlipped {
1510 #[unsafe(method_id(menuForEvent:))]
1511 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1512 ffi_guard::contain(None, || {
1513 inherited_context_menu(self, event)
1514 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1515 })
1516 }
1517
1518 #[unsafe(method(isFlipped))]
1519 fn is_flipped(&self) -> bool {
1520 true
1521 }
1522
1523 #[unsafe(method(acceptsFirstResponder))]
1527 fn accepts_first_responder(&self) -> bool {
1528 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1529 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1530 }
1531
1532 #[unsafe(method(mouseDown:))]
1536 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1537 if transfer::pressed(self, event) { return; }
1538 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1539 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1540 && let Some(window) = self.window()
1541 {
1542 window.makeFirstResponder(Some(self));
1543 }
1544 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1545 }
1546
1547 #[unsafe(method(becomeFirstResponder))]
1548 fn become_first_responder(&self) -> bool {
1549 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1550 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1551 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1552 }
1553 true
1554 }
1555
1556 #[unsafe(method(resignFirstResponder))]
1557 fn resign_first_responder(&self) -> bool {
1558 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1559 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1560 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1561 }
1562 true
1563 }
1564
1565 #[unsafe(method(keyDown:))]
1569 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1570 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1571 let handled = ffi_guard::contain(false, || {
1572 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1573 return false;
1574 };
1575 let Some(key) = key_name(event) else {
1576 return false;
1577 };
1578 if !day_spec::keys::handled(node) {
1579 return false;
1580 }
1581 emit(
1582 node,
1583 Event::Key(day_spec::KeyEvent {
1584 key: key.to_string(),
1585 modifiers: key_modifiers(event.modifierFlags()),
1586 }),
1587 );
1588 true
1589 });
1590 if !handled {
1591 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1592 }
1593 }
1594
1595 #[unsafe(method(rightMouseDown:))]
1599 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1600 if let Some(menu) = self.menuForEvent(event) {
1601 unsafe {
1602 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1603 };
1604 } else {
1605 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1606 }
1607 }
1608
1609 #[unsafe(method(drawRect:))]
1610 fn draw_rect(&self, _dirty: NSRect) {
1611 let paint = || {
1612 if self.ivars().pane_backdrop.get() {
1613 let bounds = self.bounds();
1614 unsafe {
1615 NSColor::windowBackgroundColor().setFill();
1618 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1619 }
1620 }
1621 if let Some(radius) = self.ivars().section_card.get() {
1622 let bounds = self.bounds();
1623 unsafe {
1624 let cls = objc2::class!(NSColor);
1627 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1628 let color: objc2::rc::Retained<NSColor> = if has {
1629 msg_send![cls, quaternarySystemFillColor]
1630 } else {
1631 msg_send![cls, controlBackgroundColor]
1632 };
1633 color.setFill();
1634 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1635 bounds, radius, radius,
1636 );
1637 path.fill();
1638 }
1639 }
1640 if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1641 let bounds = self.bounds();
1642 unsafe {
1643 NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1644 let path = if radius > 0.0 {
1645 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1646 bounds, radius, radius,
1647 )
1648 } else {
1649 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1650 };
1651 path.fill();
1652 }
1653 }
1654 };
1655 unsafe {
1664 let names = objc2_foundation::NSArray::from_slice(&[
1665 objc2_app_kit::NSAppearanceNameAqua,
1666 objc2_app_kit::NSAppearanceNameDarkAqua,
1667 ]);
1668 let standard = self
1669 .effectiveAppearance()
1670 .bestMatchFromAppearancesWithNames(&names)
1671 .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1672 match standard {
1673 Some(appearance) => {
1674 let block = block2::StackBlock::new(paint);
1675 appearance.performAsCurrentDrawingAppearance(&block);
1676 }
1677 None => paint(),
1678 }
1679 }
1680 }
1681 }
1682 unsafe impl NSObjectProtocol for DayFlipped {}
1683 unsafe impl NSDraggingSource for DayFlipped {
1684 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1685 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1686 }
1687 impl DayFlipped {
1688 #[unsafe(method(mouseDragged:))]
1689 fn transfer_dragged(&self, event: &NSEvent) {
1690 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1691 }
1692 #[unsafe(method(draggingEntered:))]
1693 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1694 #[unsafe(method(draggingUpdated:))]
1695 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1696 #[unsafe(method(performDragOperation:))]
1697 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1698 }
1699
1700);
1701
1702impl DayFlipped {
1703 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1704 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1705 unsafe { msg_send![super(this), init] }
1706 }
1707
1708 fn set_section_card(&self, corner_radius: f64) {
1714 self.ivars().section_card.set(Some(corner_radius));
1715 unsafe {
1716 let _: () = msg_send![self, setNeedsDisplay: true];
1717 }
1718 }
1719
1720 fn set_pane_backdrop(&self) {
1722 self.ivars().pane_backdrop.set(true);
1723 unsafe {
1724 let _: () = msg_send![self, setNeedsDisplay: true];
1725 }
1726 }
1727
1728 fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1729 self.ivars()
1730 .surface
1731 .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1732 unsafe {
1733 let _: () = msg_send![self, setNeedsDisplay: true];
1734 if clips || corner_radius > 0.0 {
1735 let _: () = msg_send![self, setWantsLayer: true];
1736 let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1737 if !layer.is_null() {
1738 let _: () = msg_send![layer, setCornerRadius: corner_radius];
1739 let _: () = msg_send![layer, setMasksToBounds: true];
1740 }
1741 }
1742 }
1743 }
1744}
1745
1746struct CanvasIvars;
1751
1752define_class!(
1753 #[unsafe(super(NSView))]
1754 #[thread_kind = MainThreadOnly]
1755 #[name = "DayCanvas"]
1756 #[ivars = CanvasIvars]
1757 struct DayCanvas;
1758
1759 impl DayCanvas {
1760 #[unsafe(method(isFlipped))]
1761 fn is_flipped(&self) -> bool {
1762 true
1763 }
1764
1765 #[unsafe(method_id(menuForEvent:))]
1769 fn menu_for_event(
1770 &self,
1771 event: &objc2_app_kit::NSEvent,
1772 ) -> Option<Retained<NSMenu>> {
1773 let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1774 let Some(f) = f else {
1775 return unsafe { msg_send![super(self), menuForEvent: event] };
1776 };
1777 ffi_guard::contain(None, || {
1779 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1780 let items = f(day_spec::Point::new(p.x, p.y));
1781 if items.is_empty() {
1782 return None;
1783 }
1784 Some(build_ns_menu(self.mtm(), "", &items))
1785 })
1786 }
1787
1788 #[unsafe(method(acceptsFirstResponder))]
1793 fn accepts_first_responder(&self) -> bool {
1794 true
1795 }
1796
1797 #[unsafe(method(mouseDown:))]
1801 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1802 if let Some(window) = self.window() {
1803 window.makeFirstResponder(Some(self));
1804 }
1805 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1806 }
1807
1808 #[unsafe(method(becomeFirstResponder))]
1811 fn become_first_responder(&self) -> bool {
1812 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1813 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1814 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1815 }
1816 true
1817 }
1818
1819 #[unsafe(method(resignFirstResponder))]
1820 fn resign_first_responder(&self) -> bool {
1821 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1822 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1823 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1824 }
1825 true
1826 }
1827
1828 #[unsafe(method(keyDown:))]
1832 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1833 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1834 let handled = ffi_guard::contain(false, || {
1835 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1836 return false;
1837 };
1838 let Some(key) = key_name(event) else {
1839 return false;
1840 };
1841 if !day_spec::keys::handled(node) {
1845 return false;
1846 }
1847 emit(
1848 node,
1849 Event::Key(day_spec::KeyEvent {
1850 key: key.to_string(),
1851 modifiers: key_modifiers(event.modifierFlags()),
1852 }),
1853 );
1854 true
1855 });
1856 if !handled {
1857 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1858 }
1859 }
1860
1861 #[unsafe(method(drawRect:))]
1862 fn draw_rect(&self, _dirty: NSRect) {
1863 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1864 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1865 paint_ops(&ops);
1866 }
1867
1868 #[unsafe(method(mouseEntered:))]
1871 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1872 self.report_hover(event, day_spec::DragPhase::Began);
1873 }
1874
1875 #[unsafe(method(mouseMoved:))]
1876 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1877 self.report_hover(event, day_spec::DragPhase::Changed);
1878 }
1879
1880 #[unsafe(method(mouseExited:))]
1881 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1882 self.report_hover(event, day_spec::DragPhase::Ended);
1883 }
1884
1885 #[unsafe(method(scrollWheel:))]
1886 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1887 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1888 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1889 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1890 return;
1891 };
1892 ffi_guard::contain((), || {
1893 let raw = unsafe { event.phase() };
1896 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1897 day_spec::DragPhase::Began
1898 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1899 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1900 {
1901 day_spec::DragPhase::Ended
1902 } else {
1903 day_spec::DragPhase::Changed
1904 };
1905 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1906 event.scrollingDeltaY()
1907 });
1908 let win = unsafe { event.locationInWindow() };
1909 let loc = self.convertPoint_fromView(win, None);
1910 emit(
1911 node,
1912 Event::Pan {
1913 phase,
1914 delta,
1915 location: Point::new(loc.x, loc.y),
1916 },
1917 );
1918 })
1919 }
1920 }
1921);
1922
1923impl DayCanvas {
1924 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1925 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
1926 unsafe { msg_send![super(this), init] }
1927 }
1928
1929 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
1937 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1938 let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
1939 return;
1940 };
1941 ffi_guard::contain((), || {
1942 let win = unsafe { event.locationInWindow() };
1943 let loc = self.convertPoint_fromView(win, None);
1944 let b = self.bounds();
1945 let inside = loc.x >= b.origin.x
1946 && loc.x <= b.origin.x + b.size.width
1947 && loc.y >= b.origin.y
1948 && loc.y <= b.origin.y + b.size.height;
1949 if !inside && phase != day_spec::DragPhase::Ended {
1952 return;
1953 }
1954 emit(
1955 node,
1956 Event::Hover {
1957 phase,
1958 location: Point::new(loc.x, loc.y),
1959 },
1960 );
1961 });
1962 }
1963}
1964
1965fn install_tracking_area(h: &NSView) {
1969 let opts = NSTrackingAreaOptions::MouseEnteredAndExited
1970 | NSTrackingAreaOptions::MouseMoved
1971 | NSTrackingAreaOptions::ActiveInKeyWindow
1972 | NSTrackingAreaOptions::InVisibleRect;
1973 let any: &objc2::runtime::AnyObject = h;
1974 let area = unsafe {
1975 NSTrackingArea::initWithRect_options_owner_userInfo(
1976 NSTrackingArea::alloc(),
1977 NSRect::ZERO,
1978 opts,
1979 Some(any),
1980 None,
1981 )
1982 };
1983 unsafe { h.addTrackingArea(&area) };
1984}
1985
1986struct GestureIvars {
1991 node: NodeId,
1992 kind: day_spec::GestureKind,
1993}
1994
1995define_class!(
1996 #[unsafe(super(NSObject))]
1997 #[thread_kind = MainThreadOnly]
1998 #[name = "DayGesture"]
1999 #[ivars = GestureIvars]
2000 struct DayGesture;
2001
2002 unsafe impl NSObjectProtocol for DayGesture {}
2003
2004 impl DayGesture {
2005 #[unsafe(method(fire:))]
2006 fn fire(&self, g: &NSGestureRecognizer) {
2007 ffi_guard::contain((), || {
2008 let node = self.ivars().node;
2009 let view = g.view();
2010 let loc = g.locationInView(view.as_deref());
2011 let at = Point::new(loc.x, loc.y);
2012 let phase = match g.state() {
2013 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2014 NSGestureRecognizerState::Ended
2015 | NSGestureRecognizerState::Cancelled
2016 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2017 _ => day_spec::DragPhase::Changed,
2018 };
2019 let obj: &objc2::runtime::AnyObject = g.as_ref();
2020 match self.ivars().kind {
2021 day_spec::GestureKind::Drag => {
2022 let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2023 let t = unsafe { pan.translationInView(view.as_deref()) };
2024 Point::new(t.x, t.y)
2025 } else {
2026 Point::ZERO
2027 };
2028 emit(node, Event::Drag { phase, location: at, translation });
2029 }
2030 day_spec::GestureKind::Pinch => {
2031 let scale = if let Some(m) =
2034 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2035 {
2036 1.0 + unsafe { m.magnification() }
2037 } else {
2038 1.0
2039 };
2040 emit(node, Event::Pinch { phase, scale, location: at });
2041 }
2042 _ => emit(node, Event::Tap(at)),
2043 }
2044 })
2045 }
2046 }
2047);
2048
2049impl DayGesture {
2050 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2051 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2052 unsafe { msg_send![super(this), init] }
2053 }
2054}
2055
2056struct NavHeader {
2065 bar: Retained<NSView>,
2066 title: Retained<NSTextField>,
2067 titles: Vec<String>,
2069 _target: Retained<DayTarget>,
2070}
2071
2072const NAV_HEADER_H: f64 = 34.0;
2074
2075use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2079
2080fn take_list_placement(state: &mut NavState) -> Option<f64> {
2084 if !state.list_visible || state.list_positioned {
2085 return None;
2086 }
2087 state.list_positioned = true;
2088 state.list_width
2089}
2090
2091const NAV_TABVIEW_INSET: f64 = 12.0;
2094const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2095
2096struct TabHost {
2108 view: Retained<objc2_app_kit::NSTabView>,
2109 target: Option<Retained<DayTarget>>,
2112}
2113
2114thread_local! {
2115 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2118}
2119
2120fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2124 unsafe {
2125 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2126 for (i, title) in titles.iter().enumerate().take(n) {
2127 tabs.view
2128 .tabViewItemAtIndex(i as isize)
2129 .setLabel(&NSString::from_str(title));
2130 }
2131 if n > 0 {
2132 TAB_PICK_SUPPRESS.with(|s| s.set(true));
2133 tabs.view
2134 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2135 TAB_PICK_SUPPRESS.with(|s| s.set(false));
2136 }
2137 }
2138}
2139
2140fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2144 let Some((titles, node)) = NAV_MENUS.with(|m| {
2145 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2146 let ivars = d.ivars();
2147 (
2148 ivars
2149 .items
2150 .borrow()
2151 .iter()
2152 .map(|s| s.to_string())
2153 .collect::<Vec<String>>(),
2154 ivars.node,
2155 )
2156 })
2157 }) else {
2158 return;
2159 };
2160 let mut up = unsafe { menu.superview() };
2161 while let Some(v) = up {
2162 let reached = NAV_STATE.with(|m| {
2163 let mut m = m.borrow_mut();
2164 let Some(s) = m.get_mut(&ptr_of(&v)) else {
2165 return false;
2166 };
2167 let selected = s.selected;
2168 if let Some(tabs) = s.tabs.as_mut() {
2169 if tabs.target.is_none() {
2170 let target = DayTarget::new(mtm, node);
2171 unsafe {
2172 tabs.view
2173 .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2174 };
2175 tabs.target = Some(target);
2176 }
2177 sync_tab_labels(tabs, &titles, selected);
2178 }
2179 true
2180 });
2181 if reached {
2182 return;
2183 }
2184 up = unsafe { v.superview() };
2185 }
2186}
2187
2188struct NavState {
2189 sidebar_wrap: Retained<NSView>,
2190 detail_wrap: Retained<NSView>,
2191 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2196 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2200 list_wrap: Option<Retained<NSView>>,
2206 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2207 list_width: Option<f64>,
2210 list_visible: bool,
2214 list_positioned: bool,
2220 pages: Vec<Retained<NSView>>,
2223 sidebar_page: Option<Retained<NSView>>,
2226 list_page: Option<Retained<NSView>>,
2229 positioned: bool,
2230 presentation: NavPresentation,
2234 selected: usize,
2237 tabs: Option<TabHost>,
2241 header: Option<NavHeader>,
2243 root_title: String,
2246 node: NodeId,
2248 title_strip: f64,
2252}
2253
2254fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2266 let pane = view_of(DayFlipped::new(mtm));
2267 unsafe {
2268 wrap.setFrame(pane.bounds());
2269 wrap.setAutoresizingMask(
2270 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2271 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2272 );
2273 pane.addSubview(wrap);
2274 }
2275 pane
2276}
2277
2278fn place_below_strip(wrap: &NSView, strip: f64) {
2280 let Some(pane) = (unsafe { wrap.superview() }) else {
2281 return;
2282 };
2283 let b = pane.bounds();
2284 unsafe {
2285 wrap.setFrame(NSRect::new(
2286 NSPoint::new(0.0, strip),
2287 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2288 ))
2289 };
2290}
2291
2292fn build_nav_header(
2300 mtm: MainThreadMarker,
2301 id: NodeId,
2302 detail_wrap: &NSView,
2303 root_title: &str,
2304) -> NavHeader {
2305 let bar = view_of(DayFlipped::new(mtm));
2306 let target = DayTarget::new(mtm, id);
2307 let back = unsafe {
2308 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2311 .expect("NSGoBackTemplate");
2312 let tobj: &objc2::runtime::AnyObject = target.as_ref();
2313 objc2_app_kit::NSButton::buttonWithImage_target_action(
2314 &img,
2315 Some(tobj),
2316 Some(sel!(navBack:)),
2317 mtm,
2318 )
2319 };
2320 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2321 unsafe {
2322 back.setFrame(NSRect::new(
2323 NSPoint::new(6.0, 4.0),
2324 NSSize::new(30.0, NAV_HEADER_H - 8.0),
2325 ));
2326 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2327 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2328 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2329 title.setFrame(NSRect::new(
2330 NSPoint::new(44.0, 9.0),
2331 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2332 ));
2333 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2334 bar.setFrame(NSRect::new(
2335 NSPoint::new(0.0, 0.0),
2336 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2337 ));
2338 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2339 bar.addSubview(&back);
2340 bar.addSubview(&title);
2341 bar.setHidden(true);
2342 detail_wrap.addSubview(&bar);
2343 }
2344 NavHeader {
2345 bar,
2346 title,
2347 titles: vec![root_title.to_string()],
2348 _target: target,
2349 }
2350}
2351
2352fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2356 let b = wrap.bounds();
2357 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2358 NSRect::new(
2359 NSPoint::new(0.0, top),
2360 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2361 )
2362}
2363
2364fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2371 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2372 if out.is_some() {
2373 return;
2374 }
2375 let found = NAV_MENUS.with(|m| {
2376 m.borrow()
2377 .get(&(v as *const NSView as usize))
2378 .map(|(_, d)| {
2379 let ivars = d.ivars();
2380 (
2381 ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2382 ivars.node,
2383 )
2384 })
2385 });
2386 if found.is_some() {
2387 *out = found;
2388 return;
2389 }
2390 for sub in unsafe { v.subviews() }.iter() {
2391 walk(&sub, out);
2392 }
2393 }
2394 let mut out = None;
2395 walk(page, &mut out);
2396 out
2397}
2398
2399fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2402 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2403 unsafe {
2404 item.setCanCollapse(shown);
2405 item.setCollapsed(!shown);
2406 match pres {
2407 NavPresentation::Split => {
2408 item.setAllowsFullHeightLayout(true);
2409 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2410 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2411 }
2412 NavPresentation::Rail => {
2418 item.setAllowsFullHeightLayout(true);
2419 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2420 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2421 }
2422 NavPresentation::Stack | NavPresentation::Tabs => {
2425 item.setMinimumThickness(0.0);
2426 item.setMaximumThickness(0.0);
2427 }
2428 }
2429 }
2430}
2431
2432pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2438 NAV_STATE.with(|m| {
2439 m.borrow()
2440 .values()
2441 .find(|st| {
2442 st.list_item.is_some()
2443 && st
2444 .sidebar_wrap
2445 .window()
2446 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2447 })
2448 .map(|st| unsafe { st._split_vc.splitView() })
2449 })
2450}
2451
2452fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2453 let visible = pages.len() >= 2;
2454 hdr.bar.setHidden(!visible);
2455 unsafe {
2456 hdr.title.setStringValue(&NSString::from_str(
2457 hdr.titles.last().map(String::as_str).unwrap_or(""),
2458 ));
2459 }
2460 let frame = nav_page_frame(wrap, visible);
2461 for page in pages {
2462 unsafe { page.setFrame(frame) };
2463 }
2464}
2465
2466fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2481 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2482 NAV_STATE.with(|m| {
2483 let st = m.borrow();
2484 let s = st.get(&ptr_of(host))?;
2485 Some((
2486 s.sidebar_page.clone(),
2487 s.detail_wrap.clone(),
2488 s.sidebar_wrap.clone(),
2489 s.sidebar_item.clone(),
2490 s.presentation,
2491 s.root_title.clone(),
2492 s.node,
2493 s.selected,
2494 ))
2495 })
2496 else {
2497 return;
2498 };
2499 if was == next {
2500 return;
2501 }
2502 apply_sidebar_item(&sidebar_item, next);
2503 NAV_STATE.with(|m| {
2508 if let Some(s) = m.borrow().get(&ptr_of(host)) {
2509 unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2510 }
2511 });
2512 let stacked = next == NavPresentation::Stack;
2515 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2516 if stacked && header.is_none() {
2517 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2518 }
2519 if let Some(hdr) = header.as_ref() {
2520 hdr.bar.setHidden(true);
2521 }
2522 let mut pages = NAV_STATE.with(|m| {
2528 m.borrow()
2529 .get(&ptr_of(host))
2530 .map(|s| s.pages.clone())
2531 .unwrap_or_default()
2532 });
2533 let shown_page = pages.get(sel).cloned();
2534 if let Some(page) = sidebar_page {
2537 pages.retain(|p| ptr_of(p) != ptr_of(&page));
2538 unsafe {
2539 if stacked {
2540 detail_wrap.addSubview(&page);
2541 pages.insert(0, page.clone());
2542 } else {
2543 page.setFrame(sidebar_wrap.bounds());
2544 sidebar_wrap.addSubview(&page);
2545 }
2546 }
2547 page.setHidden(false);
2549 }
2550 let shown = shown_page
2551 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2552 .unwrap_or_else(|| pages.len().saturating_sub(1));
2553 for (i, page) in pages.iter().enumerate() {
2554 page.setHidden(i != shown);
2555 }
2556 NAV_STATE.with(|m| {
2557 let mut m = m.borrow_mut();
2558 if let Some(s) = m.get_mut(&ptr_of(host)) {
2559 s.presentation = next;
2560 s.pages = pages;
2561 s.selected = shown;
2562 s.header = header;
2563 if let Some(hdr) = s.header.as_ref() {
2564 if stacked {
2566 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2567 } else {
2568 hdr.bar.setHidden(true);
2569 }
2570 }
2571 if !stacked {
2572 let frame = nav_page_frame(&s.detail_wrap, false);
2575 for page in &s.pages {
2576 unsafe { page.setFrame(frame) };
2577 }
2578 }
2579 }
2580 });
2581}
2582
2583struct CoverSheet(Retained<NSWindow>);
2592impl Drop for CoverSheet {
2593 fn drop(&mut self) {
2594 let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
2596 let raw = Retained::into_raw(self.0.clone()) as usize;
2599 dispatch2::DispatchQueue::main().exec_async(move || {
2600 ffi_guard::contain((), || unsafe {
2601 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2602 if let Some(parent) = window.sheetParent() {
2603 parent.endSheet(&window);
2604 }
2605 window.orderOut(None);
2606 window.setContentView(None);
2607 });
2608 });
2609 }
2610}
2611struct NavPageIvars {
2612 node: NodeId,
2613 top_inset: Cell<f64>,
2617 sheet: Cell<bool>,
2618 half: Cell<bool>,
2620 large: Cell<bool>,
2623}
2624
2625define_class!(
2626 #[unsafe(super(NSView))]
2627 #[thread_kind = MainThreadOnly]
2628 #[name = "DayNavPage"]
2629 #[ivars = NavPageIvars]
2630 struct DayNavPage;
2631
2632 impl DayNavPage {
2633 #[unsafe(method(isFlipped))]
2634 fn is_flipped(&self) -> bool {
2635 true
2636 }
2637
2638 #[unsafe(method(setFrameSize:))]
2639 fn set_frame_size(&self, size: NSSize) {
2640 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2641 ffi_guard::contain((), || {
2644 let inset = self.ivars().top_inset.get();
2645 emit(
2646 self.ivars().node,
2647 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2648 );
2649 })
2650 }
2651 }
2652);
2653
2654impl DayNavPage {
2655 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2656 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2657 node,
2658 top_inset: Cell::new(0.0),
2659 sheet: Cell::new(false),
2660 half: Cell::new(false),
2661 large: Cell::new(false),
2662 });
2663 unsafe { msg_send![super(this), init] }
2664 }
2665}
2666
2667struct InspectorState {
2676 content_wrap: Handle,
2677 panel_wrap: Handle,
2678 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2680 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2681}
2682
2683struct SplitState {
2691 split: Retained<objc2_app_kit::NSSplitView>,
2692 first_wrap: Handle,
2693 second_wrap: Handle,
2694 delegate: Retained<DaySplitDelegate>,
2695}
2696
2697struct SplitDelegateIvars {
2698 node: NodeId,
2699 min_pane: f64,
2700 share: Cell<f64>,
2703 positioned: Cell<bool>,
2705 suppress: Cell<bool>,
2707}
2708
2709define_class!(
2710 #[unsafe(super(NSObject))]
2711 #[thread_kind = MainThreadOnly]
2712 #[name = "DaySplitDelegate"]
2713 #[ivars = SplitDelegateIvars]
2714 struct DaySplitDelegate;
2715
2716 unsafe impl NSObjectProtocol for DaySplitDelegate {}
2717
2718 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2719 #[unsafe(method(splitViewDidResizeSubviews:))]
2720 fn did_resize(&self, notification: &NSNotification) {
2721 ffi_guard::contain((), || {
2722 let Some(obj) = notification.object() else {
2723 return;
2724 };
2725 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2726 return;
2727 };
2728 let iv = self.ivars();
2729 let usable = split_usable(&sv);
2730 if usable <= 0.0 {
2731 return;
2732 }
2733 if !iv.positioned.replace(true) {
2735 split_place(&sv, iv);
2736 return;
2737 }
2738 if iv.suppress.get() {
2739 return;
2740 }
2741 let Some(first) = sv.subviews().iter().next() else {
2742 return;
2743 };
2744 let f = first.frame();
2745 let a = if sv.isVertical() {
2746 f.size.width
2747 } else {
2748 f.size.height
2749 };
2750 let share = (a / usable).clamp(0.0, 1.0);
2751 if (share - iv.share.get()).abs() > 1e-4 {
2752 iv.share.set(share);
2753 emit(iv.node, Event::ValueChanged(share));
2754 }
2755 })
2756 }
2757
2758 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2759 fn constrain_min(
2760 &self,
2761 _sv: &objc2_app_kit::NSSplitView,
2762 proposed: f64,
2763 _index: isize,
2764 ) -> f64 {
2765 proposed.max(self.ivars().min_pane)
2766 }
2767
2768 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2769 fn constrain_max(
2770 &self,
2771 sv: &objc2_app_kit::NSSplitView,
2772 proposed: f64,
2773 _index: isize,
2774 ) -> f64 {
2775 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2776 }
2777 }
2778);
2779
2780impl DaySplitDelegate {
2781 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2782 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2783 node,
2784 min_pane,
2785 share: Cell::new(share.clamp(0.0, 1.0)),
2786 positioned: Cell::new(false),
2787 suppress: Cell::new(false),
2788 });
2789 unsafe { msg_send![super(this), init] }
2790 }
2791}
2792
2793fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2795 let frame = sv.frame();
2796 let len = if sv.isVertical() {
2797 frame.size.width
2798 } else {
2799 frame.size.height
2800 };
2801 (len - sv.dividerThickness()).max(0.0)
2802}
2803
2804fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2806 let usable = split_usable(sv);
2807 if usable <= 0.0 {
2808 return;
2809 }
2810 iv.suppress.set(true);
2811 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2812 iv.suppress.set(false);
2813}
2814
2815struct NavMenuIvars {
2822 node: NodeId,
2823 items: RefCell<Vec<Retained<NSString>>>,
2824 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2828 icon_fills: RefCell<Vec<f64>>,
2831 tints: RefCell<Vec<Option<day_spec::Color>>>,
2834 badges: RefCell<Vec<Option<Retained<NSString>>>>,
2836 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2839 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2840 badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2842 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2845 movable: RefCell<Vec<bool>>,
2847 regroup: std::cell::Cell<bool>,
2849 sorted: RefCell<Vec<bool>>,
2851 rows: RefCell<Vec<Option<usize>>>,
2855 row_objects: RefCell<Vec<Retained<NSString>>>,
2857 row_ids: RefCell<Vec<Retained<NSNumber>>>,
2862 suppress: std::cell::Cell<bool>,
2864}
2865
2866struct NavCellIvars {
2867 accessory: RefCell<Option<Retained<NSView>>>,
2870 count: RefCell<Option<Retained<NSTextField>>>,
2872 icon_fill: std::cell::Cell<f64>,
2874}
2875
2876define_class!(
2877 #[unsafe(super(objc2_app_kit::NSTableCellView))]
2882 #[thread_kind = MainThreadOnly]
2883 #[name = "DayNavCell"]
2884 #[ivars = NavCellIvars]
2885 struct DayNavCell;
2886
2887 unsafe impl NSObjectProtocol for DayNavCell {}
2888
2889 impl DayNavCell {
2890 #[unsafe(method(layout))]
2891 fn layout(&self) {
2892 let _: () = unsafe { msg_send![super(self), layout] };
2893 ffi_guard::contain((), || self.fit_accessories());
2894 }
2895 }
2896);
2897
2898impl DayNavCell {
2899 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2900 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
2901 accessory: RefCell::new(None),
2902 count: RefCell::new(None),
2903 icon_fill: std::cell::Cell::new(1.0),
2904 });
2905 unsafe { msg_send![super(this), init] }
2906 }
2907
2908 fn fit_accessories(&self) {
2913 let label = unsafe { self.textField() };
2914 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
2915 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
2916 (f.pointSize() - 2.0).max(9.0)
2917 });
2918 if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
2919 unsafe {
2920 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
2921 size,
2922 objc2_app_kit::NSFontWeightRegular,
2923 )));
2924 }
2925 self.layoutSubtreeIfNeeded();
2926 }
2927 }
2928 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
2929 let mut frame = label.frame();
2930 let end = accessory.frame().origin.x - 6.0;
2931 if frame.origin.x + frame.size.width > end {
2932 frame.size.width = (end - frame.origin.x).max(0.0);
2933 label.setFrame(frame);
2934 }
2935 }
2936 if let Some(icon) = unsafe { self.imageView() } {
2937 fit_nav_icon(&icon, self.ivars().icon_fill.get());
2938 nav_progress::fit(&icon);
2939 }
2940 }
2941}
2942
2943thread_local! {
2944 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
2946}
2947
2948fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
2957 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
2958 return;
2959 };
2960 let slot = icon.frame();
2961 let key = config.hash() as u64;
2964 let side = NAV_GLYPH_SIDES
2965 .with(|m| m.borrow().get(&key).copied())
2966 .or_else(|| {
2967 let symbol =
2968 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
2969 &NSString::from_str("gearshape"),
2970 None,
2971 )?;
2972 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
2973 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
2974 Some(side)
2975 });
2976 let Some(side) = side
2979 .filter(|s| *s > 0.0)
2980 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
2981 else {
2982 return;
2983 };
2984 if slot.size.width <= side && slot.size.height <= side {
2985 return;
2986 }
2987 icon.setFrame(NSRect::new(
2988 NSPoint::new(
2989 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
2990 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
2991 ),
2992 NSSize::new(side, side),
2993 ));
2994}
2995
2996define_class!(
2997 #[unsafe(super(objc2_app_kit::NSTableRowView))]
2998 #[thread_kind = MainThreadOnly]
2999 #[name = "DayNavRowView"]
3000 struct DayNavRowView;
3001
3002 unsafe impl NSObjectProtocol for DayNavRowView {}
3003
3004 impl DayNavRowView {
3005 #[unsafe(method(isEmphasized))]
3011 fn is_emphasized(&self) -> bool {
3012 true
3013 }
3014 }
3015);
3016
3017define_class!(
3018 #[unsafe(super(objc2_app_kit::NSOutlineView))]
3019 #[thread_kind = MainThreadOnly]
3020 #[name = "DayNavOutlineView"]
3021 struct DayNavOutlineView;
3022
3023 unsafe impl NSObjectProtocol for DayNavOutlineView {}
3024
3025 impl DayNavOutlineView {
3026 #[unsafe(method_id(menuForEvent:))]
3030 fn menu_for_event(
3031 &self,
3032 event: &objc2_app_kit::NSEvent,
3033 ) -> Option<Retained<NSMenu>> {
3034 ffi_guard::contain(None, || {
3035 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3036 let row = unsafe { self.rowAtPoint(point) };
3037 let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3038 match data {
3040 None => None,
3041 Some(d) => {
3042 let items = d
3043 .item_of_row(row)
3044 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3045 .unwrap_or_default();
3046 if items.is_empty() {
3047 None
3048 } else {
3049 Some(build_ns_menu(d.mtm(), "", &items))
3050 }
3051 }
3052 }
3053 })
3054 }
3055 }
3056);
3057
3058define_class!(
3059 #[unsafe(super(NSObject))]
3060 #[thread_kind = MainThreadOnly]
3061 #[name = "DayNavMenuData"]
3062 #[ivars = NavMenuIvars]
3063 struct DayNavMenuData;
3064
3065 unsafe impl NSObjectProtocol for DayNavMenuData {}
3066
3067 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3068 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3069 fn number_of_children(
3070 &self,
3071 _ov: &objc2_app_kit::NSOutlineView,
3072 item: Option<&objc2::runtime::AnyObject>,
3073 ) -> isize {
3074 if item.is_none() {
3075 self.ivars().row_objects.borrow().len() as isize
3076 } else {
3077 0
3078 }
3079 }
3080
3081 #[unsafe(method_id(outlineView:child:ofItem:))]
3082 fn child_of_item(
3083 &self,
3084 _ov: &objc2_app_kit::NSOutlineView,
3085 index: isize,
3086 _item: Option<&objc2::runtime::AnyObject>,
3087 ) -> Retained<objc2::runtime::AnyObject> {
3088 let ids = self.ivars().row_ids.borrow();
3089 let id = ids
3093 .get(index as usize)
3094 .cloned()
3095 .unwrap_or_else(|| NSNumber::new_isize(-1));
3096 unsafe { objc2::rc::Retained::cast_unchecked(id) }
3097 }
3098
3099 #[unsafe(method(outlineView:isItemExpandable:))]
3100 fn is_expandable(
3101 &self,
3102 _ov: &objc2_app_kit::NSOutlineView,
3103 _item: &objc2::runtime::AnyObject,
3104 ) -> bool {
3105 false
3106 }
3107
3108 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3115 fn pasteboard_writer_for_item(
3116 &self,
3117 _ov: &objc2_app_kit::NSOutlineView,
3118 item: &objc2::runtime::AnyObject,
3119 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3120 let make = || {
3121 let row = Self::outline_row(item);
3122 let index = self.item_of_row(row)?;
3123 if !self.is_movable(index) {
3124 return None;
3125 }
3126 let pbitem = objc2_app_kit::NSPasteboardItem::new();
3127 unsafe {
3128 pbitem.setString_forType(
3129 &NSString::from_str(&row.to_string()),
3130 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3131 );
3132 }
3133 Some(ProtocolObject::from_retained(pbitem))
3134 };
3135 ffi_guard::contain(None, make)
3136 }
3137
3138 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3139 fn validate_drop(
3140 &self,
3141 ov: &objc2_app_kit::NSOutlineView,
3142 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3143 item: Option<&objc2::runtime::AnyObject>,
3144 child_index: isize,
3145 ) -> objc2_app_kit::NSDragOperation {
3146 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3147 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3148 return objc2_app_kit::NSDragOperation::None;
3149 };
3150 if drop.retarget {
3152 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3153 }
3154 objc2_app_kit::NSDragOperation::Move
3155 })
3156 }
3157
3158 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3159 fn accept_drop(
3160 &self,
3161 ov: &objc2_app_kit::NSOutlineView,
3162 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3163 item: Option<&objc2::runtime::AnyObject>,
3164 child_index: isize,
3165 ) -> bool {
3166 ffi_guard::contain(false, || {
3167 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3168 return false;
3169 };
3170 match drop.moves {
3173 Some(NavMove::Reorder { from, to }) => {
3174 emit(self.ivars().node, Event::ListReorder { from, to });
3175 }
3176 Some(NavMove::Regroup {
3177 from,
3178 section,
3179 before,
3180 }) => emit(
3181 self.ivars().node,
3182 Event::NavRegroup {
3183 from,
3184 section,
3185 before,
3186 },
3187 ),
3188 None => {}
3189 }
3190 true
3191 })
3192 }
3193 }
3194
3195 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3196
3197 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3198 #[unsafe(method(outlineView:isGroupItem:))]
3201 fn is_group_item(
3202 &self,
3203 _ov: &objc2_app_kit::NSOutlineView,
3204 item: &objc2::runtime::AnyObject,
3205 ) -> bool {
3206 let row = Self::outline_row(item);
3207 row >= 0 && self.item_of_row(row).is_none()
3208 }
3209
3210 #[unsafe(method(outlineView:shouldSelectItem:))]
3211 fn should_select(
3212 &self,
3213 _ov: &objc2_app_kit::NSOutlineView,
3214 item: &objc2::runtime::AnyObject,
3215 ) -> bool {
3216 self.item_of_row(Self::outline_row(item)).is_some()
3217 }
3218
3219 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3220 fn view_for(
3221 &self,
3222 ov: &objc2_app_kit::NSOutlineView,
3223 _col: Option<&objc2_app_kit::NSTableColumn>,
3224 item: &objc2::runtime::AnyObject,
3225 ) -> Option<Retained<NSView>> {
3226 let mtm = self.mtm();
3227 let row = Self::outline_row(item);
3228 let text = self
3229 .ivars()
3230 .row_objects
3231 .borrow()
3232 .get(usize::try_from(row).unwrap_or(usize::MAX))
3233 .cloned();
3234 text.map(|text| {
3236 let text: &NSString = &text;
3237 let Some(index) = self.item_of_row(row) else {
3238 let cell = DayNavCell::new(mtm);
3241 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3242 unsafe {
3243 label.cell().inspect(|c| {
3244 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3245 });
3246 cell.addSubview(&label);
3247 cell.setTextField(Some(&label));
3248 }
3249 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3250 };
3251 let icon = self
3252 .ivars()
3253 .icons
3254 .borrow()
3255 .get(index)
3256 .and_then(|o| o.clone());
3257 let badge = self
3258 .ivars()
3259 .badges
3260 .borrow()
3261 .get(index)
3262 .and_then(|o| o.clone());
3263 let badge_icon = self
3264 .ivars()
3265 .badge_icons
3266 .borrow()
3267 .get(index)
3268 .and_then(|o| o.clone());
3269 let badge_tint = self
3270 .ivars()
3271 .badge_tints
3272 .borrow()
3273 .get(index)
3274 .copied()
3275 .flatten();
3276 let cell = DayNavCell::new(mtm);
3280 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3281 unsafe {
3282 label.cell().inspect(|c| {
3285 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3286 });
3287 cell.addSubview(&label);
3288 cell.setTextField(Some(&label));
3289 let accessory = objc2_app_kit::NSStackView::new(mtm);
3296 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3297 accessory.setOrientation(
3298 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3299 );
3300 accessory.setSpacing(4.0);
3301 let mut has_accessory = false;
3302 let trailing: Retained<NSView> = match &badge {
3303 Some(text) => {
3304 let b = NSTextField::labelWithString(text, mtm);
3305 b.setTranslatesAutoresizingMaskIntoConstraints(false);
3306 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3307 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3308 b.setFont(Some(
3309 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3310 objc2_app_kit::NSFont::smallSystemFontSize(),
3311 objc2_app_kit::NSFontWeightRegular,
3312 ),
3313 ));
3314 b.setContentCompressionResistancePriority_forOrientation(
3315 objc2_app_kit::NSLayoutPriorityRequired,
3316 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3317 );
3318 *cell.ivars().count.borrow_mut() = Some(b.clone());
3319 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3320 objc2::rc::Retained::into_super(b),
3321 ));
3322 has_accessory = true;
3323 let v: Retained<NSView> =
3324 objc2::rc::Retained::into_super(accessory.clone());
3325 v
3326 }
3327 None => objc2::rc::Retained::into_super(accessory.clone()),
3328 };
3329 if let Some(img) = &badge_icon {
3334 let iv = objc2_app_kit::NSImageView::new(mtm);
3335 iv.setImage(Some(img));
3336 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3337 if let Some(c) = badge_tint {
3338 iv.setContentTintColor(Some(&nscolor(c)));
3339 }
3340 iv.setContentCompressionResistancePriority_forOrientation(
3341 objc2_app_kit::NSLayoutPriorityRequired,
3342 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3343 );
3344 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3345 has_accessory = true;
3346 }
3347 cell.addSubview(&trailing);
3348 if has_accessory {
3349 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3350 }
3351 objc2_app_kit::NSLayoutConstraint::activateConstraints(
3352 &objc2_foundation::NSArray::from_retained_slice(&[
3353 trailing
3354 .trailingAnchor()
3355 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3356 trailing
3357 .centerYAnchor()
3358 .constraintEqualToAnchor(&cell.centerYAnchor()),
3359 ]),
3360 );
3361 }
3362 if let Some(img) = icon {
3363 let fill = self.ivars().icon_fills.borrow().get(index).copied();
3364 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3365 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3366 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3367 unsafe {
3368 iv.setImage(Some(&img));
3369 if let Some(t) = tint {
3372 iv.setContentTintColor(Some(&nscolor(t)));
3373 }
3374 iv.setImageScaling(
3375 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3376 );
3377 cell.addSubview(&iv);
3378 cell.setImageView(Some(&iv));
3379 let progress = self
3380 .ivars()
3381 .icon_progress
3382 .borrow()
3383 .iter()
3384 .find(|(row, _)| *row == index)
3385 .map(|(_, f)| *f);
3386 nav_progress::update(&iv, progress);
3387 }
3388 }
3389 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3390 })
3391 }
3392
3393 #[unsafe(method_id(outlineView:rowViewForItem:))]
3394 fn row_view_for(
3395 &self,
3396 _ov: &objc2_app_kit::NSOutlineView,
3397 _item: &objc2::runtime::AnyObject,
3398 ) -> Retained<objc2_app_kit::NSTableRowView> {
3399 let row: Retained<DayNavRowView> =
3400 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3401 objc2::rc::Retained::into_super(row)
3402 }
3403
3404 #[unsafe(method(outlineViewSelectionDidChange:))]
3405 fn selection_did_change(&self, notification: &NSNotification) {
3406 ffi_guard::contain((), || {
3407 if self.ivars().suppress.get() {
3408 return;
3409 }
3410 let Some(obj) = (unsafe { notification.object() }) else {
3411 return;
3412 };
3413 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3414 return;
3415 };
3416 let row = unsafe { ov.selectedRow() };
3417 if let Some(item) = self.item_of_row(row) {
3418 emit(self.ivars().node, Event::SelectionChanged(item as i64));
3419 }
3420 })
3421 }
3422 }
3423);
3424
3425thread_local! {
3426 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3429}
3430
3431fn nav_icon_fills(
3433 names: &[Option<String>],
3434 images: &[Option<Retained<objc2_app_kit::NSImage>>],
3435) -> Vec<f64> {
3436 names
3437 .iter()
3438 .zip(images)
3439 .map(|(name, image)| match (name, image) {
3440 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3441 *m.borrow_mut()
3442 .entry(name.clone())
3443 .or_insert_with(|| nav_icon_fill(image))
3444 }),
3445 _ => 1.0,
3446 })
3447 .collect()
3448}
3449
3450fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3455 const PX: f64 = 64.0;
3456 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3457 return 1.0;
3458 };
3459 let (w, h) = (
3460 rep.pixelsWide().max(0) as usize,
3461 rep.pixelsHigh().max(0) as usize,
3462 );
3463 let stride = rep.bytesPerRow().max(0) as usize;
3464 let data = unsafe { rep.bitmapData() };
3465 if data.is_null() || stride < w * 4 {
3466 return 1.0;
3467 }
3468 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3471 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3472 for y in 0..h {
3473 for x in 0..w {
3474 if bytes[y * stride + x * 4 + 3] > 24 {
3475 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3476 }
3477 }
3478 }
3479 if x1 <= x0 || y1 <= y0 {
3480 return 1.0;
3481 }
3482 let size = image.size();
3485 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3486 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3487 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3488}
3489
3490fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3491 icons
3493 .iter()
3494 .map(|ic| {
3495 let name = ic.as_deref()?;
3496 let path = day_spec::resource::resolve_vector_svg(name)
3498 .or_else(|| day_spec::resource::resolve_image_file(name))?;
3499 use objc2::AllocAnyThread as _;
3500 let img = unsafe {
3501 objc2_app_kit::NSImage::initWithContentsOfFile(
3502 objc2_app_kit::NSImage::alloc(),
3503 &NSString::from_str(&path.to_string_lossy()),
3504 )
3505 }?;
3506 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3508 Some(img)
3509 })
3510 .collect()
3511}
3512
3513impl DayNavMenuData {
3514 #[allow(clippy::too_many_arguments)]
3515 fn new(
3516 mtm: MainThreadMarker,
3517 node: NodeId,
3518 items: &[String],
3519 icons: &[Option<String>],
3520 badges: &[Option<String>],
3521 badge_icons: &[Option<String>],
3522 badge_tints: &[Option<day_spec::Color>],
3523 sections: &[Option<String>],
3524 tints: &[Option<day_spec::Color>],
3525 menus: &[Vec<day_spec::MenuItem>],
3526 ) -> Retained<Self> {
3527 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3528 node,
3529 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3530 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3531 icons: RefCell::new(resolve_nav_icons(icons)),
3532 tints: RefCell::new(tints.to_vec()),
3533 menus: RefCell::new(menus.to_vec()),
3534 movable: RefCell::new(Vec::new()),
3535 regroup: std::cell::Cell::new(false),
3536 sorted: RefCell::new(Vec::new()),
3537 badges: RefCell::new(ns_badges(badges)),
3538 icon_progress: RefCell::new(Vec::new()),
3539 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3540 badge_tints: RefCell::new(badge_tints.to_vec()),
3541 rows: RefCell::new(Vec::new()),
3542 row_objects: RefCell::new(Vec::new()),
3543 row_ids: RefCell::new(Vec::new()),
3544 suppress: std::cell::Cell::new(false),
3545 });
3546 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3547 this.rebuild_rows(items, sections);
3548 this
3549 }
3550
3551 #[allow(clippy::too_many_arguments)]
3555 fn set_items(
3556 &self,
3557 items: &[String],
3558 icons: &[Option<String>],
3559 badges: &[Option<String>],
3560 badge_icons: &[Option<String>],
3561 badge_tints: &[Option<day_spec::Color>],
3562 sections: &[Option<String>],
3563 tints: &[Option<day_spec::Color>],
3564 menus: &[Vec<day_spec::MenuItem>],
3565 ) {
3566 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3567 let resolved = resolve_nav_icons(icons);
3568 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3569 *self.ivars().icons.borrow_mut() = resolved;
3570 *self.ivars().tints.borrow_mut() = tints.to_vec();
3571 *self.ivars().menus.borrow_mut() = menus.to_vec();
3572 *self.ivars().badges.borrow_mut() = ns_badges(badges);
3573 self.ivars().icon_progress.borrow_mut().clear();
3574 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3575 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3576 self.rebuild_rows(items, sections);
3577 }
3578
3579 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3583 let mut rows = Vec::with_capacity(items.len());
3584 let mut objects = Vec::with_capacity(items.len());
3585 for (i, label) in items.iter().enumerate() {
3586 if let Some(Some(header)) = sections.get(i) {
3587 rows.push(None);
3588 objects.push(NSString::from_str(header));
3589 }
3590 rows.push(Some(i));
3591 objects.push(NSString::from_str(label));
3592 }
3593 let ids = (0..objects.len())
3594 .map(|i| NSNumber::new_isize(i as isize))
3595 .collect();
3596 *self.ivars().rows.borrow_mut() = rows;
3597 *self.ivars().row_objects.borrow_mut() = objects;
3598 *self.ivars().row_ids.borrow_mut() = ids;
3599 }
3600
3601 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3604 item.downcast_ref::<NSNumber>()
3605 .map(|n| n.integerValue())
3606 .unwrap_or(-1)
3607 }
3608
3609 fn item_of_row(&self, row: isize) -> Option<usize> {
3611 if row < 0 {
3612 return None;
3613 }
3614 self.ivars()
3615 .rows
3616 .borrow()
3617 .get(row as usize)
3618 .copied()
3619 .flatten()
3620 }
3621
3622 fn row_of_item(&self, item: usize) -> Option<usize> {
3624 self.ivars()
3625 .rows
3626 .borrow()
3627 .iter()
3628 .position(|r| *r == Some(item))
3629 }
3630
3631 fn is_movable(&self, item: usize) -> bool {
3632 self.ivars()
3633 .movable
3634 .borrow()
3635 .get(item)
3636 .copied()
3637 .unwrap_or(false)
3638 }
3639
3640 fn nav_drop(
3645 &self,
3646 ov: &objc2_app_kit::NSOutlineView,
3647 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3648 item: Option<&objc2::runtime::AnyObject>,
3649 child_index: isize,
3650 ) -> Option<NavDrop> {
3651 let src = unsafe { info.draggingSource() }?;
3652 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3653 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3654 {
3655 return None;
3656 }
3657 let pb = unsafe { info.draggingPasteboard() };
3658 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3659 .to_string()
3660 .parse::<usize>()
3661 .ok()?;
3662 let rows = self.ivars().rows.borrow();
3663 let proposed = match item {
3666 Some(item) => Self::outline_row(item),
3667 None => child_index,
3668 };
3669 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3670 if self.ivars().regroup.get() {
3671 regroup_gap(
3672 &rows,
3673 &self.ivars().movable.borrow(),
3674 &self.ivars().sorted.borrow(),
3675 from_row,
3676 proposed,
3677 item.is_some(),
3678 )
3679 } else {
3680 reorder_gap(
3681 &rows,
3682 &self.ivars().movable.borrow(),
3683 from_row,
3684 proposed,
3685 item.is_some(),
3686 )
3687 }
3688 }
3689}
3690
3691#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3693struct NavDrop {
3694 gap: usize,
3696 retarget: bool,
3698 moves: Option<NavMove>,
3700}
3701
3702#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3704enum NavMove {
3705 Reorder { from: usize, to: usize },
3707 Regroup {
3710 from: usize,
3711 section: usize,
3712 before: Option<usize>,
3713 },
3714}
3715
3716fn reorder_gap(
3721 rows: &[Option<usize>],
3722 movable: &[bool],
3723 from_row: usize,
3724 proposed: usize,
3725 onto: bool,
3726) -> Option<NavDrop> {
3727 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3728 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3729 let in_run = |r: usize| rows[r].is_some_and(is_movable);
3730 let first = (0..from_row)
3731 .rev()
3732 .take_while(|r| in_run(*r))
3733 .last()
3734 .unwrap_or(from_row);
3735 let last = (from_row + 1..rows.len())
3736 .take_while(|r| in_run(*r))
3737 .last()
3738 .unwrap_or(from_row);
3739 let gap = proposed.clamp(first, last + 1);
3740 let target_row = if gap > from_row { gap - 1 } else { gap };
3742 let moves = (target_row != from_row)
3743 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3744 .flatten();
3745 Some(NavDrop {
3746 gap,
3747 retarget: gap != proposed || onto,
3748 moves,
3749 })
3750}
3751
3752fn regroup_gap(
3760 rows: &[Option<usize>],
3761 movable: &[bool],
3762 sorted: &[bool],
3763 from_row: usize,
3764 proposed: usize,
3765 onto: bool,
3766) -> Option<NavDrop> {
3767 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3768 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3769 let gap = match rows.get(proposed) {
3770 Some(None) if onto => proposed + 1,
3771 _ => proposed.min(rows.len()),
3772 };
3773 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3775 Some(header) => Some(header + 1),
3776 None => rows.first().copied().flatten().map(|_| 0),
3777 };
3778 let first = section_start(gap)?;
3779 let end = (first..rows.len())
3780 .find(|r| rows[*r].is_none())
3781 .unwrap_or(rows.len());
3782 let section = rows.get(first).copied().flatten()?;
3783 if !rows[first..end]
3784 .iter()
3785 .all(|r| r.is_some_and(|i| flag(movable, i)))
3786 {
3787 return None;
3788 }
3789 let own = section_start(from_row) == Some(first);
3790 if own && flag(sorted, from) {
3791 return None;
3792 }
3793 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3794 from,
3795 section,
3796 before: rows.get(gap).copied().flatten(),
3797 });
3798 Some(NavDrop {
3799 gap,
3800 retarget: gap != proposed || onto,
3801 moves,
3802 })
3803}
3804
3805#[cfg(test)]
3806mod nav_gap_tests {
3807 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3808
3809 const ROWS: [Option<usize>; 10] = [
3811 Some(0),
3812 None,
3813 Some(1),
3814 Some(2),
3815 Some(3),
3816 None,
3817 Some(4),
3818 Some(5),
3819 None,
3820 Some(6),
3821 ];
3822 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3824 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3825 const UNSORTED: [bool; 7] = [false; 7];
3826
3827 fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3828 Some(NavMove::Regroup {
3829 from,
3830 section,
3831 before,
3832 })
3833 }
3834
3835 #[test]
3836 fn regroup_gaps_name_the_section_above_and_the_row_below() {
3837 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3838 assert_eq!(
3840 at(2, 6),
3841 Some(NavDrop {
3842 gap: 6,
3843 retarget: false,
3844 moves: regroup(1, 4, Some(4)),
3845 })
3846 );
3847 assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3849 assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3851 assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3852 }
3853
3854 #[test]
3855 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
3856 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3857 for gap in [0, 1, 9, 10] {
3859 assert_eq!(at(2, gap), None, "gap {gap}");
3860 }
3861 for gap in [2, 3, 4, 5] {
3863 assert_eq!(at(2, gap), None, "gap {gap}");
3864 }
3865 assert_eq!(at(0, 6), None);
3867 assert_eq!(at(1, 6), None);
3868 assert_eq!(at(9, 6), None);
3869 }
3870
3871 #[test]
3872 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
3873 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
3874 assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
3876 assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
3878 for gap in [2, 3] {
3880 let drop = at(2, gap).expect("offered");
3881 assert_eq!(drop.moves, None, "gap {gap}");
3882 }
3883 }
3884
3885 #[test]
3886 fn regroup_drops_onto_a_row_move_to_a_gap() {
3887 assert_eq!(
3889 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
3890 Some(NavDrop {
3891 gap: 6,
3892 retarget: true,
3893 moves: regroup(1, 4, Some(4)),
3894 })
3895 );
3896 assert_eq!(
3897 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
3898 Some(NavDrop {
3899 gap: 7,
3900 retarget: true,
3901 moves: regroup(1, 4, Some(5)),
3902 })
3903 );
3904 }
3905
3906 #[test]
3907 fn regroup_offers_nothing_above_a_leading_header() {
3908 let rows = [None, Some(0), None, Some(1)];
3910 let movable = [true, true];
3911 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
3912 assert_eq!(at(0), None);
3913 assert_eq!(at(1).map(|d| d.moves), Some(None));
3914 assert_eq!(at(2).map(|d| d.moves), Some(None));
3915 assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
3916 assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
3917 }
3918
3919 #[test]
3920 fn reorder_gaps_clamp_to_the_run() {
3921 assert_eq!(
3923 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
3924 Some(NavDrop {
3925 gap: 5,
3926 retarget: true,
3927 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
3928 })
3929 );
3930 assert_eq!(
3932 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
3933 Some(None)
3934 );
3935 assert_eq!(
3937 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
3938 Some(NavMove::Reorder { from: 2, to: 1 })
3939 );
3940 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
3941 }
3942}
3943
3944const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
3946
3947fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
3949 badges
3950 .iter()
3951 .map(|b| b.as_deref().map(NSString::from_str))
3952 .collect()
3953}
3954
3955fn post_realize_visible_rows(key: usize) {
3961 <AppKit as Platform>::post(Box::new(move || {
3962 if let Some((table, data)) = list_entry(key) {
3963 unsafe { table.layoutSubtreeIfNeeded() };
3964 let range = unsafe { table.rowsInRect(table.visibleRect()) };
3965 if let Some(source) = data.ivars().source.borrow().clone()
3966 && let Some(report) = &source.first_visible
3967 {
3968 report(range.location.min((source.len)().saturating_sub(1)));
3969 }
3970 for row in range.location..range.location + range.length {
3971 let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
3972 if let Some(cell) = cell
3976 && cell.subviews().is_empty()
3977 {
3978 let source = data.ivars().source.borrow().clone();
3979 if let Some(source) = source {
3980 (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
3981 }
3982 }
3983 }
3984 }
3985 day_core::pump_events();
3988 }));
3989}
3990
3991fn post_settle_list_drop(key: usize) {
3996 <AppKit as Platform>::post(Box::new(move || {
3997 day_core::pump_events();
4000 let Some((table, data)) = list_entry(key) else {
4001 return;
4002 };
4003 let Some(scroll) = table.enclosingScrollView() else {
4004 return;
4005 };
4006 let clip = scroll.contentView();
4007 let origin = clip.bounds().origin;
4008 let selected = table.selectedRowIndexes();
4009 let suppressed = data.ivars().suppress.replace(true);
4010 table.reloadData();
4011 table.layoutSubtreeIfNeeded();
4013 let restored = objc2_foundation::NSMutableIndexSet::new();
4014 for row in 0..table.numberOfRows().max(0) as usize {
4015 if selected.containsIndex(row) {
4016 restored.addIndex(row);
4017 }
4018 }
4019 table.selectRowIndexes_byExtendingSelection(&restored, false);
4020 let mut bounds = clip.bounds();
4021 bounds.origin = origin;
4022 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4023 scroll.reflectScrolledClipView(&clip);
4024 data.ivars().suppress.set(suppressed);
4025 post_realize_visible_rows(key);
4026 }));
4027}
4028
4029define_class!(
4038 #[unsafe(super(NSTableView))]
4039 #[thread_kind = MainThreadOnly]
4040 #[name = "DayListView"]
4041 struct DayListView;
4042 unsafe impl NSObjectProtocol for DayListView {}
4043 impl DayListView {
4044 #[unsafe(method_id(menuForEvent:))]
4047 fn menu_for_event(
4048 &self,
4049 event: &objc2_app_kit::NSEvent,
4050 ) -> Option<Retained<NSMenu>> {
4051 ffi_guard::contain(None, || {
4052 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4053 let row = unsafe { self.rowAtPoint(point) };
4054 let provider = if row >= 0 {
4055 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4056 .and_then(|cell| list_row_menu_provider(&cell))
4057 } else {
4058 None
4059 };
4060 match provider {
4061 Some((view, provider)) => {
4062 let point = view.convertPoint_fromView(
4063 unsafe { event.locationInWindow() }, None,
4064 );
4065 let items = provider(day_spec::Point::new(point.x, point.y));
4066 if items.is_empty() {
4067 None
4068 } else {
4069 Some(build_ns_menu(self.mtm(), "", &items))
4070 }
4071 }
4072 None => unsafe { msg_send![super(self), menuForEvent: event] },
4073 }
4074 })
4075 }
4076
4077 #[unsafe(method(becomeFirstResponder))]
4078 fn become_first_responder(&self) -> bool {
4079 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4080 if accepted {
4081 self.report_focus(true);
4082 }
4083 accepted
4084 }
4085
4086 #[unsafe(method(resignFirstResponder))]
4087 fn resign_first_responder(&self) -> bool {
4088 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4089 if accepted {
4090 self.report_focus(false);
4091 }
4092 accepted
4093 }
4094
4095 #[unsafe(method(keyDown:))]
4096 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4097 ffi_guard::contain((), || {
4098 let key = unsafe { event.keyCode() };
4099 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4100 let row = unsafe { self.selectedRow() };
4101 if row >= 0 && let Some(target) = unsafe { self.target() } {
4102 let _: () = unsafe { msg_send![&*target, activateRow: self] };
4103 return;
4104 }
4105 }
4106 let _: () = unsafe { msg_send![super(self), keyDown: event] };
4107 });
4108 }
4109 }
4110);
4111
4112fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4115 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4116 return Some((view.retain(), provider));
4117 }
4118 view.subviews()
4119 .iter()
4120 .find_map(|view| list_row_menu_provider(&view))
4121}
4122
4123fn inherited_context_menu(
4127 view: &NSView,
4128 event: &objc2_app_kit::NSEvent,
4129) -> Option<Option<Retained<NSMenu>>> {
4130 let mut current = Some(view.retain());
4131 while let Some(view) = current {
4132 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4133 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4134 let items = provider(day_spec::Point::new(point.x, point.y));
4135 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4136 }
4137 current = unsafe { view.superview() };
4138 }
4139 None
4140}
4141
4142impl DayListView {
4143 fn report_focus(&self, focused: bool) {
4144 ffi_guard::contain((), || {
4145 if let Some(target) = unsafe { self.target() }
4146 && let Some(data) = target.downcast_ref::<DayListData>()
4147 {
4148 emit(data.ivars().node, Event::FocusChanged(focused));
4149 }
4150 });
4151 }
4152}
4153
4154struct ListIvars {
4155 node: NodeId,
4156 source: RefCell<Option<ListSource>>,
4158 selectable: std::cell::Cell<bool>,
4159 multi: std::cell::Cell<bool>,
4161 suppress: std::cell::Cell<bool>,
4163 tokens: RefCell<Vec<u64>>,
4166 automatic: bool,
4170 sections: bool,
4174 header_estimate: std::cell::Cell<f64>,
4176 heights: RefCell<std::collections::HashMap<u64, f64>>,
4179 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4182 estimate: std::cell::Cell<f64>,
4185 heights_pending: std::cell::Cell<bool>,
4187}
4188
4189define_class!(
4190 #[unsafe(super(NSObject))]
4191 #[thread_kind = MainThreadOnly]
4192 #[name = "DayListData"]
4193 #[ivars = ListIvars]
4194 struct DayListData;
4195
4196 unsafe impl NSObjectProtocol for DayListData {}
4197 unsafe impl NSControlTextEditingDelegate for DayListData {}
4198
4199 impl DayListData {
4200 #[unsafe(method(respondsToSelector:))]
4204 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4205 if selector == objc2::sel!(tableView:heightOfRow:)
4206 && !self.ivars().automatic
4207 && !self.ivars().sections
4208 {
4209 false
4210 } else {
4211 unsafe { msg_send![super(self), respondsToSelector: selector] }
4212 }
4213 }
4214
4215 #[unsafe(method(listViewportChanged:))]
4216 fn list_viewport_changed(&self, notification: &NSNotification) {
4217 ffi_guard::contain((), || {
4218 let source = self.ivars().source.borrow().clone();
4219 if let Some(source) = source && let Some(report) = &source.first_visible
4220 && let Some(object) = notification.object()
4221 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4222 && let Some(document) = clip.documentView()
4223 && let Some(table) = document.downcast_ref::<NSTableView>() {
4224 let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4225 report(visible.location.min((source.len)().saturating_sub(1)));
4226 }
4227 });
4228 }
4229
4230 #[unsafe(method(activateRow:))]
4231 fn activate_row(&self, table: &NSTableView) {
4232 ffi_guard::contain((), || {
4233 let row = unsafe { table.selectedRow() };
4234 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4235 });
4236 }
4237 #[unsafe(method(doubleClickRow:))]
4238 fn double_click_row(&self, table: &NSTableView) {
4239 ffi_guard::contain((), || {
4240 let row = unsafe { table.clickedRow() };
4241 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4242 });
4243 }
4244 }
4245
4246 unsafe impl NSTableViewDataSource for DayListData {
4247 #[unsafe(method(numberOfRowsInTableView:))]
4248 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4249 ffi_guard::contain(0, || {
4253 self.ivars()
4254 .source
4255 .borrow()
4256 .as_ref()
4257 .map(|s| (s.len)() as isize)
4258 .unwrap_or(0)
4259 })
4260 }
4261
4262 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4268 fn pasteboard_writer_for_row(
4269 &self,
4270 _tv: &NSTableView,
4271 row: isize,
4272 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4273 let make = || {
4276 let reorderable = self
4278 .ivars()
4279 .source
4280 .borrow()
4281 .as_ref()
4282 .is_some_and(|s| s.reorder.is_some());
4283 if !reorderable || row < 0 || self.is_header(row) {
4285 return None;
4286 }
4287 let item = objc2_app_kit::NSPasteboardItem::new();
4288 unsafe {
4289 item.setString_forType(
4290 &NSString::from_str(&row.to_string()),
4291 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4292 );
4293 }
4294 Some(ProtocolObject::from_retained(item))
4295 };
4296 ffi_guard::contain(None, make)
4297 }
4298
4299 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4300 fn validate_drop(
4301 &self,
4302 tv: &NSTableView,
4303 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4304 row: isize,
4305 _op: objc2_app_kit::NSTableViewDropOperation,
4306 ) -> objc2_app_kit::NSDragOperation {
4307 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4309 let Some((from, len)) = self.drag_context(tv, info) else {
4310 return objc2_app_kit::NSDragOperation::None;
4311 };
4312 let ins = row.clamp(0, len as isize) as usize;
4315 let to = insertion_to_target(from, ins, len);
4316 let accepted = self.can_move(from, to);
4317 if accepted < 0 {
4318 return objc2_app_kit::NSDragOperation::None;
4319 }
4320 let accepted = (accepted as usize).min(len.saturating_sub(1));
4321 if accepted != to {
4322 unsafe {
4324 tv.setDropRow_dropOperation(
4325 target_to_insertion(from, accepted) as isize,
4326 objc2_app_kit::NSTableViewDropOperation::Above,
4327 );
4328 }
4329 }
4330 objc2_app_kit::NSDragOperation::Move
4331 })
4332 }
4333
4334 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4335 fn accept_drop(
4336 &self,
4337 tv: &NSTableView,
4338 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4339 row: isize,
4340 _op: objc2_app_kit::NSTableViewDropOperation,
4341 ) -> bool {
4342 let drop = || {
4344 let Some((from, len)) = self.drag_context(tv, info) else {
4345 return false;
4346 };
4347 let ins = row.clamp(0, len as isize) as usize;
4348 let to = insertion_to_target(from, ins, len);
4349 let accepted = self.can_move(from, to);
4350 if accepted < 0 {
4351 return false;
4352 }
4353 let accepted = (accepted as usize).min(len.saturating_sub(1));
4354 if accepted == from {
4355 return true; }
4357 let mv = self
4361 .ivars()
4362 .source
4363 .borrow()
4364 .as_ref()
4365 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4366 let Some(mv) = mv else { return false };
4367 mv(from, accepted);
4368 {
4371 let mut toks = self.ivars().tokens.borrow_mut();
4372 if from < toks.len() && accepted < toks.len() {
4373 let t = toks.remove(from);
4374 toks.insert(accepted, t);
4375 }
4376 }
4377 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4378 if let Some(scroll) = tv.enclosingScrollView() {
4379 post_settle_list_drop(ptr_of(&scroll));
4380 }
4381 true
4382 };
4383 ffi_guard::contain(false, drop)
4385 }
4386 }
4387
4388 unsafe impl NSTableViewDelegate for DayListData {
4389 #[unsafe(method(tableView:heightOfRow:))]
4394 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4395 ffi_guard::contain(44.0, || {
4396 let ivars = self.ivars();
4397 let header = self.is_header(row);
4398 if !header && !ivars.automatic {
4400 return unsafe { tv.rowHeight() };
4401 }
4402 let token = ivars
4403 .source
4404 .borrow()
4405 .as_ref()
4406 .filter(|s| row >= 0 && (row as usize) < (s.len)())
4407 .map(|s| (s.token_at)(row as usize));
4408 token
4409 .and_then(|t| ivars.heights.borrow().get(&t).copied())
4410 .unwrap_or_else(|| {
4411 if header {
4412 ivars.header_estimate.get()
4413 } else {
4414 ivars.estimate.get()
4415 }
4416 })
4417 })
4418 }
4419
4420 #[unsafe(method(tableView:isGroupRow:))]
4424 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4425 ffi_guard::contain(false, || self.is_header(row))
4426 }
4427
4428 #[unsafe(method(tableView:shouldSelectRow:))]
4430 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4431 ffi_guard::contain(true, || !self.is_header(row))
4432 }
4433
4434 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4435 fn view_for_row(
4436 &self,
4437 tv: &NSTableView,
4438 _col: Option<&NSTableColumn>,
4439 row: isize,
4440 ) -> Option<Retained<NSView>> {
4441 ffi_guard::contain(None, || {
4443 let mtm = self.mtm();
4444 let header = self.is_header(row);
4446 let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4447 let cell: Retained<NSView> =
4449 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4450 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4451 unsafe { v.setIdentifier(Some(&ident)) };
4452 v
4453 });
4454 let source = self.ivars().source.borrow().clone();
4458 if let Some(source) = source {
4459 let raw = Retained::as_ptr(&cell) as RawHandle;
4460 (source.bind_row)(row as usize, raw);
4461 if self.ivars().automatic || header {
4462 self.note_row_height(tv, &source, row, raw, header);
4463 }
4464 }
4465 Some(cell)
4466 })
4467 }
4468
4469 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4470 fn did_remove_row_view(
4471 &self,
4472 _tv: &NSTableView,
4473 row_view: &objc2_app_kit::NSTableRowView,
4474 _row: isize,
4475 ) {
4476 ffi_guard::contain((), || {
4482 let Some(cell) = row_view.subviews().iter().find(|sub| {
4483 sub.identifier()
4484 .map(|i| {
4485 let i = i.to_string();
4486 i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4487 })
4488 .unwrap_or(false)
4489 }) else {
4490 return;
4491 };
4492 let cell = Retained::into_raw(cell) as usize;
4495 let Some(this) = (unsafe {
4496 Retained::retain(self as *const DayListData as *mut DayListData)
4497 }) else {
4498 return;
4499 };
4500 let this = Retained::into_raw(this) as usize;
4501 <AppKit as Platform>::post(Box::new(move || {
4502 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4504 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4505 let (Some(this), Some(cell)) = (this, cell) else {
4506 return;
4507 };
4508 if cell.window().is_some() {
4509 return; }
4511 let recycle = this
4512 .ivars()
4513 .source
4514 .borrow()
4515 .as_ref()
4516 .map(|s| s.recycle.clone());
4517 if let Some(recycle) = recycle {
4518 recycle(Retained::as_ptr(&cell) as RawHandle);
4519 }
4520 }));
4521 })
4522 }
4523
4524 #[unsafe(method(tableViewSelectionDidChange:))]
4525 fn selection_did_change(&self, notification: &NSNotification) {
4526 ffi_guard::contain((), || {
4527 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4528 return;
4529 }
4530 let Some(obj) = (unsafe { notification.object() }) else {
4531 return;
4532 };
4533 let Ok(tv) = obj.downcast::<NSTableView>() else {
4534 return;
4535 };
4536 if self.ivars().multi.get() {
4537 let idx = unsafe { tv.selectedRowIndexes() };
4539 let mut rows = Vec::with_capacity(idx.count());
4540 let mut i = idx.firstIndex();
4541 while i != objc2_foundation::NSNotFound as usize {
4542 rows.push(i as i64);
4543 i = unsafe { idx.indexGreaterThanIndex(i) };
4544 }
4545 emit(self.ivars().node, Event::SelectionSet(rows));
4546 } else {
4547 let row = unsafe { tv.selectedRow() };
4548 if row >= 0 {
4549 emit(self.ivars().node, Event::SelectionChanged(row as i64));
4550 } else {
4551 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4559 }
4560 }
4561 })
4562 }
4563
4564 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4570 fn row_actions_for_row(
4571 &self,
4572 tv: &NSTableView,
4573 row: isize,
4574 edge: objc2_app_kit::NSTableRowActionEdge,
4575 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4576 ffi_guard::contain(NSArray::new(), || {
4578 let sw = self
4579 .ivars()
4580 .source
4581 .borrow()
4582 .as_ref()
4583 .and_then(|s| s.swipe.clone());
4584 let Some(sw) = sw else {
4585 return NSArray::new();
4586 };
4587 if row < 0 {
4588 return NSArray::new();
4589 }
4590 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4592 day_spec::SwipeEdge::Leading
4593 } else {
4594 day_spec::SwipeEdge::Trailing
4595 };
4596 let offer = (sw.actions_at)(row as usize, day_edge);
4597 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4598 .iter()
4599 .enumerate()
4600 .map(|(i, a)| {
4601 let style = if a.destructive {
4602 objc2_app_kit::NSTableViewRowActionStyle::Destructive
4603 } else {
4604 objc2_app_kit::NSTableViewRowActionStyle::Regular
4605 };
4606 let perform = sw.perform.clone();
4607 let table = tv.retain();
4610 let handler = block2::RcBlock::new(
4611 move |_action: std::ptr::NonNull<
4612 objc2_app_kit::NSTableViewRowAction,
4613 >,
4614 row: isize| {
4615 ffi_guard::contain((), || {
4616 perform(row as usize, day_edge, i);
4617 unsafe { table.setRowActionsVisible(false) };
4620 })
4621 },
4622 );
4623 let action =
4624 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4625 style,
4626 &NSString::from_str(&a.label),
4627 &handler,
4628 );
4629 if let Some(t) = a.tint {
4630 unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4631 }
4632 if let Some(sym) = a.symbol {
4636 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4637 &NSString::from_str(day_spec::sf_symbol_name(sym)),
4638 None,
4639 );
4640 if let Some(img) = img {
4641 unsafe { action.setImage(Some(&img)) };
4642 }
4643 }
4644 action
4645 })
4646 .collect();
4647 NSArray::from_retained_slice(&actions)
4648 })
4649 }
4650 }
4651);
4652
4653impl DayListData {
4654 fn new(
4655 mtm: MainThreadMarker,
4656 node: NodeId,
4657 selectable: bool,
4658 multi: bool,
4659 automatic: bool,
4660 sections: bool,
4661 ) -> Retained<Self> {
4662 let this = Self::alloc(mtm).set_ivars(ListIvars {
4663 node,
4664 source: RefCell::new(None),
4665 selectable: std::cell::Cell::new(selectable),
4666 multi: std::cell::Cell::new(multi),
4667 suppress: std::cell::Cell::new(false),
4668 tokens: RefCell::new(Vec::new()),
4669 automatic,
4670 sections,
4671 header_estimate: std::cell::Cell::new(28.0),
4672 heights: RefCell::new(std::collections::HashMap::new()),
4673 cell_tokens: RefCell::new(std::collections::HashMap::new()),
4674 estimate: std::cell::Cell::new(44.0),
4675 heights_pending: std::cell::Cell::new(false),
4676 });
4677 unsafe { msg_send![super(this), init] }
4678 }
4679
4680 fn note_row_height(
4684 &self,
4685 table: &NSTableView,
4686 source: &ListSource,
4687 row: isize,
4688 cell: RawHandle,
4689 header: bool,
4690 ) {
4691 let height = (source.cell_height)(cell);
4692 if height <= 0.0 || row < 0 {
4693 return;
4694 }
4695 let token = (source.token_at)(row as usize);
4696 self.ivars()
4697 .cell_tokens
4698 .borrow_mut()
4699 .insert(cell as usize, token);
4700 self.ivars().heights.borrow_mut().insert(token, height);
4701 if header {
4702 self.ivars().header_estimate.set(height);
4703 } else {
4704 self.ivars().estimate.set(height);
4705 }
4706 let drawn = unsafe { table.rectOfRow(row) }.size.height;
4707 if (drawn - height).abs() > 0.5 {
4708 self.post_row_heights(table);
4709 }
4710 }
4711
4712 fn is_header(&self, row: isize) -> bool {
4714 row >= 0
4715 && self
4716 .ivars()
4717 .source
4718 .borrow()
4719 .as_ref()
4720 .and_then(|s| s.is_header.clone())
4721 .is_some_and(|is_header| is_header(row as usize))
4722 }
4723
4724 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4727 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4728 if let Some(token) = token {
4729 self.ivars().heights.borrow_mut().insert(token, height);
4730 self.post_row_heights(table);
4731 }
4732 }
4733
4734 fn post_row_heights(&self, table: &NSTableView) {
4738 if self.ivars().heights_pending.replace(true) {
4739 return;
4740 }
4741 let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4744 return;
4745 };
4746 let this = Retained::into_raw(this) as usize;
4747 let table = Retained::into_raw(table.retain()) as usize;
4748 <AppKit as Platform>::post(Box::new(move || {
4749 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4751 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4752 let (Some(this), Some(table)) = (this, table) else {
4753 return;
4754 };
4755 this.ivars().heights_pending.set(false);
4756 ffi_guard::contain((), || this.apply_row_heights(&table));
4757 }));
4758 }
4759
4760 fn apply_row_heights(&self, table: &NSTableView) {
4761 let Some(source) = self.ivars().source.borrow().clone() else {
4762 return;
4763 };
4764 let count = unsafe { table.numberOfRows() }.max(0) as usize;
4765 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4766 let first = shown.location.saturating_sub(8);
4768 let last = (shown.location + shown.length + 8)
4769 .min(count)
4770 .min((source.len)());
4771 let changed = objc2_foundation::NSMutableIndexSet::new();
4772 {
4773 let heights = self.ivars().heights.borrow();
4774 for row in first..last {
4775 if let Some(&height) = heights.get(&(source.token_at)(row)) {
4776 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4777 if (drawn - height).abs() > 0.5 {
4778 unsafe { changed.addIndex(row) };
4779 }
4780 }
4781 }
4782 }
4783 if changed.count() == 0 {
4784 return;
4785 }
4786 NSAnimationContext::beginGrouping();
4788 NSAnimationContext::currentContext().setDuration(0.0);
4789 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4790 NSAnimationContext::endGrouping();
4791 }
4792
4793 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4805 let source = self.ivars().source.borrow();
4806 let source = source.as_ref()?;
4807 let n = (source.len)();
4808 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4809 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4810 if old.len() != n || n == 0 || old == new {
4811 return None;
4812 }
4813 let (mut so, mut sn) = (old.clone(), new.clone());
4814 so.sort_unstable();
4815 sn.sort_unstable();
4816 if so != sn {
4817 return None;
4818 }
4819 for i in 0..n {
4820 if old[i] != new[i]
4821 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4822 {
4823 return None;
4824 }
4825 }
4826 let mut work = old;
4827 let mut moves = Vec::new();
4828 for i in 0..n {
4829 if work[i] == new[i] {
4830 continue;
4831 }
4832 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4833 let t = work.remove(j);
4834 work.insert(i, t);
4835 moves.push((j, i));
4836 }
4837 Some(moves)
4838 }
4839
4840 fn drag_context(
4844 &self,
4845 tv: &NSTableView,
4846 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4847 ) -> Option<(usize, usize)> {
4848 let src = unsafe { info.draggingSource() }?;
4849 if Retained::as_ptr(&src) as *const std::ffi::c_void
4850 != tv as *const NSTableView as *const std::ffi::c_void
4851 {
4852 return None;
4853 }
4854 let pb = unsafe { info.draggingPasteboard() };
4855 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
4856 .to_string()
4857 .parse::<usize>()
4858 .ok()?;
4859 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
4860 (from < len).then_some((from, len))
4861 }
4862
4863 fn can_move(&self, from: usize, to: usize) -> i64 {
4865 self.ivars()
4866 .source
4867 .borrow()
4868 .as_ref()
4869 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
4870 .unwrap_or(-1)
4871 }
4872}
4873
4874const DAY_ROW_CELL: &str = "day.cell";
4876const DAY_HEADER_CELL: &str = "day.header";
4877
4878const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
4880
4881fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
4884 let to = if ins > from { ins - 1 } else { ins };
4885 to.min(len.saturating_sub(1))
4886}
4887
4888fn target_to_insertion(from: usize, to: usize) -> usize {
4890 if to > from { to + 1 } else { to }
4891}
4892
4893type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
4895
4896fn list_entry(key: usize) -> Option<ListEntry> {
4903 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
4904}
4905
4906struct TreeIvars {
4911 node: NodeId,
4912 source: RefCell<Option<TreeSource>>,
4914 selectable: std::cell::Cell<bool>,
4915 suppress: std::cell::Cell<bool>,
4917 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
4921}
4922
4923define_class!(
4924 #[unsafe(super(NSObject))]
4925 #[thread_kind = MainThreadOnly]
4926 #[name = "DayTreeData"]
4927 #[ivars = TreeIvars]
4928 struct DayTreeData;
4929
4930 unsafe impl NSObjectProtocol for DayTreeData {}
4931
4932 unsafe impl NSOutlineViewDataSource for DayTreeData {
4933 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4934 fn number_of_children(
4935 &self,
4936 _ov: &objc2_app_kit::NSOutlineView,
4937 item: Option<&objc2::runtime::AnyObject>,
4938 ) -> isize {
4939 ffi_guard::contain(0, || {
4943 let parent = item.and_then(Self::token_of_item);
4944 if item.is_some() && parent.is_none() {
4945 return 0; }
4947 self.ivars()
4948 .source
4949 .borrow()
4950 .as_ref()
4951 .map(|s| (s.children_len)(parent) as isize)
4952 .unwrap_or(0)
4953 })
4954 }
4955
4956 #[unsafe(method_id(outlineView:child:ofItem:))]
4957 fn child_of_item(
4958 &self,
4959 _ov: &objc2_app_kit::NSOutlineView,
4960 index: isize,
4961 item: Option<&objc2::runtime::AnyObject>,
4962 ) -> Retained<objc2::runtime::AnyObject> {
4963 let token = ffi_guard::contain(0, || {
4967 let parent = item.and_then(Self::token_of_item);
4968 self.ivars()
4969 .source
4970 .borrow()
4971 .as_ref()
4972 .map(|s| (s.child_token)(parent, index.max(0) as usize))
4973 .unwrap_or(0)
4974 });
4975 let ns = self.intern(token);
4976 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
4977 }
4978
4979 #[unsafe(method(outlineView:isItemExpandable:))]
4980 fn is_expandable(
4981 &self,
4982 _ov: &objc2_app_kit::NSOutlineView,
4983 item: &objc2::runtime::AnyObject,
4984 ) -> bool {
4985 ffi_guard::contain(false, || {
4986 let Some(token) = Self::token_of_item(item) else {
4987 return false;
4988 };
4989 self.ivars()
4990 .source
4991 .borrow()
4992 .as_ref()
4993 .map(|s| (s.expandable)(token))
4994 .unwrap_or(false)
4995 })
4996 }
4997
4998 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5004 fn pasteboard_writer_for_item(
5005 &self,
5006 _ov: &objc2_app_kit::NSOutlineView,
5007 item: &objc2::runtime::AnyObject,
5008 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5009 let make = || {
5010 let movable = self
5011 .ivars()
5012 .source
5013 .borrow()
5014 .as_ref()
5015 .is_some_and(|s| s.moves.is_some());
5016 let token = Self::token_of_item(item)?;
5017 if !movable {
5018 return None;
5019 }
5020 let pbitem = objc2_app_kit::NSPasteboardItem::new();
5021 unsafe {
5022 pbitem.setString_forType(
5023 &NSString::from_str(&token.to_string()),
5024 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5025 );
5026 }
5027 Some(ProtocolObject::from_retained(pbitem))
5028 };
5029 ffi_guard::contain(None, make)
5030 }
5031
5032 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5033 fn validate_drop(
5034 &self,
5035 ov: &objc2_app_kit::NSOutlineView,
5036 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5037 item: Option<&objc2::runtime::AnyObject>,
5038 child_index: isize,
5039 ) -> objc2_app_kit::NSDragOperation {
5040 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5041 match self.drop_proposal(ov, info, item, child_index) {
5042 Some((token, parent, index)) if self.can_move(token, parent, index) => {
5043 objc2_app_kit::NSDragOperation::Move
5044 }
5045 _ => objc2_app_kit::NSDragOperation::None,
5046 }
5047 })
5048 }
5049
5050 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5051 fn accept_drop(
5052 &self,
5053 ov: &objc2_app_kit::NSOutlineView,
5054 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5055 item: Option<&objc2::runtime::AnyObject>,
5056 child_index: isize,
5057 ) -> bool {
5058 let drop = || {
5059 let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5060 else {
5061 return false;
5062 };
5063 if !self.can_move(token, parent, index) {
5064 return false;
5065 }
5066 let mv = self
5069 .ivars()
5070 .source
5071 .borrow()
5072 .as_ref()
5073 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5074 let Some(mv) = mv else { return false };
5075 mv(token, parent, index);
5076 true
5077 };
5078 ffi_guard::contain(false, drop)
5079 }
5080 }
5081
5082 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5083
5084 unsafe impl NSOutlineViewDelegate for DayTreeData {
5085 #[unsafe(method(outlineView:isGroupItem:))]
5086 fn is_group_item(
5087 &self,
5088 _ov: &objc2_app_kit::NSOutlineView,
5089 item: &objc2::runtime::AnyObject,
5090 ) -> bool {
5091 Self::token_of_item(item).is_some_and(|t| {
5092 self.ivars()
5093 .source
5094 .borrow()
5095 .as_ref()
5096 .is_some_and(|s| (s.section_header)(t))
5097 })
5098 }
5099 #[unsafe(method(outlineView:shouldSelectItem:))]
5100 fn should_select_item(
5101 &self,
5102 _ov: &objc2_app_kit::NSOutlineView,
5103 item: &objc2::runtime::AnyObject,
5104 ) -> bool {
5105 Self::token_of_item(item).is_some_and(|t| {
5106 self.ivars()
5107 .source
5108 .borrow()
5109 .as_ref()
5110 .is_some_and(|s| !(s.section_header)(t))
5111 })
5112 }
5113
5114 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5115 fn view_for_item(
5116 &self,
5117 ov: &objc2_app_kit::NSOutlineView,
5118 _col: Option<&NSTableColumn>,
5119 item: &objc2::runtime::AnyObject,
5120 ) -> Option<Retained<NSView>> {
5121 ffi_guard::contain(None, || {
5123 let mtm = self.mtm();
5124 let token = Self::token_of_item(item)?;
5125 let ident = NSString::from_str("day.tree.cell");
5126 let cell: Retained<NSView> =
5130 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5131 let v: Retained<NSView> =
5132 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5133 unsafe { v.setIdentifier(Some(&ident)) };
5134 v
5135 });
5136 if let Some(source) = self.ivars().source.borrow().as_ref() {
5137 let raw = Retained::as_ptr(&cell) as RawHandle;
5138 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5139 unsafe {
5140 cell.setTextField(None);
5141 }
5142 }
5143 (source.bind_row)(token, raw);
5144 if (source.section_header)(token) {
5147 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5148 for child in unsafe { view.subviews() }.iter() {
5149 if let Ok(label) = child.clone().downcast::<NSTextField>() {
5150 return Some(label);
5151 }
5152 if let Some(label) = label_in(&child) {
5153 return Some(label);
5154 }
5155 }
5156 None
5157 }
5158 if let Some(label) = label_in(&cell) {
5159 let cell = cell.downcast_ref::<DayTreeCell>()?;
5160 unsafe {
5161 cell.setTextField(Some(&label));
5162 }
5163 }
5164 }
5165 }
5166 Some(cell)
5167 })
5168 }
5169
5170 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5171 fn type_select_string(
5172 &self,
5173 _ov: &objc2_app_kit::NSOutlineView,
5174 _col: Option<&NSTableColumn>,
5175 item: &objc2::runtime::AnyObject,
5176 ) -> Option<Retained<NSString>> {
5177 ffi_guard::contain(None, || {
5178 let token = Self::token_of_item(item)?;
5179 let text = self
5180 .ivars()
5181 .source
5182 .borrow()
5183 .as_ref()
5184 .map(|s| (s.type_select_text)(token))
5185 .unwrap_or_default();
5186 (!text.is_empty()).then(|| NSString::from_str(&text))
5188 })
5189 }
5190
5191 #[unsafe(method_id(outlineView:rowViewForItem:))]
5192 fn row_view_for_item(
5193 &self,
5194 ov: &objc2_app_kit::NSOutlineView,
5195 _item: &objc2::runtime::AnyObject,
5196 ) -> Retained<objc2_app_kit::NSTableRowView> {
5197 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5198 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5200 } else {
5201 let rv: Retained<DayTreeRowView> =
5203 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5204 Retained::into_super(rv)
5205 }
5206 }
5207
5208 #[unsafe(method(outlineViewSelectionDidChange:))]
5209 fn selection_did_change(&self, notification: &NSNotification) {
5210 ffi_guard::contain((), || {
5211 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5212 return;
5213 }
5214 let Some(obj) = (unsafe { notification.object() }) else {
5215 return;
5216 };
5217 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5218 return;
5219 };
5220 let idx = unsafe { ov.selectedRowIndexes() };
5222 let mut tokens = Vec::with_capacity(idx.count());
5223 let mut i = idx.firstIndex();
5224 while i != objc2_foundation::NSNotFound as usize {
5225 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5226 && let Some(tok) = Self::token_of_item(&item)
5227 {
5228 tokens.push(tok);
5229 }
5230 i = unsafe { idx.indexGreaterThanIndex(i) };
5231 }
5232 emit(self.ivars().node, Event::TreeSelection(tokens));
5233 })
5234 }
5235
5236 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5237 fn did_remove_row_view(
5238 &self,
5239 ov: &objc2_app_kit::NSOutlineView,
5240 row_view: &objc2_app_kit::NSTableRowView,
5241 _row: isize,
5242 ) {
5243 ffi_guard::contain((), || {
5249 let mut cell_ptr: Option<usize> = None;
5250 for sub in row_view.subviews().iter() {
5251 let is_cell = sub
5252 .identifier()
5253 .map(|i| i.to_string() == "day.tree.cell")
5254 .unwrap_or(false);
5255 if is_cell {
5256 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5257 }
5258 }
5259 let Some(cell) = cell_ptr else { return };
5260 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5261 return;
5262 };
5263 let key = Retained::as_ptr(&scroll) as usize;
5264 let retained =
5268 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5269 as usize;
5270 <AppKit as Platform>::post(Box::new(move || {
5271 let cell_view: Retained<NSView> =
5274 match unsafe { Retained::from_raw(retained as *mut NSView) } {
5275 Some(v) => v,
5276 None => return,
5277 };
5278 let recycle = tree_entry(key).and_then(|(_, data)| {
5279 data.ivars()
5280 .source
5281 .borrow()
5282 .as_ref()
5283 .map(|s| s.recycle.clone())
5284 });
5285 let Some(recycle) = recycle else { return };
5286 if cell_view.window().is_some() {
5287 return; }
5289 recycle(cell as RawHandle);
5290 }));
5291 })
5292 }
5293
5294 #[unsafe(method(outlineViewItemDidExpand:))]
5295 fn item_did_expand(&self, notification: &NSNotification) {
5296 self.report_disclosure(notification, true);
5297 }
5298
5299 #[unsafe(method(outlineViewItemDidCollapse:))]
5300 fn item_did_collapse(&self, notification: &NSNotification) {
5301 self.report_disclosure(notification, false);
5302 }
5303 }
5304);
5305
5306impl DayTreeData {
5307 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5308 let this = Self::alloc(mtm).set_ivars(TreeIvars {
5309 node,
5310 source: RefCell::new(None),
5311 selectable: std::cell::Cell::new(selectable),
5312 suppress: std::cell::Cell::new(false),
5313 items: RefCell::new(HashMap::new()),
5314 });
5315 unsafe { msg_send![super(this), init] }
5316 }
5317
5318 fn intern(&self, token: u64) -> Retained<NSNumber> {
5320 self.ivars()
5321 .items
5322 .borrow_mut()
5323 .entry(token)
5324 .or_insert_with(|| NSNumber::new_u64(token))
5325 .clone()
5326 }
5327
5328 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5329 item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5330 }
5331
5332 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5335 ffi_guard::contain((), || {
5336 if self.ivars().suppress.get() {
5337 return;
5338 }
5339 let token = unsafe { notification.userInfo() }
5340 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5341 .and_then(|item| Self::token_of_item(&item));
5342 if let Some(token) = token {
5343 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5344 }
5345 })
5346 }
5347
5348 fn drop_proposal(
5352 &self,
5353 ov: &objc2_app_kit::NSOutlineView,
5354 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5355 item: Option<&objc2::runtime::AnyObject>,
5356 child_index: isize,
5357 ) -> Option<(u64, Option<u64>, Option<usize>)> {
5358 let src = unsafe { info.draggingSource() }?;
5359 if Retained::as_ptr(&src) as *const std::ffi::c_void
5360 != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5361 {
5362 return None;
5363 }
5364 let pb = unsafe { info.draggingPasteboard() };
5365 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5366 .to_string()
5367 .parse::<u64>()
5368 .ok()?;
5369 let parent = match item {
5370 Some(i) => Some(Self::token_of_item(i)?), None => None,
5372 };
5373 let index = (child_index >= 0).then_some(child_index as usize);
5374 Some((token, parent, index))
5375 }
5376
5377 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5379 self.ivars()
5380 .source
5381 .borrow()
5382 .as_ref()
5383 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5384 .map(|v| v == MoveVerdict::Allow)
5385 .unwrap_or(false)
5386 }
5387}
5388
5389define_class!(
5395 #[unsafe(super(objc2_app_kit::NSOutlineView))]
5396 #[thread_kind = MainThreadOnly]
5397 #[name = "DayOutlineView"]
5398 struct DayOutlineView;
5399
5400 impl DayOutlineView {
5401 #[unsafe(method(layout))]
5402 fn layout(&self) {
5403 sync_tree_width(self);
5404 let _: () = unsafe { msg_send![super(self), layout] };
5405 }
5406
5407 #[unsafe(method_id(menuForEvent:))]
5410 fn menu_for_event(
5411 &self,
5412 event: &objc2_app_kit::NSEvent,
5413 ) -> Option<Retained<NSMenu>> {
5414 ffi_guard::contain(None, || {
5415 let scroll = unsafe { self.enclosingScrollView() }?;
5416 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5417 let row_menu = data
5418 .ivars()
5419 .source
5420 .borrow()
5421 .as_ref()
5422 .and_then(|s| s.row_menu.clone())?;
5423 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5424 let row = unsafe { self.rowAtPoint(p) };
5425 if row < 0 {
5426 return None;
5427 }
5428 let token =
5429 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5430 let items = row_menu(token);
5431 if items.is_empty() {
5432 return None;
5433 }
5434 Some(build_ns_menu(self.mtm(), "", &items))
5435 })
5436 }
5437 }
5438);
5439
5440define_class!(
5447 #[unsafe(super(objc2_app_kit::NSTableRowView))]
5448 #[thread_kind = MainThreadOnly]
5449 #[name = "DayTreeRowView"]
5450 struct DayTreeRowView;
5451
5452 impl DayTreeRowView {
5453 #[unsafe(method(drawSelectionInRect:))]
5454 fn draw_selection_in_rect(&self, _dirty: NSRect) {
5455 if !unsafe { self.isSelected() } {
5456 return;
5457 }
5458 let color = if unsafe { self.isEmphasized() } {
5459 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5460 } else {
5461 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5462 };
5463 let b = self.bounds();
5464 let pill = NSRect::new(
5465 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5466 NSSize::new(
5467 (b.size.width - 10.0).max(0.0),
5468 (b.size.height - 2.0).max(0.0),
5469 ),
5470 );
5471 unsafe {
5472 color.setFill();
5473 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5474 pill, 5.0, 5.0,
5475 )
5476 .fill();
5477 }
5478 }
5479 }
5480);
5481
5482define_class!(
5486 #[unsafe(super(objc2_app_kit::NSTableCellView))]
5487 #[thread_kind = MainThreadOnly]
5488 #[name = "DayTreeCell"]
5489 struct DayTreeCell;
5490
5491 impl DayTreeCell {
5492 #[unsafe(method(isFlipped))]
5493 fn is_flipped(&self) -> bool {
5494 true
5495 }
5496
5497 #[unsafe(method(layout))]
5498 fn layout(&self) {
5499 let _: () = unsafe { msg_send![super(self), layout] };
5500 ffi_guard::contain((), || {
5501 let width = self.bounds().size.width;
5502 if width <= 0.0 {
5503 return;
5504 }
5505 let mut cur = unsafe { self.superview() };
5509 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5510 while let Some(v) = cur {
5511 cur = unsafe { v.superview() };
5512 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5513 outline = Some(ov);
5514 break;
5515 }
5516 }
5517 let Some(ov) = outline else { return };
5518 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5519 return;
5520 };
5521 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5522 .and_then(|(_, data)| {
5523 data.ivars()
5524 .source
5525 .borrow()
5526 .as_ref()
5527 .map(|s| s.layout_cell_size.clone())
5528 });
5529 if let Some(f) = f {
5530 f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5531 }
5532 })
5533 }
5534 }
5535);
5536
5537impl DayTreeCell {
5538 fn new(mtm: MainThreadMarker) -> Retained<Self> {
5539 unsafe { msg_send![Self::alloc(mtm), init] }
5540 }
5541}
5542
5543const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5545
5546type TreeEntry = (
5548 Retained<objc2_app_kit::NSOutlineView>,
5549 Retained<DayTreeData>,
5550);
5551
5552fn tree_entry(key: usize) -> Option<TreeEntry> {
5555 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5556}
5557
5558fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5562 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5563 return;
5564 };
5565 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5566 let f = outline.frame();
5567 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5568 unsafe {
5569 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5570 outline.sizeLastColumnToFit();
5571 }
5572 }
5573}
5574
5575fn post_realize_visible_tree_rows(key: usize) {
5578 <AppKit as Platform>::post(Box::new(move || {
5579 if let Some((outline, _)) = tree_entry(key) {
5580 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5581 for row in range.location..range.location + range.length {
5582 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5583 }
5584 }
5585 day_core::pump_events();
5586 }));
5587}
5588
5589type NavMenuEntry = (
5591 Retained<objc2_app_kit::NSOutlineView>,
5592 Retained<DayNavMenuData>,
5593);
5594
5595fn ns_rect(r: day_spec::Rect) -> NSRect {
5596 NSRect::new(
5597 NSPoint::new(r.origin.x, r.origin.y),
5598 NSSize::new(r.size.width, r.size.height),
5599 )
5600}
5601
5602fn draw_op(op: &DrawOp) {
5603 unsafe {
5604 match op {
5605 DrawOp::Stamp(st) => {
5611 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5612 for p in &st.at {
5613 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5614 unsafe { batch.appendBezierPath(©) };
5615 }
5616 }
5617 let color = match &st.paint {
5618 day_spec::Paint::Solid(c) => *c,
5619 _ => day_spec::Color::WHITE,
5622 };
5623 match &st.stroke {
5624 None => {
5625 nscolor(color).setFill();
5626 unsafe { batch.fill() };
5627 }
5628 Some(style) => {
5629 nscolor(color).setStroke();
5630 apply_stroke_style(&batch, style);
5631 unsafe { batch.stroke() };
5632 }
5633 }
5634 }
5635 DrawOp::Fill(shape, paint) => match paint {
5636 day_spec::Paint::Solid(color) => {
5637 nscolor(*color).setFill();
5638 if let Some(p) = bezier(shape) {
5639 p.fill();
5640 }
5641 }
5642 day_spec::Paint::Linear(g) => {
5643 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5646 let b = shape.bounds();
5647 let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5648 NSGraphicsContext::saveGraphicsState_class();
5649 p.addClip();
5650 grad.drawFromPoint_toPoint_options(
5651 NSPoint::new(s.x, s.y),
5652 NSPoint::new(e.x, e.y),
5653 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5654 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5655 );
5656 NSGraphicsContext::restoreGraphicsState_class();
5657 }
5658 }
5659 day_spec::Paint::Radial(g) => {
5660 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5663 let b = shape.bounds();
5664 NSGraphicsContext::saveGraphicsState_class();
5665 p.addClip();
5666 concat_unit_to_bounds(b);
5667 let c = NSPoint::new(g.center.x, g.center.y);
5668 grad.drawFromCenter_radius_toCenter_radius_options(
5669 c,
5670 0.0,
5671 c,
5672 g.radius,
5673 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5674 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5675 );
5676 NSGraphicsContext::restoreGraphicsState_class();
5677 }
5678 }
5679 },
5680 DrawOp::Stroke(shape, paint, style) => {
5681 if let Some(p) = bezier(shape) {
5682 apply_stroke_style(&p, style);
5683 match paint {
5684 day_spec::Paint::Solid(color) => {
5685 nscolor(*color).setStroke();
5686 p.stroke();
5687 }
5688 _ => {
5694 let Some(ctx) = NSGraphicsContext::currentContext() else {
5695 return;
5696 };
5697 let cg = ctx.CGContext();
5698 NSGraphicsContext::saveGraphicsState_class();
5699 objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5700 objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5701 &cg,
5702 ));
5703 objc2_core_graphics::CGContext::clip(Some(&cg));
5704 draw_gradient_in(paint, shape.bounds());
5705 NSGraphicsContext::restoreGraphicsState_class();
5706 }
5707 }
5708 }
5709 }
5710 DrawOp::Clip(shape) => {
5711 if let Some(p) = bezier(shape) {
5713 p.addClip();
5714 }
5715 }
5716 DrawOp::Text {
5717 text,
5718 at,
5719 size,
5720 color,
5721 anchor,
5722 font,
5723 } => {
5724 let font = canvas_nsfont(*size, font);
5725 let attrs = canvas_text_attrs(&font, *color);
5726 let ns = NSString::from_str(text);
5727 let mut origin = NSPoint::new(at.x, at.y);
5728 if *anchor != day_spec::TextAnchor::LEADING {
5733 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5734 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5735 origin.x += dx;
5736 origin.y += dy;
5737 }
5738 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5739 }
5740 DrawOp::Image {
5744 image,
5745 rect,
5746 opacity,
5747 } => {
5748 let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5749 if let Some(img) = img {
5750 let dest = NSRect::new(
5751 NSPoint::new(rect.origin.x, rect.origin.y),
5752 NSSize::new(rect.size.width, rect.size.height),
5753 );
5754 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5758 dest,
5759 NSRect::ZERO,
5760 objc2_app_kit::NSCompositingOperation::SourceOver,
5761 *opacity,
5762 true,
5763 None,
5764 );
5765 }
5766 }
5767 DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5768 DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5769 DrawOp::Concat(m) => {
5770 let t = NSAffineTransform::new();
5771 t.setTransformStruct(NSAffineTransformStruct {
5772 m11: m.a,
5773 m12: m.b,
5774 m21: m.c,
5775 m22: m.d,
5776 tX: m.tx,
5777 tY: m.ty,
5778 });
5779 t.concat();
5780 }
5781 }
5782 }
5783}
5784
5785fn nsgradient(
5787 stops: &[(f64, day_spec::Color)],
5788) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5789 if stops.is_empty() {
5790 return None;
5791 }
5792 let colors = objc2_foundation::NSArray::from_retained_slice(
5793 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5794 );
5795 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5796 unsafe {
5797 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5798 objc2_app_kit::NSGradient::alloc(),
5799 &colors,
5800 locations.as_ptr(),
5801 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5802 )
5803 }
5804}
5805
5806fn concat_unit_to_bounds(b: day_spec::Rect) {
5809 let t = NSAffineTransform::new();
5810 t.setTransformStruct(NSAffineTransformStruct {
5811 m11: b.size.width,
5812 m12: 0.0,
5813 m21: 0.0,
5814 m22: b.size.height,
5815 tX: b.origin.x,
5816 tY: b.origin.y,
5817 });
5818 unsafe { t.concat() };
5819}
5820
5821fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5827 use day_spec::{LineCap, LineJoin};
5828 unsafe {
5829 p.setLineWidth(style.width);
5830 p.setLineCapStyle(match style.cap {
5831 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5832 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5833 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5834 });
5835 if style.is_plain() {
5836 return;
5837 }
5838 p.setLineJoinStyle(match style.join {
5839 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5840 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5841 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5842 });
5843 p.setMiterLimit(style.miter_limit);
5844 if !style.dash.is_empty() {
5845 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5846 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5847 }
5848 }
5849}
5850
5851fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
5855 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5856 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
5857 match paint {
5858 day_spec::Paint::Linear(g) => {
5859 if let Some(grad) = nsgradient(&g.stops) {
5860 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
5861 unsafe {
5862 grad.drawFromPoint_toPoint_options(
5863 NSPoint::new(s.x, s.y),
5864 NSPoint::new(e.x, e.y),
5865 opts,
5866 )
5867 };
5868 }
5869 }
5870 day_spec::Paint::Radial(g) => {
5871 if let Some(grad) = nsgradient(&g.stops) {
5872 NSGraphicsContext::saveGraphicsState_class();
5873 concat_unit_to_bounds(bounds);
5874 let c = NSPoint::new(g.center.x, g.center.y);
5875 unsafe {
5876 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
5877 };
5878 NSGraphicsContext::restoreGraphicsState_class();
5879 }
5880 }
5881 day_spec::Paint::Solid(_) => {}
5882 }
5883}
5884
5885fn apply_button_content(
5886 btn: &NSButton,
5887 title: &str,
5888 icon: Option<&day_spec::Icon>,
5889 icon_only: bool,
5890) {
5891 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
5892 if let Some(image) = &image {
5893 let size = image.size();
5894 let longest = size.width.max(size.height);
5895 if longest > 0.0 {
5896 image.setSize(objc2_foundation::NSSize::new(
5897 size.width * 20.0 / longest,
5898 size.height * 20.0 / longest,
5899 ));
5900 }
5901 }
5902 let style = BUTTON_STYLES
5903 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
5904 .unwrap_or_default();
5905 BUTTON_IMAGES.with(|images| {
5906 images.remove(ptr_of(btn));
5907 if let Some(image) = &image {
5908 images.insert(ptr_of(btn), image.clone());
5909 }
5910 });
5911 set_button_title(btn, title, style);
5912 unsafe {
5915 btn.setImagePosition(if image.is_none() {
5916 objc2_app_kit::NSCellImagePosition::NoImage
5917 } else if icon_only {
5918 objc2_app_kit::NSCellImagePosition::ImageOnly
5919 } else {
5920 objc2_app_kit::NSCellImagePosition::ImageLeading
5921 });
5922 }
5923 set_button_image(btn, style);
5924 unsafe {
5925 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
5928 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
5929 }
5930 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
5931 btn.setToolTip(tooltip.as_deref());
5932 }
5933}
5934
5935fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
5939 use day_spec::props::ButtonStyleSpec as S;
5940 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
5941 let image = image.map(|source| {
5942 let S::Tinted(fill) = style else {
5943 return source;
5944 };
5945 let size = source.size();
5946 let ink = nscolor(S::on_tint(fill));
5947 let draw = block2::RcBlock::new(move |rect: NSRect| {
5948 source.drawInRect_fromRect_operation_fraction(
5949 rect,
5950 NSRect::ZERO,
5951 objc2_app_kit::NSCompositingOperation::SourceOver,
5952 1.0,
5953 );
5954 unsafe {
5955 ink.setFill();
5956 objc2_app_kit::NSRectFillUsingOperation(
5957 rect,
5958 objc2_app_kit::NSCompositingOperation::SourceIn,
5959 );
5960 }
5961 objc2::runtime::Bool::YES
5962 });
5963 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
5964 });
5965 unsafe {
5966 let position = btn.imagePosition();
5967 let image = image.map(|source| {
5972 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
5975 return source;
5976 }
5977 let size = source.size();
5978 let template = source.isTemplate();
5979 let padded = NSSize::new(size.width + 8.0, size.height);
5980 let draw = block2::RcBlock::new(move |_rect: NSRect| {
5981 source.drawInRect_fromRect_operation_fraction(
5982 NSRect::new(NSPoint::new(0.0, 0.0), size),
5983 NSRect::ZERO,
5984 objc2_app_kit::NSCompositingOperation::SourceOver,
5985 1.0,
5986 );
5987 objc2::runtime::Bool::YES
5988 });
5989 let out =
5990 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
5991 out.setTemplate(template);
5992 out
5993 });
5994 btn.setImage(image.as_deref());
5995 btn.setImagePosition(position);
5996 btn.setImageHugsTitle(true);
5997 }
5998}
5999
6000fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6006 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6007 unsafe {
6008 if on {
6009 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6010 }
6011 btn.setState(if on {
6012 NSControlStateValueOn
6013 } else {
6014 NSControlStateValueOff
6015 });
6016 }
6017}
6018
6019const TINT_CORNER_RADIUS: f64 = 6.0;
6022
6023fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6033 use day_spec::props::ButtonStyleSpec as S;
6034 let title = unsafe { btn.title() }.to_string();
6035 unsafe {
6036 btn.setKeyEquivalent(&NSString::from_str(""));
6038 btn.setBezelColor(None);
6039 btn.setBordered(!matches!(style, S::Plain));
6040 match style {
6041 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6042 S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6043 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6046 }
6047 btn.setWantsLayer(true);
6048 if let Some(layer) = btn.layer() {
6049 match style {
6050 S::Tinted(c) => {
6051 layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6052 layer.setCornerRadius(TINT_CORNER_RADIUS);
6053 }
6054 _ => layer.setBackgroundColor(None),
6055 }
6056 }
6057 }
6058 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6059 let ink = match style {
6060 S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6061 _ => None,
6062 };
6063 unsafe {
6064 btn.setContentTintColor(ink.as_deref());
6065 }
6066 set_button_title(btn, &title, style);
6067 set_button_image(btn, style);
6068}
6069
6070fn set_button_title(
6080 btn: &objc2_app_kit::NSButton,
6081 title: &str,
6082 style: day_spec::props::ButtonStyleSpec,
6083) {
6084 use day_spec::props::ButtonStyleSpec as S;
6085 let position = unsafe { btn.imagePosition() };
6088 let S::Tinted(fill) = style else {
6089 unsafe {
6091 btn.setTitle(&NSString::from_str(title));
6092 btn.setImagePosition(position);
6093 }
6094 return;
6095 };
6096 unsafe {
6097 let col = nscolor(S::on_tint(fill));
6098 let font = btn
6099 .font()
6100 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6101 let para = objc2_app_kit::NSMutableParagraphStyle::new();
6104 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6105 let keys: [&NSString; 3] = [
6106 objc2_app_kit::NSFontAttributeName,
6107 objc2_app_kit::NSForegroundColorAttributeName,
6108 objc2_app_kit::NSParagraphStyleAttributeName,
6109 ];
6110 let objs: [&objc2::runtime::AnyObject; 3] = [
6111 font.as_ref() as &objc2::runtime::AnyObject,
6112 col.as_ref() as &objc2::runtime::AnyObject,
6113 para.as_ref() as &objc2::runtime::AnyObject,
6114 ];
6115 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6116 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6117 objc2_foundation::NSAttributedString::alloc(),
6118 &NSString::from_str(title),
6119 Some(&attrs),
6120 );
6121 btn.setAttributedTitle(&s);
6122 btn.setImagePosition(position);
6123 }
6124}
6125
6126define_class!(
6129 #[unsafe(super(objc2_app_kit::NSImageView))]
6130 #[thread_kind = MainThreadOnly]
6131 #[name = "DayFillImageView"]
6132 struct FillImageView;
6133
6134 impl FillImageView {
6135 #[unsafe(method(drawRect:))]
6136 fn draw_rect(&self, dirty: NSRect) {
6137 let bounds = self.bounds();
6138 let image = unsafe { self.image() };
6139 let Some(size) = image.map(|image| image.size()).filter(|size| {
6140 size.width > 0.0 && size.height > 0.0
6141 && bounds.size.width > 0.0 && bounds.size.height > 0.0
6142 }) else {
6143 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6144 return;
6145 };
6146 let x = bounds.size.width / size.width;
6147 let y = bounds.size.height / size.height;
6148 let scale = x.max(y) / x.min(y);
6149 let cx = bounds.origin.x + bounds.size.width / 2.0;
6150 let cy = bounds.origin.y + bounds.size.height / 2.0;
6151 NSGraphicsContext::saveGraphicsState_class();
6152 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6153 let transform = NSAffineTransform::transform();
6154 transform.translateXBy_yBy(cx, cy);
6155 transform.scaleBy(scale);
6156 transform.translateXBy_yBy(-cx, -cy);
6157 transform.concat();
6158 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6159 NSGraphicsContext::restoreGraphicsState_class();
6160 }
6161
6162 #[unsafe(method(setFrameSize:))]
6163 fn set_frame_size(&self, size: NSSize) {
6164 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6165 NSView::setNeedsDisplay(self, true);
6166 }
6167 }
6168);
6169
6170fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6171 use day_spec::Shape;
6172 use objc2_app_kit::NSBezierPath;
6173 unsafe {
6174 Some(match shape {
6175 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6176 Shape::RoundedRect(r, rad) => {
6177 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6178 }
6179 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6180 Shape::Arc {
6181 rect,
6182 start_deg,
6183 sweep_deg,
6184 } => {
6185 let p = NSBezierPath::new();
6186 let center = NSPoint::new(
6187 rect.origin.x + rect.size.width / 2.0,
6188 rect.origin.y + rect.size.height / 2.0,
6189 );
6190 let radius = rect.size.width.min(rect.size.height) / 2.0;
6191 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6193 center,
6194 radius,
6195 *start_deg,
6196 *start_deg + *sweep_deg,
6197 );
6198 p
6199 }
6200 Shape::Line(a, b) => {
6201 let p = NSBezierPath::new();
6202 p.moveToPoint(NSPoint::new(a.x, a.y));
6203 p.lineToPoint(NSPoint::new(b.x, b.y));
6204 p
6205 }
6206 Shape::Polygon(pts) => {
6207 if pts.len() < 2 {
6208 return None;
6209 }
6210 let p = NSBezierPath::new();
6211 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6212 for pt in &pts[1..] {
6213 p.lineToPoint(NSPoint::new(pt.x, pt.y));
6214 }
6215 p.closePath();
6216 p
6217 }
6218 Shape::Path(path) => {
6219 use day_spec::PathSeg;
6220 if path.segs.is_empty() {
6221 return None;
6222 }
6223 let p = NSBezierPath::new();
6224 let mut cur = NSPoint::new(0.0, 0.0);
6228 for seg in &path.segs {
6229 match seg {
6230 PathSeg::Move(a) => {
6231 cur = NSPoint::new(a.x, a.y);
6232 p.moveToPoint(cur);
6233 }
6234 PathSeg::Line(a) => {
6235 cur = NSPoint::new(a.x, a.y);
6236 p.lineToPoint(cur);
6237 }
6238 PathSeg::Quad(c, a) => {
6239 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6240 let c1 = NSPoint::new(
6241 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6242 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6243 );
6244 let c2 = NSPoint::new(
6245 end.x + 2.0 / 3.0 * (ctl.x - end.x),
6246 end.y + 2.0 / 3.0 * (ctl.y - end.y),
6247 );
6248 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6249 cur = end;
6250 }
6251 PathSeg::Cubic(c1, c2, a) => {
6252 cur = NSPoint::new(a.x, a.y);
6253 p.curveToPoint_controlPoint1_controlPoint2(
6254 cur,
6255 NSPoint::new(c1.x, c1.y),
6256 NSPoint::new(c2.x, c2.y),
6257 );
6258 }
6259 PathSeg::Close => p.closePath(),
6260 }
6261 }
6262 p.setWindingRule(match path.rule {
6263 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6264 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6265 });
6266 p
6267 }
6268 })
6269 }
6270}
6271
6272struct UndoIvars {
6280 state: std::cell::RefCell<day_spec::UndoState>,
6281}
6282
6283define_class!(
6284 #[unsafe(super(objc2_foundation::NSUndoManager))]
6285 #[thread_kind = MainThreadOnly]
6286 #[name = "DayUndoManager"]
6287 #[ivars = UndoIvars]
6288 struct DayUndoManager;
6289
6290 impl DayUndoManager {
6294 #[unsafe(method(canUndo))]
6295 fn can_undo(&self) -> bool {
6296 self.ivars().state.borrow().can_undo
6297 }
6298
6299 #[unsafe(method(canRedo))]
6300 fn can_redo(&self) -> bool {
6301 self.ivars().state.borrow().can_redo
6302 }
6303
6304 #[unsafe(method(undo))]
6305 fn do_undo(&self) {
6306 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6307 }
6308
6309 #[unsafe(method(redo))]
6310 fn do_redo(&self) {
6311 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6312 }
6313
6314 #[unsafe(method_id(undoMenuItemTitle))]
6315 fn undo_menu_item_title(&self) -> Retained<NSString> {
6316 let label = self.ivars().state.borrow().undo_label.clone();
6319 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6320 }
6321
6322 #[unsafe(method_id(redoMenuItemTitle))]
6323 fn redo_menu_item_title(&self) -> Retained<NSString> {
6324 let label = self.ivars().state.borrow().redo_label.clone();
6325 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6326 }
6327 }
6328);
6329
6330fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6331 UNDO_FRONT.with(|u| {
6332 u.borrow_mut()
6333 .get_or_insert_with(|| {
6334 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6335 state: std::cell::RefCell::new(day_spec::UndoState::default()),
6336 });
6337 unsafe { msg_send![super(this), init] }
6338 })
6339 .clone()
6340 })
6341}
6342
6343struct WinIvars {
6351 node: Option<NodeId>,
6352 group: Option<String>,
6355 last_state: Cell<i32>,
6358}
6359
6360define_class!(
6361 #[unsafe(super(NSObject))]
6362 #[thread_kind = MainThreadOnly]
6363 #[name = "DayWinDelegate"]
6364 #[ivars = WinIvars]
6365 struct DayWinDelegate;
6366
6367 unsafe impl NSObjectProtocol for DayWinDelegate {}
6368
6369 impl DayWinDelegate {
6373 #[unsafe(method(undo:))]
6377 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6378 ffi_guard::contain((), || {
6379 if let Some(m) = self.acting_undo_manager() {
6380 unsafe { m.undo() };
6381 }
6382 });
6383 }
6384
6385 #[unsafe(method(redo:))]
6387 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6388 ffi_guard::contain((), || {
6389 if let Some(m) = self.acting_undo_manager() {
6390 unsafe { m.redo() };
6391 }
6392 });
6393 }
6394
6395 #[unsafe(method(cut:))]
6396 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6397 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6398 }
6399
6400 #[unsafe(method(copy:))]
6401 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6402 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6403 }
6404
6405 #[unsafe(method(paste:))]
6406 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6407 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6408 }
6409
6410 #[unsafe(method(selectAll:))]
6411 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6412 ffi_guard::contain((), || {
6413 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6414 });
6415 }
6416
6417 #[unsafe(method(validateMenuItem:))]
6421 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6422 ffi_guard::contain(false, || {
6423 let state = EDIT_STATE.with(|s| s.get());
6424 match unsafe { item.action() } {
6425 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6428 Some(m) => {
6429 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6430 unsafe { m.canUndo() }
6431 }
6432 None => false,
6433 },
6434 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6435 Some(m) => {
6436 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6437 unsafe { m.canRedo() }
6438 }
6439 None => false,
6440 },
6441 Some(a) if a == sel!(selectAll:) => state.can_select_all,
6442 Some(a) if a == sel!(cut:) => state.can_cut,
6443 Some(a) if a == sel!(copy:) => state.can_copy,
6444 Some(a) if a == sel!(paste:) => {
6445 state.can_paste && {
6446 let pb = unsafe { NSPasteboard::generalPasteboard() };
6447 pb.types().is_some_and(|types| !types.is_empty())
6448 }
6449 }
6450 _ => true,
6451 }
6452 })
6453 }
6454 }
6455
6456 unsafe impl NSWindowDelegate for DayWinDelegate {
6457 #[unsafe(method(windowDidResize:))]
6458 fn window_did_resize(&self, notification: &NSNotification) {
6459 ffi_guard::contain((), || {
6460 if let Some(obj) = unsafe { notification.object() }
6461 && let Ok(win) = obj.downcast::<NSWindow>()
6462 && let Some(size) = pin_below_title_bar(&win)
6463 {
6464 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6465 emit(target, Event::WindowResized(size));
6466 }
6467 self.report_state_of(notification);
6469 })
6470 }
6471
6472 #[unsafe(method(windowShouldClose:))]
6473 fn window_should_close(&self, _window: &NSWindow) -> bool {
6474 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6475 }
6476
6477 #[unsafe(method(windowWillClose:))]
6478 fn window_will_close(&self, _notification: &NSNotification) {
6479 ffi_guard::contain((), || {
6480 match self.ivars().node {
6481 Some(node) => emit(node, Event::WindowClosed),
6484 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6489 None => {
6490 let app = NSApplication::sharedApplication(self.mtm());
6491 unsafe { app.terminate(None) };
6492 }
6493 }
6494 })
6495 }
6496
6497 #[unsafe(method_id(windowWillReturnUndoManager:))]
6498 fn window_will_return_undo_manager(
6499 &self,
6500 _window: &NSWindow,
6501 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6502 ffi_guard::contain(None, || {
6506 UNDO_FRONT.with(|u| {
6507 u.borrow()
6508 .as_ref()
6509 .map(|m| Retained::into_super(m.clone()))
6510 })
6511 })
6512 }
6513
6514 #[unsafe(method(windowDidBecomeKey:))]
6515 fn window_did_become_key(&self, _notification: &NSNotification) {
6516 ffi_guard::contain((), || {
6517 if let Some(node) = self.ivars().node {
6518 emit(node, Event::WindowFocused(true));
6519 }
6520 })
6521 }
6522
6523 #[unsafe(method(windowDidResignKey:))]
6524 fn window_did_resign_key(&self, _notification: &NSNotification) {
6525 ffi_guard::contain((), || {
6526 if let Some(node) = self.ivars().node {
6527 emit(node, Event::WindowFocused(false));
6528 }
6529 })
6530 }
6531
6532 #[unsafe(method(windowDidMiniaturize:))]
6533 fn window_did_miniaturize(&self, notification: &NSNotification) {
6534 ffi_guard::contain((), || self.report_state_of(notification))
6535 }
6536
6537 #[unsafe(method(windowDidDeminiaturize:))]
6538 fn window_did_deminiaturize(&self, notification: &NSNotification) {
6539 ffi_guard::contain((), || self.report_state_of(notification))
6540 }
6541
6542 #[unsafe(method(windowDidEnterFullScreen:))]
6543 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6544 ffi_guard::contain((), || self.report_state_of(notification))
6545 }
6546
6547 #[unsafe(method(windowDidExitFullScreen:))]
6548 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6549 ffi_guard::contain((), || self.report_state_of(notification))
6550 }
6551 }
6552
6553 impl DayWinDelegate {
6557 #[unsafe(method(newWindowForTab:))]
6558 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6559 ffi_guard::contain((), || {
6560 let _ = match self.ivars().group.as_deref() {
6563 Some(group) => day_core::windows::open_new_window_for_group(group),
6564 None => day_core::windows::open_new_window(),
6565 };
6566 })
6567 }
6568 }
6569);
6570
6571impl DayWinDelegate {
6572 fn report_state_of(&self, notification: &NSNotification) {
6573 if let Some(obj) = unsafe { notification.object() }
6574 && let Ok(win) = obj.downcast::<NSWindow>()
6575 {
6576 self.report_state(&win);
6577 }
6578 }
6579}
6580
6581fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6584 match unsafe { event.keyCode() } {
6585 123 => Some("ArrowLeft"),
6586 124 => Some("ArrowRight"),
6587 125 => Some("ArrowDown"),
6588 126 => Some("ArrowUp"),
6589 _ => {
6597 let held = NSEventModifierFlags::Command
6598 | NSEventModifierFlags::Option
6599 | NSEventModifierFlags::Control;
6600 if event.modifierFlags().intersects(held) {
6601 return None;
6602 }
6603 let typed = event.characters()?.to_string();
6604 let mut chars = typed.chars();
6605 match (chars.next(), chars.next()) {
6606 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6607 _ => None,
6608 }
6609 }
6610 }
6611}
6612
6613fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6615 let mut modifiers = 0u8;
6616 if f.contains(NSEventModifierFlags::Shift) {
6617 modifiers |= day_spec::KeyEvent::SHIFT;
6618 }
6619 if f.contains(NSEventModifierFlags::Command) {
6620 modifiers |= day_spec::KeyEvent::PRIMARY;
6621 }
6622 if f.contains(NSEventModifierFlags::Option) {
6623 modifiers |= day_spec::KeyEvent::ALT;
6624 }
6625 modifiers
6626}
6627
6628impl DayWinDelegate {
6629 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6634 let responder = NSApplication::sharedApplication(self.mtm())
6635 .keyWindow()
6636 .and_then(|w| w.firstResponder());
6637 responder
6638 .and_then(|r| unsafe { r.undoManager() })
6639 .or_else(|| {
6640 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6641 })
6642 }
6643}
6644
6645impl DayWinDelegate {
6646 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6647 let this = Self::alloc(mtm).set_ivars(WinIvars {
6648 node,
6649 group,
6650 last_state: Cell::new(day_spec::WindowState::Normal.code()),
6651 });
6652 unsafe { msg_send![super(this), init] }
6653 }
6654
6655 fn report_state(&self, window: &NSWindow) {
6659 let state = ns_window_state(window);
6660 if self.ivars().last_state.replace(state.code()) != state.code() {
6661 log::debug!("appkit: window state now {state:?}");
6662 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6663 emit(target, Event::WindowStateChanged(state));
6664 }
6665 }
6666}
6667
6668fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6671 if window.isMiniaturized() {
6672 day_spec::WindowState::Minimized
6673 } else if window
6674 .styleMask()
6675 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6676 {
6677 day_spec::WindowState::Fullscreen
6678 } else if window.isZoomed() {
6679 day_spec::WindowState::Maximized
6680 } else {
6681 day_spec::WindowState::Normal
6682 }
6683}
6684
6685fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6688 use day_spec::WindowState as S;
6689 let current = ns_window_state(window);
6690 if current == state {
6691 return;
6692 }
6693 unsafe {
6694 match current {
6695 S::Minimized => window.deminiaturize(None),
6696 S::Fullscreen => {
6700 window.toggleFullScreen(None);
6701 return;
6702 }
6703 S::Maximized if state != S::Minimized => window.zoom(None),
6704 _ => {}
6705 }
6706 match state {
6707 S::Normal => {}
6708 S::Minimized => window.miniaturize(None),
6709 S::Maximized => {
6710 if !window.isZoomed() {
6711 window.zoom(None)
6712 }
6713 }
6714 S::Fullscreen => window.toggleFullScreen(None),
6715 }
6716 }
6717}
6718
6719#[distributed_slice]
6725pub static RENDERERS: [fn() -> Renderer<AppKit>];
6726
6727struct SecondaryWin {
6731 window: Retained<NSWindow>,
6732 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
6734 content: Handle,
6735}
6736
6737struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6740impl Drop for MenuEscapeMonitor {
6741 fn drop(&mut self) {
6742 unsafe { NSEvent::removeMonitor(&self.0) };
6743 }
6744}
6745
6746pub struct AppKit {
6747 menu_escape_monitor: Option<MenuEscapeMonitor>,
6748 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6749
6750 mtm: MainThreadMarker,
6751 registry: Registry<AppKit>,
6752 window: Option<Retained<NSWindow>>,
6753 content: Option<Handle>,
6754 secondary: Vec<SecondaryWin>,
6755 app_name: String,
6756 cascade: Option<NSPoint>,
6761 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
6764}
6765
6766impl AppKit {
6767 fn swap_text_field(
6772 &mut self,
6773 h: &Handle,
6774 old: &NSTextField,
6775 node: NodeId,
6776 secure: bool,
6777 ) -> Retained<NSTextField> {
6778 let new = new_text_field(self.mtm, node, secure);
6779 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
6780 let window = h.window();
6783 let focused = window
6784 .as_deref()
6785 .is_some_and(|w| owns_first_responder(w, h));
6786 let selection = old.currentEditor().map(|e| e.selectedRange());
6787 unsafe {
6788 new.setStringValue(&old.stringValue());
6789 new.setPlaceholderString(old.placeholderString().as_deref());
6790 new.setEnabled(old.isEnabled());
6791 new.setFont(old.font().as_deref());
6792 new.setFrame(h.frame());
6793 new.setHidden(h.isHidden());
6794 new.setMenu(h.menu().as_deref());
6795 new.setToolTip(h.toolTip().as_deref());
6796 if h.wantsLayer() {
6798 new.setWantsLayer(true);
6799 new.setAlphaValue(h.alphaValue());
6800 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
6801 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
6802 if !from.is_null() && !to.is_null() {
6803 let t: CGAffineTransform = msg_send![from, affineTransform];
6804 let _: () = msg_send![to, setAffineTransform: t];
6805 }
6806 }
6807 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
6810 new.setAccessibilityIdentifier(Some(&id));
6811 }
6812 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
6813 new.setAccessibilityLabel(Some(&label));
6814 }
6815 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
6816 new.setAccessibilityHelp(Some(&help));
6817 }
6818 if !h.isAccessibilityElement() {
6819 new.setAccessibilityElement(false);
6820 }
6821 }
6822 for r in unsafe { h.gestureRecognizers() }.iter() {
6824 unsafe {
6825 h.removeGestureRecognizer(&r);
6826 new.addGestureRecognizer(&r);
6827 }
6828 }
6829 GESTURES.with(|m| {
6830 let mut m = m.borrow_mut();
6831 if let Some(targets) = m.remove(&old_key) {
6832 m.insert(new_key, targets);
6833 }
6834 });
6835 if let Some((owner, area)) = self.cursors.remove(&old_key) {
6836 unsafe {
6837 h.removeTrackingArea(&area);
6838 new.addTrackingArea(&area);
6839 }
6840 self.cursors.insert(new_key, (owner, area));
6841 }
6842 PAN_NODES.with(|t| rekey(t, old_key, new_key));
6843 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
6844 KEY_NODES.with(|t| rekey(t, old_key, new_key));
6845 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
6846 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
6847 transfer::moved(h, &new);
6848 unsafe { old.setDelegate(None) };
6851 TARGETS.with(|m| {
6852 m.borrow_mut().remove(&old_key);
6853 });
6854 if let Some(parent) = unsafe { h.superview() } {
6855 unsafe {
6856 parent.addSubview_positioned_relativeTo(
6857 &new,
6858 objc2_app_kit::NSWindowOrderingMode::Above,
6859 Some(h),
6860 );
6861 h.removeFromSuperview();
6862 }
6863 }
6864 if focused && let Some(window) = window {
6865 FIELD_SWAP.with(|s| s.set(true));
6866 let taken = window.makeFirstResponder(Some(&new));
6867 FIELD_SWAP.with(|s| s.set(false));
6868 if taken && let Some(editor) = new.currentEditor() {
6871 let len = unsafe { new.stringValue() }.length();
6872 let range = selection
6873 .filter(|r| r.location.saturating_add(r.length) <= len)
6874 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
6875 editor.setSelectedRange(range);
6876 }
6877 }
6878 day_spec::sidetable::sweep(old_key);
6880 new
6881 }
6882
6883 pub fn new() -> Self {
6884 let mtm =
6885 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
6886 let mut registry = Registry::default();
6887 for f in RENDERERS {
6888 registry.register(f());
6889 }
6890 AppKit {
6891 menu_escape_monitor: None,
6892 mtm,
6893 registry,
6894 window: None,
6895 sharing: None,
6896 content: None,
6897 secondary: Vec::new(),
6898 app_name: "Day".into(),
6899 cascade: None,
6900 cursors: HashMap::new(),
6901 }
6902 }
6903
6904 pub fn mtm(&self) -> MainThreadMarker {
6906 self.mtm
6907 }
6908
6909 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
6911 if let Some(w) = self
6912 .secondary
6913 .iter()
6914 .find(|w| ptr_of(&w.content) == ptr_of(host))
6915 {
6916 return Some(w.window.clone());
6917 }
6918 self.content
6919 .as_ref()
6920 .filter(|c| ptr_of(c) == ptr_of(host))
6921 .and(self.window.clone())
6922 }
6923
6924 fn make_window(
6930 &self,
6931 options: &WindowOptions,
6932 prefs_style: bool,
6933 node: Option<NodeId>,
6934 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
6935 let mtm = self.mtm;
6936 let (title, size, min_size, tabbing) = (
6937 options.title.as_str(),
6938 options.size,
6939 options.min_size,
6940 &options.tabbing,
6941 );
6942 let content_rect =
6943 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
6944 let style = window_chrome::style_mask(options, prefs_style);
6946 let window = window_chrome::alloc_window(
6947 mtm,
6948 content_rect,
6949 style,
6950 options.chrome == day_spec::WindowChrome::Frameless,
6951 );
6952 unsafe { window.setReleasedWhenClosed(false) };
6953 window.setTitle(&NSString::from_str(title));
6954 if let Some(min) = min_size {
6955 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
6956 }
6957 if let Some(max) = options.max_size {
6958 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
6959 }
6960 use day_spec::WindowTabbing as T;
6961 use objc2_app_kit::NSWindowTabbingMode as M;
6962 let group = match tabbing {
6963 T::Group(g) | T::Preferred(g) => Some(g.clone()),
6964 T::Automatic | T::Disallowed => None,
6965 };
6966 match tabbing {
6967 _ if prefs_style => window.setTabbingMode(M::Disallowed),
6968 T::Disallowed => window.setTabbingMode(M::Disallowed),
6969 T::Automatic => unsafe {
6973 window.setTabbingIdentifier(&NSString::from_str("day.normal"))
6974 },
6975 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
6976 T::Preferred(g) => {
6977 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
6978 window.setTabbingMode(M::Preferred);
6979 }
6980 }
6981 if group.is_some() {
6982 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
6985 }
6986 let delegate = DayWinDelegate::new(mtm, node, group);
6987 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
6988 let content = view_of(DayFlipped::new(mtm));
6989 window.setContentView(Some(&content));
6990 window_chrome::apply(&window, &content, options);
6991 window.setAutorecalculatesKeyViewLoop(true);
7000 (window, delegate, content)
7001 }
7002}
7003
7004impl Default for AppKit {
7005 fn default() -> Self {
7006 Self::new()
7007 }
7008}
7009
7010fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7011 Retained::from(x.as_ref())
7012}
7013
7014fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7015 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7016}
7017
7018fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7021 use objc2_app_kit::*;
7022 unsafe {
7023 Some(match f {
7024 Font::LargeTitle => NSFontTextStyleLargeTitle,
7025 Font::Title => NSFontTextStyleTitle1,
7026 Font::Title2 => NSFontTextStyleTitle2,
7027 Font::Title3 => NSFontTextStyleTitle3,
7028 Font::Headline => NSFontTextStyleHeadline,
7029 Font::Subheadline => NSFontTextStyleSubheadline,
7030 Font::Body => NSFontTextStyleBody,
7031 Font::Callout => NSFontTextStyleCallout,
7032 Font::Footnote => NSFontTextStyleFootnote,
7033 Font::Caption => NSFontTextStyleCaption1,
7034 Font::Caption2 => NSFontTextStyleCaption2,
7035 Font::System(_) | Font::Custom(..) => return None,
7036 })
7037 }
7038}
7039
7040fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7041 use day_spec::FontWeight as W;
7042 use objc2_app_kit::*;
7043 unsafe {
7044 match w {
7045 W::UltraLight => NSFontWeightUltraLight,
7046 W::Thin => NSFontWeightThin,
7047 W::Light => NSFontWeightLight,
7048 W::Regular => NSFontWeightRegular,
7049 W::Medium => NSFontWeightMedium,
7050 W::Semibold => NSFontWeightSemibold,
7051 W::Bold => NSFontWeightBold,
7052 W::Heavy => NSFontWeightHeavy,
7053 W::Black => NSFontWeightBlack,
7054 }
7055 }
7056}
7057
7058fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7061 use day_spec::FontWeight as W;
7062 match w {
7063 W::UltraLight => 2,
7064 W::Thin => 3,
7065 W::Light => 4,
7066 W::Regular => 5,
7067 W::Medium => 6,
7068 W::Semibold => 8,
7069 W::Bold => 9,
7070 W::Heavy => 10,
7071 W::Black => 12,
7072 }
7073}
7074
7075fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7080 use objc2_app_kit::*;
7081 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7082 let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7083 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7084 let mut traits = NSFontTraitMask::empty();
7085 if weight >= day_spec::FontWeight::Semibold {
7086 traits |= NSFontTraitMask::BoldFontMask;
7087 }
7088 if font.italic {
7089 traits |= NSFontTraitMask::ItalicFontMask;
7090 }
7091 let Some(family) = font.family.as_deref() else {
7092 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7093 return if font.italic {
7094 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7095 } else {
7096 base
7097 };
7098 };
7099 let ns_family = NSString::from_str(family);
7100 if let Some(f) = unsafe {
7101 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7102 } {
7103 return f;
7104 }
7105 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7106 return if traits.is_empty() {
7107 f
7108 } else {
7109 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7110 };
7111 }
7112 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7113 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7114}
7115
7116fn canvas_text_attrs(
7119 font: &NSFont,
7120 color: day_spec::Color,
7121) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7122 let col = nscolor(color);
7123 let keys: [&NSString; 2] = unsafe {
7125 [
7126 objc2_app_kit::NSFontAttributeName,
7127 objc2_app_kit::NSForegroundColorAttributeName,
7128 ]
7129 };
7130 let objs: [&objc2::runtime::AnyObject; 2] = [
7131 font as &objc2::runtime::AnyObject,
7132 col.as_ref() as &objc2::runtime::AnyObject,
7133 ];
7134 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7135}
7136
7137fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7140 use objc2_app_kit::*;
7141 let base: Retained<NSFont> = match spec.style {
7142 Font::System(pt) => {
7143 let w = spec
7144 .weight
7145 .map(ns_weight)
7146 .unwrap_or(unsafe { NSFontWeightRegular });
7147 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7148 }
7149 Font::Custom(name, pt) => {
7153 match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7154 Some(f) => {
7155 if spec
7156 .weight
7157 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7158 {
7159 let mtm = objc2::MainThreadMarker::new()
7160 .expect("labels realize on the main thread");
7161 unsafe {
7162 NSFontManager::sharedFontManager(mtm)
7163 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7164 }
7165 } else {
7166 f
7167 }
7168 }
7169 None => {
7170 log::warn!(
7171 "unknown font family {name:?} — falling back to the system font \
7172 (is the file in the project's fonts/ directory?)"
7173 );
7174 let w = spec
7175 .weight
7176 .map(ns_weight)
7177 .unwrap_or(unsafe { NSFontWeightRegular });
7178 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7179 }
7180 }
7181 }
7182 style => {
7183 let ts = ns_text_style(style).expect("semantic style");
7186 let opts = objc2_foundation::NSDictionary::new();
7187 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7188 match spec.weight {
7189 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7191 None => f,
7192 }
7193 }
7194 };
7195 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7200 let w = spec
7201 .weight
7202 .map(ns_weight)
7203 .unwrap_or(unsafe { NSFontWeightRegular });
7204 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7205 } else {
7206 base
7207 };
7208 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7212 let w = spec
7213 .weight
7214 .map(ns_weight)
7215 .unwrap_or(unsafe { NSFontWeightRegular });
7216 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7217 } else {
7218 base
7219 };
7220 let base = if spec.scale != 1.0 {
7224 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7225 let pts = spec.resolved_points(base.pointSize());
7226 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7227 } else {
7228 base
7229 };
7230 if spec.italic {
7231 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7232 unsafe {
7233 NSFontManager::sharedFontManager(mtm)
7234 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7235 }
7236 } else {
7237 base
7238 }
7239}
7240
7241fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7251 use objc2_foundation::{NSMutableAttributedString, NSRange};
7252 unsafe {
7253 let cur = tf.attributedStringValue();
7254 let m = NSMutableAttributedString::initWithAttributedString(
7255 NSMutableAttributedString::alloc(),
7256 &cur,
7257 );
7258 let style = objc2_app_kit::NSMutableParagraphStyle::new();
7259 style.setAlignment(align);
7260 style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7263 m.addAttribute_value_range(
7264 objc2_app_kit::NSParagraphStyleAttributeName,
7265 &style,
7266 NSRange::new(0, cur.length()),
7267 );
7268 tf.setAttributedStringValue(&m);
7269 }
7270}
7271
7272fn attributed_label(
7273 text: &str,
7274 base_font: &NSFont,
7275 color: Option<day_spec::Color>,
7276 role: day_spec::props::TextRole,
7277 runs: &[day_spec::TextRun],
7278) -> Retained<objc2_foundation::NSAttributedString> {
7279 use objc2_foundation::{NSMutableAttributedString, NSRange};
7280 let ns = NSString::from_str(text);
7281 let s = unsafe {
7282 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7283 };
7284 let whole = NSRange::new(0, ns.length());
7285 unsafe {
7286 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7287 let fg = color.map(nscolor).unwrap_or_else(|| match role {
7295 day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7296 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7297 });
7298 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7299 }
7300 for r in runs {
7301 let Some(range) = utf16_range(text, &r.range) else {
7302 continue;
7303 };
7304 unsafe {
7305 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7306 if let Some(c) = r.color {
7307 s.addAttribute_value_range(
7308 objc2_app_kit::NSForegroundColorAttributeName,
7309 &nscolor(c),
7310 range,
7311 );
7312 }
7313 if let Some(c) = r.background {
7314 s.addAttribute_value_range(
7315 objc2_app_kit::NSBackgroundColorAttributeName,
7316 &nscolor(c),
7317 range,
7318 );
7319 }
7320 if r.underline.is_on() {
7321 let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7322 s.addAttribute_value_range(
7323 objc2_app_kit::NSUnderlineStyleAttributeName,
7324 &style,
7325 range,
7326 );
7327 }
7328 if r.strikethrough {
7329 let one = objc2_foundation::NSNumber::new_i64(1);
7330 s.addAttribute_value_range(
7331 objc2_app_kit::NSStrikethroughStyleAttributeName,
7332 &one,
7333 range,
7334 );
7335 }
7336 if let Some(url) = r.link.as_deref() {
7337 let value = NSString::from_str(url);
7340 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7341 }
7342 }
7343 }
7344 s.into_super()
7345}
7346
7347fn ns_underline(u: day_spec::Underline) -> i64 {
7351 use day_spec::Underline as U;
7352 match u {
7353 U::None => 0,
7354 U::Single => 0x01,
7355 U::Double => 0x09,
7356 U::Dotted => 0x01 | 0x0100,
7357 U::Wavy => 0x01 | 0x0400,
7358 }
7359}
7360
7361fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7363 let start = text.get(..r.start)?.encode_utf16().count();
7364 let len = text.get(r.clone())?.encode_utf16().count();
7365 Some(objc2_foundation::NSRange::new(start, len))
7366}
7367
7368fn register_bundled_fonts() {
7373 #[link(name = "CoreText", kind = "framework")]
7375 unsafe extern "C" {
7376 fn CTFontManagerRegisterFontsForURL(
7377 font_url: *const std::ffi::c_void,
7378 scope: u32, error: *mut *const std::ffi::c_void,
7380 ) -> bool;
7381 }
7382 for path in day_spec::fonts::bundled_fonts() {
7383 let url = unsafe {
7384 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7385 };
7386 let ok = unsafe {
7387 CTFontManagerRegisterFontsForURL(
7388 Retained::as_ptr(&url) as *const std::ffi::c_void,
7389 1,
7390 std::ptr::null_mut(),
7391 )
7392 };
7393 if !ok {
7394 log::warn!("could not register bundled font {}", path.display());
7395 }
7396 }
7397}
7398
7399fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7402 match a {
7403 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7404 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7405 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7406 }
7407}
7408
7409fn configure_label_cell(tf: &NSTextField) {
7410 if let Some(cell) = unsafe { tf.cell() } {
7411 unsafe {
7412 cell.setWraps(true);
7413 cell.setUsesSingleLineMode(false);
7414 cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7415 }
7416 }
7417}
7418
7419fn content_of(parent: &Handle) -> Retained<NSView> {
7421 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7422 && let Some(doc) = unsafe { sv.documentView() }
7423 {
7424 return doc;
7425 }
7426 parent.clone()
7427}
7428
7429fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7435 let Some(a) = anim else {
7436 body();
7437 return;
7438 };
7439 let (dur, timing) = appkit_timing(a);
7440 unsafe {
7441 NSAnimationContext::beginGrouping();
7442 let ctx = NSAnimationContext::currentContext();
7443 ctx.setDuration(dur);
7444 ctx.setTimingFunction(Some(&timing));
7445 ctx.setAllowsImplicitAnimation(true);
7446 body();
7447 NSAnimationContext::endGrouping();
7448 }
7449}
7450
7451fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7454 unsafe {
7455 let named = |n| {
7456 (
7457 a.duration_secs().max(0.01),
7458 CAMediaTimingFunction::functionWithName(n),
7459 )
7460 };
7461 match a.curve {
7462 Curve::Linear => named(kCAMediaTimingFunctionLinear),
7463 Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7464 Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7465 Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7466 Curve::Spring { damping, .. } => {
7467 let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7469 (
7470 a.duration_secs().max(0.05),
7471 CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7472 )
7473 }
7474 }
7475 }
7476}
7477
7478fn warn_missing_renderer(kind: PieceKind) {
7483 day_spec::placeholder::report(kind, "appkit");
7484}
7485
7486pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7490 view_of(unsafe {
7491 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7492 })
7493}
7494
7495impl Toolkit for AppKit {
7496 fn ui_idle(&mut self) -> bool {
7499 toolbar::chrome_settled()
7500 }
7501
7502 type Handle = Handle;
7503
7504 fn dark_mode(&mut self) -> bool {
7505 let app = NSApplication::sharedApplication(self.mtm());
7508 app.effectiveAppearance()
7509 .name()
7510 .to_string()
7511 .contains("Dark")
7512 }
7513
7514 fn reduce_motion(&mut self) -> bool {
7517 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7518 }
7519
7520 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7524 use day_spec::AppBadge;
7525 let label = match badge {
7526 AppBadge::None => None,
7527 AppBadge::Count(0) => None,
7529 AppBadge::Count(n) => Some(n.to_string()),
7530 AppBadge::Text(t) if t.is_empty() => None,
7531 AppBadge::Text(t) => Some(t.clone()),
7532 AppBadge::Dot => Some("\u{2022}".to_string()),
7534 };
7535 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7536 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7537 unsafe { tile.setBadgeLabel(ns.as_deref()) };
7538 tile.display();
7539 }
7540
7541 fn set_appearance(&mut self, dark: Option<bool>) {
7542 let app = NSApplication::sharedApplication(self.mtm());
7543 let appearance = dark.and_then(|d| {
7544 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7545 if d {
7546 objc2_app_kit::NSAppearanceNameDarkAqua
7547 } else {
7548 objc2_app_kit::NSAppearanceNameAqua
7549 }
7550 })
7551 });
7552 unsafe { app.setAppearance(appearance.as_deref()) };
7554 }
7555
7556 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7557 controls::refresh_gesture::attach(handle, host);
7558 }
7559
7560 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7561 unsafe {
7562 handle.setHidden(!visible);
7563 }
7564 }
7565
7566 fn capability(&self, cap: Cap) -> Support {
7567 match cap {
7568 Cap::SearchField => Support::Native,
7569 Cap::ComboBox => Support::Native,
7570 Cap::Stepper => Support::Native,
7571 Cap::DateTimePicker => Support::Native,
7572 Cap::ColorPicker => Support::Native,
7573 Cap::PullRefresh => Support::Emulated,
7574 Cap::Pager => Support::Emulated,
7575 Cap::PullRefreshGesture => Support::Emulated,
7576 Cap::Cursor => Support::Native,
7580 Cap::FontList => Support::Native,
7582 Cap::ListItem => Support::Native,
7584 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7588 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7591 Cap::Announce => Support::Native,
7594 Cap::ReduceMotion => Support::Native,
7597 Cap::Snapshot
7598 | Cap::NativeSymbols
7599 | Cap::NavTabs
7608 | Cap::NavSplit
7609 | Cap::NavRepresent
7613 | Cap::NavContentList
7616 | Cap::Dialogs
7617 | Cap::FileDialogs
7618 | Cap::FolderDialog
7620 | Cap::Animation
7621 | Cap::TextEditable
7623 | Cap::TextSelectable
7624 | Cap::TextSpellCheck
7625 | Cap::NavReorder | Cap::ListReorder
7628 | Cap::ListRecycling
7631 | Cap::ListSwipeActions
7634 | Cap::ListSections
7636 | Cap::Tree
7639 | Cap::TreeSections
7640 | Cap::TreeMove
7641 | Cap::MultiWindow
7643 | Cap::WindowStates
7646 | Cap::WindowFullscreen
7647 | Cap::ContentProtection
7649 | Cap::WindowTabbing
7652 | Cap::DockMenu
7654 | Cap::FramelessWindow
7658 | Cap::OverlayTitleBar
7659 | Cap::TransparentWindow
7660 | Cap::WindowMaterial
7661 | Cap::DragRegion
7663 | Cap::StatusItem
7666 | Cap::AppProgress
7667 | Cap::DockVisibility
7668 | Cap::WindowGeometry
7671 | Cap::WindowPosition
7672 | Cap::WindowLevel
7673 | Cap::WindowAppearance
7674 | Cap::RequestAttention
7675 | Cap::Monitors
7676 | Cap::DynamicShortcuts
7678 | Cap::Toolbar
7680 | Cap::ToolbarSearch
7682 | Cap::AppMenu
7683 | Cap::AppBadgeCount
7686 | Cap::AppBadgeText
7687 | Cap::UndoBridge
7690 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7691 | Cap::AppBadgeDot
7692 | Cap::Appearance
7693 | Cap::BaselineAlignment
7695 | Cap::Inspector
7698 | Cap::Split
7700 | Cap::TextRuns
7701 | Cap::TextLinks => Support::Native,
7702 Cap::Cover => Support::Emulated,
7705 Cap::CoverSheet => Support::Native,
7707 _ => Support::Unsupported,
7708 }
7709 }
7710
7711 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7712 let mtm = self.mtm;
7713 match Builtin::from_key(kind) {
7714 Some(Builtin::Container) => {
7715 let v = DayFlipped::new(mtm);
7716 if let Some(p) = props.downcast_ref::<ContainerProps>() {
7717 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7718 v.set_section_card(p.corner_radius);
7719 } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7720 v.set_surface(p.background, p.corner_radius, p.clips);
7721 }
7722 }
7723 view_of(v)
7724 }
7725 Some(Builtin::Scroll) => {
7726 let horizontal = props
7727 .downcast_ref::<day_spec::props::ScrollProps>()
7728 .map(|p| p.horizontal)
7729 .unwrap_or(false);
7730 let sv = unsafe { NSScrollView::new(mtm) };
7731 unsafe {
7732 sv.setHasVerticalScroller(!horizontal);
7733 sv.setHasHorizontalScroller(horizontal);
7734 sv.setDrawsBackground(false);
7735 sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7741 }
7742 let doc = DayFlipped::new(mtm);
7743 unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7744 view_of(sv)
7745 }
7746 Some(Builtin::Label) => {
7747 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7752 return placeholder_view(mtm, kind);
7753 };
7754 let tf = DayLabel::new(mtm, id, &p.text);
7755 configure_label_cell(&tf);
7756 if !p.wraps || p.max_lines > 0 {
7757 unsafe {
7758 tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
7759 if !p.wraps || p.max_lines == 1 {
7760 tf.setUsesSingleLineMode(true);
7761 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
7762 }
7763 }
7764 }
7765 unsafe { tf.setFont(Some(&nsfont(p.font))) };
7766 match (p.color, p.role) {
7770 (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
7771 (None, day_spec::props::TextRole::Secondary) => unsafe {
7772 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
7773 },
7774 (None, day_spec::props::TextRole::Primary) => {}
7775 }
7776 if !p.runs.is_empty() {
7777 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
7778 unsafe { tf.setAttributedStringValue(&s) };
7779 }
7780 tf.ivars().has_runs.set(!p.runs.is_empty());
7781 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
7782 if p.align != day_spec::props::TextAlign::Leading {
7787 unsafe { tf.setAlignment(nstextalign(p.align)) };
7788 if !p.runs.is_empty() {
7789 set_paragraph_alignment(&tf, nstextalign(p.align));
7790 }
7791 }
7792 view_of(Retained::into_super(tf))
7793 }
7794 Some(Builtin::Button) => {
7795 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
7796 return placeholder_view(mtm, kind);
7797 };
7798 let target = DayTarget::new(mtm, id);
7799 let btn = unsafe {
7800 NSButton::buttonWithTitle_target_action(
7801 &NSString::from_str(&p.title),
7802 Some(&*target),
7803 Some(sel!(action:)),
7804 mtm,
7805 )
7806 };
7807 apply_button_style(&btn, p.style);
7808 if p.icon.is_some() {
7809 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
7810 }
7811 unsafe { btn.setEnabled(p.enabled) };
7812 set_button_selected(&btn, p.selected);
7813 let view = view_of(btn);
7814 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7815 view
7816 }
7817 Some(Builtin::Toggle) => {
7818 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
7819 return placeholder_view(mtm, kind);
7820 };
7821 let target = DayTarget::new(mtm, id);
7822 let sw = unsafe { NSSwitch::new(mtm) };
7823 unsafe {
7824 sw.setState(if p.on { 1 } else { 0 });
7825 sw.setEnabled(p.enabled);
7826 sw.setTarget(Some(&*target));
7827 sw.setAction(Some(sel!(action:)));
7828 }
7829 let view = view_of(sw);
7830 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7831 view
7832 }
7833 Some(Builtin::Slider) => {
7834 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
7835 return placeholder_view(mtm, kind);
7836 };
7837 let target = DayTarget::new(mtm, id);
7838 let sl = unsafe {
7839 NSSlider::sliderWithValue_minValue_maxValue_target_action(
7840 p.value,
7841 p.min,
7842 p.max,
7843 Some(&*target),
7844 Some(sel!(action:)),
7845 mtm,
7846 )
7847 };
7848 unsafe { sl.setContinuous(true) };
7849 let view = view_of(sl);
7850 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7851 view
7852 }
7853 Some(Builtin::Picker) => picker::realize_any(self, props, id),
7854 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
7855 Some(Builtin::TextField) => {
7856 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
7857 return placeholder_view(mtm, kind);
7858 };
7859 let tf = new_text_field(mtm, id, false);
7860 unsafe {
7861 tf.setStringValue(&NSString::from_str(&p.text));
7862 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
7863 }
7864 view_of(tf)
7865 }
7866 Some(Builtin::Divider) => {
7867 let b = unsafe { NSBox::new(mtm) };
7868 unsafe { b.setBoxType(NSBoxType::Separator) };
7869 view_of(b)
7870 }
7871 Some(Builtin::Progress) => {
7872 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
7873 return placeholder_view(mtm, kind);
7874 };
7875 if p.value.is_none() {
7876 return crate::controls::spinner::make(self, p, id);
7877 }
7878 let pi = unsafe { NSProgressIndicator::new(mtm) };
7879 unsafe {
7880 match p.value {
7881 Some(v) => {
7882 pi.setStyle(NSProgressIndicatorStyle::Bar);
7883 pi.setIndeterminate(false);
7884 pi.setMinValue(0.0);
7885 pi.setMaxValue(1.0);
7886 pi.setDoubleValue(v);
7887 }
7888 None => {
7889 pi.setStyle(NSProgressIndicatorStyle::Spinning);
7890 pi.setIndeterminate(true);
7891 pi.startAnimation(None);
7892 }
7893 }
7894 }
7895 view_of(pi)
7896 }
7897 Some(Builtin::Canvas) => {
7898 let canvas = DayCanvas::new(mtm);
7899 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
7900 view_of(canvas)
7901 }
7902 Some(Builtin::Inspector) => {
7903 let (visible, width, leading) = props
7904 .downcast_ref::<InspectorProps>()
7905 .map(|p| {
7906 (
7907 p.visible,
7908 p.width,
7909 p.edge == day_spec::props::PaneEdge::Leading,
7910 )
7911 })
7912 .unwrap_or((false, 280.0, false));
7913 let content_wrap = view_of(DayFlipped::new(mtm));
7914 let panel_flipped = DayFlipped::new(mtm);
7915 panel_flipped.set_pane_backdrop();
7919 let panel_wrap = view_of(panel_flipped);
7920 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
7921 let _ = unsafe { split_vc.view() };
7924 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7925 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7926 unsafe {
7927 content_vc.setView(&content_wrap);
7928 panel_vc.setView(&panel_wrap);
7929 }
7930 let content_item = unsafe {
7931 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
7932 };
7933 let panel_item = unsafe {
7938 if leading {
7939 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
7940 } else {
7941 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
7942 }
7943 };
7944 unsafe {
7945 panel_item.setCanCollapse(false);
7949 panel_item.setCollapsed(!visible);
7950 panel_item.setMinimumThickness(width);
7951 panel_item.setMaximumThickness(width);
7952 panel_item.setAllowsFullHeightLayout(true);
7953 if leading {
7954 split_vc.addSplitViewItem(&panel_item);
7955 split_vc.addSplitViewItem(&content_item);
7956 } else {
7957 split_vc.addSplitViewItem(&content_item);
7958 split_vc.addSplitViewItem(&panel_item);
7959 }
7960 }
7961 let split = unsafe { split_vc.splitView() };
7962 unsafe {
7963 split.setVertical(true);
7964 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7965 split.setTranslatesAutoresizingMaskIntoConstraints(true);
7969 }
7970 let view = view_of(split);
7971 INSPECTOR_STATE.with(|m| {
7972 m.borrow_mut().insert(
7973 ptr_of(&view),
7974 InspectorState {
7975 content_wrap,
7976 panel_wrap,
7977 _split_vc: split_vc,
7978 panel_item,
7979 },
7980 )
7981 });
7982 view
7983 }
7984 Some(Builtin::InspectorPane) => {
7985 let pane = view_of(DayNavPage::new(mtm, id));
7989 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7990 let panel = props
7991 .downcast_ref::<InspectorPaneProps>()
7992 .map(|p| p.panel)
7993 .unwrap_or(false);
7994 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
7995 pane
7996 }
7997 Some(Builtin::Split) => {
7998 let (axis, fraction, min_pane) = props
7999 .downcast_ref::<SplitProps>()
8000 .map(|p| (p.axis, p.fraction, p.min_pane))
8001 .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8002 let wrap = view_of(DayFlipped::new(mtm));
8003 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8004 let first_wrap = view_of(DayFlipped::new(mtm));
8005 let second_wrap = view_of(DayFlipped::new(mtm));
8006 unsafe {
8007 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8009 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8010 split.addArrangedSubview(&first_wrap);
8011 split.addArrangedSubview(&second_wrap);
8012 split.setFrame(wrap.bounds());
8013 split.setAutoresizingMask(
8014 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8015 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8016 );
8017 wrap.addSubview(&split);
8018 }
8019 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8020 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8021 SPLIT_STATE.with(|m| {
8022 m.borrow_mut().insert(
8023 ptr_of(&wrap),
8024 SplitState {
8025 split,
8026 first_wrap,
8027 second_wrap,
8028 delegate,
8029 },
8030 )
8031 });
8032 wrap
8033 }
8034 Some(Builtin::SplitPane) => {
8035 let pane = view_of(DayNavPage::new(mtm, id));
8038 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8039 let second = props
8040 .downcast_ref::<SplitPaneProps>()
8041 .map(|p| p.second)
8042 .unwrap_or(false);
8043 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8044 pane
8045 }
8046 Some(Builtin::Nav) => {
8047 let presentation = props
8048 .downcast_ref::<NavProps>()
8049 .map(|p| p.presentation)
8050 .unwrap_or(NavPresentation::Split);
8051 let is_split = presentation.is_split();
8052 let sidebar_wrap = view_of(DayFlipped::new(mtm));
8061 let detail_wrap = view_of(DayFlipped::new(mtm));
8062 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8063 let _ = unsafe { split_vc.view() };
8069 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8072 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8073 unsafe {
8074 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8075 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8076 }
8077 let sidebar_item = unsafe {
8078 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8079 };
8080 let detail_item = unsafe {
8081 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8082 };
8083 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8089 let list_visible = props
8095 .downcast_ref::<NavProps>()
8096 .is_none_or(|p| p.list_visible);
8097 let (list_wrap, list_item) = match list_width {
8098 Some(w) => {
8099 let wrap = view_of(DayFlipped::new(mtm));
8100 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8101 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8102 let item = unsafe {
8103 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8104 };
8105 unsafe {
8106 item.setCanCollapse(true);
8107 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8108 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8109 item.setCollapsed(!list_visible);
8110 }
8111 (Some(wrap), Some(item))
8112 }
8113 None => (None, None),
8114 };
8115 unsafe {
8116 sidebar_item.setCanCollapse(is_split);
8119 sidebar_item.setCollapsed(!is_split);
8120 if is_split {
8121 sidebar_item.setAllowsFullHeightLayout(true);
8125 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8126 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8127 } else {
8128 sidebar_item.setMinimumThickness(0.0);
8129 sidebar_item.setMaximumThickness(0.0);
8130 }
8131 split_vc.addSplitViewItem(&sidebar_item);
8132 if let Some(item) = list_item.as_ref() {
8133 split_vc.addSplitViewItem(item);
8134 }
8135 split_vc.addSplitViewItem(&detail_item);
8136 }
8137 let split = unsafe { split_vc.splitView() };
8138 unsafe {
8145 let after = split.nextResponder();
8146 split.setNextResponder(Some(&split_vc));
8147 let own_view = split_vc.view();
8157 let vc_resp: *const objc2_app_kit::NSResponder = {
8158 let r: &objc2_app_kit::NSResponder = &split_vc;
8159 r
8160 };
8161 let view_resp: *const objc2_app_kit::NSResponder = {
8162 let r: &objc2_app_kit::NSResponder = &own_view;
8163 r
8164 };
8165 let upstream = after.filter(|a| {
8166 let p: *const objc2_app_kit::NSResponder = &**a;
8167 p != vc_resp && p != view_resp
8168 });
8169 split_vc.setNextResponder(upstream.as_deref());
8170 }
8171 unsafe {
8172 split.setVertical(true);
8173 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8174 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8182 }
8183 let root_title = props
8184 .downcast_ref::<NavProps>()
8185 .map(|p| p.title.clone())
8186 .unwrap_or_default();
8187 let header = if presentation == NavPresentation::Stack {
8190 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8191 } else {
8192 None
8193 };
8194 let tabs = (presentation == NavPresentation::Tabs).then(|| {
8197 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8198 let b = detail_wrap.bounds();
8203 let frame = NSRect::new(
8204 NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8205 NSSize::new(
8206 (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8207 (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8208 ),
8209 );
8210 unsafe {
8211 tv.setTabViewType(
8212 if props
8213 .downcast_ref::<NavProps>()
8214 .is_some_and(|p| p.documents.is_some())
8215 {
8216 objc2_app_kit::NSTabViewType::NoTabsNoBorder
8217 } else {
8218 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8219 },
8220 );
8221 tv.setFrame(frame);
8222 tv.setAutoresizingMask(
8223 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8224 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8225 );
8226 detail_wrap.addSubview(&tv);
8227 }
8228 TabHost {
8229 view: tv,
8230 target: None,
8231 }
8232 });
8233 let view = view_of(split);
8234 NAV_STATE.with(|m| {
8235 m.borrow_mut().insert(
8236 ptr_of(&view),
8237 NavState {
8238 sidebar_wrap,
8239 detail_wrap,
8240 _split_vc: split_vc,
8241 sidebar_item,
8242 list_wrap,
8243 list_item,
8244 pages: Vec::new(),
8245 list_page: None,
8246 sidebar_page: None,
8247 list_width,
8248 list_visible,
8249 list_positioned: false,
8250 positioned: false,
8251 presentation,
8252 selected: 0,
8253 tabs,
8254 header,
8255 root_title,
8256 node: id,
8257 title_strip: 0.0,
8258 },
8259 )
8260 });
8261 view
8262 }
8263 Some(Builtin::NavPage) => {
8264 let page = view_of(DayNavPage::new(mtm, id));
8265 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8266 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8267 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8268 }
8269 page
8270 }
8271 Some(Builtin::Cover) => {
8275 let page = DayNavPage::new(mtm, id);
8276 let cover_props = props.downcast_ref::<CoverProps>();
8277 page.ivars()
8280 .sheet
8281 .set(cover_props.is_some_and(|p| p.sheet || p.half));
8282 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8283 page.ivars().large.set(cover_props.is_some_and(|p| p.large));
8284 unsafe { page.setHidden(true) };
8285 view_of(page)
8286 }
8287 Some(Builtin::NavMenu) => {
8288 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8289 return placeholder_view(mtm, kind);
8290 };
8291 let data = DayNavMenuData::new(
8292 mtm,
8293 id,
8294 &p.items,
8295 &p.icons,
8296 &p.badges,
8297 &p.badge_icons,
8298 &p.badge_tints,
8299 &p.sections,
8300 &p.tints,
8301 &p.menus,
8302 );
8303 *data.ivars().movable.borrow_mut() = p.movable.clone();
8304 data.ivars().regroup.set(p.regroup);
8305 *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8306 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8308 let o: Retained<DayNavOutlineView> =
8309 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8310 NAV_OUTLINE_MENUS
8311 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8312 unsafe { msg_send![&*o, self] }
8313 };
8314 let col = unsafe {
8315 objc2_app_kit::NSTableColumn::initWithIdentifier(
8316 objc2_app_kit::NSTableColumn::alloc(mtm),
8317 &NSString::from_str("item"),
8318 )
8319 };
8320 unsafe {
8321 outline.addTableColumn(&col);
8322 outline.setOutlineTableColumn(Some(&col));
8323 outline.setHeaderView(None);
8324 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8337 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8342 outline.setFloatsGroupRows(true);
8345 outline.setIndentationPerLevel(0.0);
8346 outline.registerForDraggedTypes(
8349 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8350 DAY_NAV_PASTEBOARD_TYPE,
8351 )]),
8352 );
8353 outline.setDraggingSourceOperationMask_forLocal(
8354 objc2_app_kit::NSDragOperation::Move,
8355 true,
8356 );
8357 outline.setDraggingSourceOperationMask_forLocal(
8358 objc2_app_kit::NSDragOperation::None,
8359 false,
8360 );
8361 outline.setDraggingDestinationFeedbackStyle(
8362 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8363 );
8364 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8365 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8366 outline.reloadData();
8367 }
8368 let scroll = unsafe { NSScrollView::new(mtm) };
8369 unsafe {
8370 scroll.setDrawsBackground(false);
8371 scroll.setHasVerticalScroller(true);
8372 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8376 scroll.setHasHorizontalScroller(false);
8378 outline.setAutoresizingMask(
8379 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8380 );
8381 outline.setColumnAutoresizingStyle(
8382 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8383 );
8384 scroll.setDocumentView(Some(&outline));
8385 }
8386 let view = view_of(scroll);
8387 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8390 data.ivars().suppress.set(true);
8391 unsafe {
8392 outline.selectRowIndexes_byExtendingSelection(
8393 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8394 false,
8395 )
8396 };
8397 data.ivars().suppress.set(false);
8398 }
8399 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8400 view
8401 }
8402 Some(Builtin::List) => {
8403 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8404 return placeholder_view(mtm, kind);
8405 };
8406 let table: Retained<DayListView> =
8408 unsafe { msg_send![DayListView::alloc(mtm), init] };
8409 let table = Retained::into_super(table);
8410 let col = unsafe {
8411 NSTableColumn::initWithIdentifier(
8412 NSTableColumn::alloc(mtm),
8413 &NSString::from_str("day.list.col"),
8414 )
8415 };
8416 let data = DayListData::new(
8417 mtm,
8418 id,
8419 p.selectable,
8420 p.multi_select,
8421 p.row_height == RowHeight::Automatic,
8422 p.sections,
8423 );
8424 unsafe {
8425 if p.multi_select {
8426 table.setAllowsMultipleSelection(true);
8427 }
8428 table.addTableColumn(&col);
8429 table.setHeaderView(None);
8430 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8439 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8443 if p.separators == Some(true) {
8447 table.setGridStyleMask(
8448 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8449 );
8450 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8451 }
8452 table.setColumnAutoresizingStyle(
8453 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8454 );
8455 table.setFloatsGroupRows(p.sections);
8458 match p.row_height {
8459 RowHeight::Uniform(h) => table.setRowHeight(h),
8460 RowHeight::Automatic => table.setRowHeight(44.0),
8461 }
8462 if !p.selectable {
8463 table.setSelectionHighlightStyle(
8464 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8465 );
8466 }
8467 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8471 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8472 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8473 table.setTarget(Some(&*data));
8474 if p.activatable {
8475 table.setDoubleAction(Some(sel!(doubleClickRow:)));
8476 }
8477 if p.reorderable {
8478 table.registerForDraggedTypes(
8482 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8483 DAY_ROW_PASTEBOARD_TYPE,
8484 )]),
8485 );
8486 table.setDraggingSourceOperationMask_forLocal(
8487 objc2_app_kit::NSDragOperation::Move,
8488 true,
8489 );
8490 table.setDraggingSourceOperationMask_forLocal(
8491 objc2_app_kit::NSDragOperation::None,
8492 false,
8493 );
8494 table.setDraggingDestinationFeedbackStyle(
8495 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8496 );
8497 }
8498 }
8499 let scroll = unsafe { NSScrollView::new(mtm) };
8500 unsafe {
8501 scroll.setDrawsBackground(false);
8502 scroll.setHasVerticalScroller(true);
8503 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8507 scroll.setDocumentView(Some(&table));
8508 let clip = scroll.contentView();
8509 clip.setPostsBoundsChangedNotifications(true);
8510 objc2_foundation::NSNotificationCenter::defaultCenter()
8511 .addObserver_selector_name_object(
8512 &data,
8513 sel!(listViewportChanged:),
8514 Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8515 Some(&clip),
8516 );
8517 }
8518 let view = view_of(scroll);
8519 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8520 view
8521 }
8522 Some(Builtin::Tree) => {
8523 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8524 return placeholder_view(mtm, kind);
8525 };
8526 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8528 let o: Retained<DayOutlineView> =
8529 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8530 unsafe { msg_send![&*o, self] }
8531 };
8532 let col = unsafe {
8533 NSTableColumn::initWithIdentifier(
8534 NSTableColumn::alloc(mtm),
8535 &NSString::from_str("day.tree.col"),
8536 )
8537 };
8538 let data = DayTreeData::new(mtm, id, p.selectable);
8539 unsafe {
8540 if p.multi_select {
8541 outline.setAllowsMultipleSelection(true);
8542 }
8543 outline.addTableColumn(&col);
8544 outline.setOutlineTableColumn(Some(&col));
8545 outline.setHeaderView(None);
8546 if p.section_headers {
8547 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8550 outline.setFloatsGroupRows(true);
8551 } else {
8552 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8555 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8556 }
8557 outline.setColumnAutoresizingStyle(
8558 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8559 );
8560 outline.setAutoresizesOutlineColumn(true);
8561 if let Some(indent) = p.indent {
8562 outline.setIndentationPerLevel(indent);
8563 }
8564 match p.row_height {
8565 RowHeight::Uniform(h) => outline.setRowHeight(h),
8566 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8567 RowHeight::Automatic => {}
8568 }
8569 if !p.selectable {
8570 outline.setSelectionHighlightStyle(
8571 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8572 );
8573 }
8574 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8575 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8576 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8577 if p.movable {
8578 outline.registerForDraggedTypes(
8583 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8584 DAY_TREE_PASTEBOARD_TYPE,
8585 )]),
8586 );
8587 outline.setDraggingSourceOperationMask_forLocal(
8588 objc2_app_kit::NSDragOperation::Move,
8589 true,
8590 );
8591 outline.setDraggingSourceOperationMask_forLocal(
8592 objc2_app_kit::NSDragOperation::None,
8593 false,
8594 );
8595 }
8596 }
8597 let scroll = unsafe { NSScrollView::new(mtm) };
8598 unsafe {
8599 scroll.setDrawsBackground(false);
8600 scroll.setHasVerticalScroller(true);
8601 scroll.setHasHorizontalScroller(false);
8602 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8603 outline.setAutoresizingMask(
8604 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8605 );
8606 scroll.setDocumentView(Some(&outline));
8607 }
8608 let view = view_of(scroll);
8609 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8610 view
8611 }
8612 Some(Builtin::Image) => {
8613 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8614 return placeholder_view(mtm, kind);
8615 };
8616 let iv: Retained<objc2_app_kit::NSImageView> =
8617 if p.content_mode == ContentMode::Fill {
8618 let view: Retained<FillImageView> =
8619 unsafe { msg_send![FillImageView::alloc(mtm), init] };
8620 Retained::from(
8621 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8622 )
8623 } else {
8624 unsafe { objc2_app_kit::NSImageView::new(mtm) }
8625 };
8626 let scaling = match p.content_mode {
8629 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8630 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8631 };
8632 unsafe { iv.setImageScaling(scaling) };
8633 if let Some(img) = appkit_image_for(&p.source) {
8634 if p.tint.is_some() || p.template {
8639 unsafe { img.setTemplate(true) };
8640 }
8641 unsafe { iv.setImage(Some(&img)) };
8642 }
8643 if let Some(t) = p.tint {
8644 unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8645 }
8646 IMAGE_MODES.with(|t| {
8647 t.insert(
8648 ptr_of(&iv),
8649 ImageMode {
8650 template: p.template,
8651 tinted: p.tint.is_some(),
8652 },
8653 )
8654 });
8655 view_of(iv)
8656 }
8657 Some(Builtin::ListItem) => {
8658 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8659 else {
8660 return placeholder_view(mtm, kind);
8661 };
8662 make_list_item(p, mtm)
8663 }
8664 Some(Builtin::ListCell) | None => {
8667 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8668 return make(self, props, id);
8669 }
8670 warn_missing_renderer(kind);
8674 placeholder_view(mtm, kind)
8675 }
8676 }
8677 }
8678
8679 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8680 match kind {
8681 kinds::LIST_ITEM => {
8682 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8683 return;
8684 };
8685 let props = LIST_ITEMS.with(|m| {
8686 let mut m = m.borrow_mut();
8687 let props = m.get_mut(&ptr_of(h))?;
8688 use day_spec::props::ListItemPatch as P;
8689 match p {
8690 P::Title(t) => props.title = t.clone(),
8691 P::Subtitle(t) => props.subtitle = t.clone(),
8692 P::Detail(t) => props.detail = t.clone(),
8693 P::Icon(i) => props.icon = i.clone(),
8694 P::IconTint(c) => props.icon_tint = *c,
8695 P::Checked(on) => props.checked = *on,
8696 }
8697 Some(props.clone())
8698 });
8699 if let Some(props) = props {
8700 dress_list_item(h, &props, self.mtm());
8701 }
8702 }
8703 kinds::IMAGE => {
8704 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8705 match p {
8706 day_spec::props::ImagePatch::Tint(c) => {
8707 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8711 let key = ptr_of(&iv);
8712 let template = IMAGE_MODES
8713 .with(|t| {
8714 t.with(key, |m| {
8715 m.tinted = c.is_some();
8716 m.renders_template()
8717 })
8718 })
8719 .unwrap_or(c.is_some());
8720 if let Some(img) = unsafe { iv.image() } {
8721 unsafe { img.setTemplate(template) };
8722 }
8723 unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8724 }
8725 }
8726 day_spec::props::ImagePatch::Source(source) => {
8730 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8731 if let Some(img) = appkit_image_for(source) {
8737 let template = IMAGE_MODES
8738 .with(|t| t.get(ptr_of(&iv)))
8739 .is_some_and(|m| m.renders_template());
8740 unsafe {
8741 img.setTemplate(template);
8742 iv.setImage(Some(&img));
8743 }
8744 }
8745 }
8746 }
8747 }
8748 }
8749 }
8750 kinds::CONTAINER => {
8751 if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8752 patch.downcast_ref::<ContainerPatch>(),
8753 h.clone().downcast::<DayFlipped>(),
8754 ) {
8755 v.set_surface(*c, 0.0, false);
8763 }
8764 }
8765 kinds::LABEL => {
8766 if let (Some(p), Ok(tf)) = (
8767 patch.downcast_ref::<LabelPatch>(),
8768 h.clone().downcast::<NSTextField>(),
8769 ) {
8770 match p {
8771 LabelPatch::Text(t) => {
8772 unsafe { tf.setStringValue(&NSString::from_str(t)) };
8773 if let Some(label) = h.downcast_ref::<DayLabel>() {
8774 label.ivars().has_runs.set(false);
8775 label.set_links(false);
8776 }
8777 }
8778 LabelPatch::Color(c) => unsafe {
8779 tf.setTextColor(c.map(nscolor).as_deref())
8780 },
8781 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
8782 LabelPatch::Runs(text, runs) => {
8783 let base = unsafe { tf.font() };
8787 let s = match base.as_deref() {
8788 Some(f) => {
8789 attributed_label(text, f, None, Default::default(), runs)
8790 }
8791 None => attributed_label(
8792 text,
8793 &nsfont(day_spec::FontSpec::default()),
8794 None,
8795 Default::default(),
8796 runs,
8797 ),
8798 };
8799 unsafe { tf.setAttributedStringValue(&s) };
8800 set_paragraph_alignment(&tf, unsafe { tf.alignment() });
8803 if let Some(label) = h.downcast_ref::<DayLabel>() {
8804 label.ivars().has_runs.set(!runs.is_empty());
8805 label.set_links(runs.iter().any(|r| r.link.is_some()));
8806 }
8807 }
8808 }
8809 }
8810 }
8811 kinds::BUTTON => {
8812 if let (Some(p), Ok(btn)) = (
8813 patch.downcast_ref::<ButtonPatch>(),
8814 h.clone().downcast::<NSButton>(),
8815 ) {
8816 match p {
8817 ButtonPatch::Content(c) => {
8818 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
8819 }
8820 ButtonPatch::Title(t) => {
8821 let style = BUTTON_STYLES
8822 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
8823 .unwrap_or_default();
8824 set_button_title(&btn, t, style);
8825 }
8826 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
8827 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
8828 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
8829 }
8830 }
8831 }
8832 kinds::TOGGLE => {
8833 if let (Some(p), Ok(sw)) = (
8834 patch.downcast_ref::<TogglePatch>(),
8835 h.clone().downcast::<NSSwitch>(),
8836 ) {
8837 match p {
8838 TogglePatch::On(on) => {
8839 let want = if *on { 1 } else { 0 };
8840 if unsafe { sw.state() } != want {
8841 unsafe { sw.setState(want) };
8842 }
8843 }
8844 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
8845 }
8846 }
8847 }
8848 kinds::SLIDER => {
8849 if let (Some(p), Ok(sl)) = (
8850 patch.downcast_ref::<SliderPatch>(),
8851 h.clone().downcast::<NSSlider>(),
8852 ) {
8853 match p {
8854 SliderPatch::Value(v) => {
8855 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
8856 unsafe { sl.setDoubleValue(*v) };
8857 }
8858 }
8859 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
8860 }
8861 }
8862 }
8863 kinds::PROGRESS => {
8864 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
8865 {
8866 crate::controls::spinner::update(self, h, p);
8867 return;
8868 }
8869
8870 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
8871 patch.downcast_ref::<ProgressPatch>(),
8872 h.clone().downcast::<NSProgressIndicator>(),
8873 ) {
8874 unsafe {
8875 match v {
8876 Some(val) => {
8877 if pi.isIndeterminate() {
8878 pi.stopAnimation(None);
8879 pi.setIndeterminate(false);
8880 pi.setStyle(NSProgressIndicatorStyle::Bar);
8881 pi.setMinValue(0.0);
8882 pi.setMaxValue(1.0);
8883 }
8884 if (pi.doubleValue() - val).abs() > 0.0001 {
8885 pi.setDoubleValue(*val);
8886 }
8887 }
8888 None => {
8889 pi.setIndeterminate(true);
8890 pi.setStyle(NSProgressIndicatorStyle::Spinning);
8891 pi.startAnimation(None);
8892 }
8893 }
8894 }
8895 }
8896 }
8897 kinds::NAV_MENU => {
8898 if let Some(NavMenuPatch::Items {
8899 items,
8900 icons,
8901 badges,
8902 badge_icons,
8903 badge_tints,
8904 sections,
8905 tints,
8906 menus,
8907 movable,
8908 sorted,
8909 selected,
8910 rows_changed,
8911 ..
8912 }) = patch.downcast_ref::<NavMenuPatch>()
8913 {
8914 NAV_MENUS.with(|m| {
8915 let m = m.borrow();
8916 let Some((outline, data)) = m.get(&ptr_of(h)) else {
8917 return;
8918 };
8919 *data.ivars().movable.borrow_mut() = movable.clone();
8920 *data.ivars().sorted.borrow_mut() = sorted.clone();
8921 data.set_items(
8922 items,
8923 icons,
8924 badges,
8925 badge_icons,
8926 badge_tints,
8927 sections,
8928 tints,
8929 menus,
8930 );
8931 data.ivars().suppress.set(true);
8932 if let Some(rows) = rows_changed {
8935 let set = objc2_foundation::NSMutableIndexSet::new();
8936 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
8937 unsafe { set.addIndex(row) };
8938 }
8939 unsafe {
8940 outline.reloadDataForRowIndexes_columnIndexes(
8941 &set,
8942 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
8943 )
8944 };
8945 data.ivars().suppress.set(false);
8946 return;
8947 }
8948 unsafe {
8949 outline.reloadData();
8950 match selected.and_then(|i| data.row_of_item(i)) {
8951 Some(row) => outline.selectRowIndexes_byExtendingSelection(
8952 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8953 false,
8954 ),
8955 None => outline.deselectAll(None),
8956 }
8957 }
8958 data.ivars().suppress.set(false);
8959 });
8960 adopt_menu_for_tabs(self.mtm(), h);
8962 } else if let Some(NavMenuPatch::IconProgress(progress)) =
8963 patch.downcast_ref::<NavMenuPatch>()
8964 {
8965 NAV_MENUS.with(|menus| {
8966 let menus = menus.borrow();
8967 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
8968 return;
8969 };
8970 let previous = data.ivars().icon_progress.replace(progress.clone());
8971 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
8972 let Some(index) = item else {
8973 continue;
8974 };
8975 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
8976 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
8977 continue;
8978 }
8979 if let Some(view) = unsafe {
8980 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
8981 } && let Some(cell) =
8982 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
8983 && let Some(icon) = unsafe { cell.imageView() }
8984 {
8985 nav_progress::update(&icon, value);
8986 }
8987 }
8988 });
8989 } else if let Some(NavMenuPatch::Selected(sel)) =
8990 patch.downcast_ref::<NavMenuPatch>()
8991 {
8992 NAV_MENUS.with(|m| {
8993 let m = m.borrow();
8994 let Some((outline, data)) = m.get(&ptr_of(h)) else {
8995 return;
8996 };
8997 data.ivars().suppress.set(true);
8998 unsafe {
8999 match sel.and_then(|i| data.row_of_item(i)) {
9000 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9001 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9002 false,
9003 ),
9004 None => outline.deselectAll(None),
9005 }
9006 }
9007 data.ivars().suppress.set(false);
9008 });
9009 }
9010 }
9011 kinds::INSPECTOR => {
9012 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9013 INSPECTOR_STATE.with(|m| {
9014 if let Some(state) = m.borrow().get(&ptr_of(h)) {
9015 state.panel_item.setCollapsed(!*v);
9018 }
9019 });
9020 }
9021 }
9022 kinds::SPLIT => {
9023 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9024 SPLIT_STATE.with(|m| {
9025 let m = m.borrow();
9026 let Some(state) = m.get(&ptr_of(h)) else {
9027 return;
9028 };
9029 let iv = state.delegate.ivars();
9030 match p {
9031 SplitPatch::Fraction(f) => {
9032 iv.share.set(f.clamp(0.0, 1.0));
9033 if iv.positioned.get() {
9034 split_place(&state.split, iv);
9035 }
9036 }
9037 SplitPatch::Axis(axis) => unsafe {
9038 state
9039 .split
9040 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9041 state.split.adjustSubviews();
9042 if iv.positioned.get() {
9043 split_place(&state.split, iv);
9044 }
9045 },
9046 }
9047 });
9048 }
9049 }
9050 kinds::NAV => {
9051 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9052 nav_present(self.mtm(), h, *next);
9053 return;
9054 }
9055 if let Some(p) = patch.downcast_ref::<NavPatch>() {
9056 NAV_STATE.with(|m| {
9057 let mut m = m.borrow_mut();
9058 let Some(state) = m.get_mut(&ptr_of(h)) else {
9059 return;
9060 };
9061 match p {
9062 NavPatch::Pushed { title, .. } => {
9063 let last = state.pages.len().saturating_sub(1);
9065 state.selected = last;
9066 for (i, page) in state.pages.iter().enumerate() {
9067 page.setHidden(i != last);
9068 }
9069 if let Some(hdr) = state.header.as_mut() {
9070 hdr.titles.push(title.clone());
9071 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9072 }
9073 }
9074 NavPatch::Popped => {
9075 let n = state.pages.len();
9078 if let Some(top) = state.pages.last() {
9079 top.setHidden(true);
9080 }
9081 if n >= 2 {
9082 state.pages[n - 2].setHidden(false);
9083 }
9084 state.selected = n.saturating_sub(2);
9085 if let Some(hdr) = state.header.as_mut() {
9086 if hdr.titles.len() > 1 {
9087 hdr.titles.pop();
9088 }
9089 let after: Vec<Retained<NSView>> = state
9092 .pages
9093 .iter()
9094 .take(n.saturating_sub(1))
9095 .cloned()
9096 .collect();
9097 sync_nav_header(hdr, &state.detail_wrap, &after);
9098 }
9099 }
9100 NavPatch::Title(t) => {
9101 if let Some(hdr) = state.header.as_mut() {
9102 if let Some(last) = hdr.titles.last_mut() {
9103 *last = t.clone();
9104 }
9105 unsafe {
9106 hdr.title.setStringValue(&NSString::from_str(t));
9107 }
9108 }
9109 }
9110 NavPatch::GuardTop(_) => {}
9114 NavPatch::Reorder(order) => {
9115 let old = state.pages.clone();
9116 state.pages =
9117 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9118 if let Some(tabs) = &state.tabs {
9119 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9120 unsafe {
9121 let items = tabs.view.tabViewItems();
9122 for item in items.iter() {
9123 tabs.view.removeTabViewItem(&item);
9124 }
9125 for i in order {
9126 if let Some(item) = items.iter().nth(*i) {
9127 tabs.view.addTabViewItem(&item);
9128 }
9129 }
9130 }
9131 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9132 }
9133 }
9134 NavPatch::Presentation(_) => {}
9136 NavPatch::Select(i) => {
9140 state.selected = *i;
9141 match state.tabs.as_ref() {
9142 Some(tabs) => {
9144 let n = unsafe { tabs.view.numberOfTabViewItems() };
9145 if (*i as isize) < n {
9146 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9147 unsafe {
9148 tabs.view.selectTabViewItemAtIndex(*i as isize)
9149 };
9150 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9151 }
9152 }
9153 None => {
9154 for (n, page) in state.pages.iter().enumerate() {
9155 page.setHidden(n != *i);
9156 }
9157 }
9158 }
9159 }
9160 NavPatch::ListVisible(v) => {
9166 state.list_visible = *v;
9167 if let Some(item) = state.list_item.as_ref() {
9168 item.setCollapsed(!*v);
9169 let split = unsafe { state._split_vc.splitView() };
9170 unsafe { split.layoutSubtreeIfNeeded() };
9171 if let Some(w) = take_list_placement(state) {
9176 unsafe {
9177 split.setPosition_ofDividerAtIndex(
9178 day_spec::NAV_SIDEBAR_WIDTH + w,
9179 1,
9180 );
9181 }
9182 }
9183 if *v
9190 && let Some(wrap) = state.list_wrap.as_ref()
9191 && let Some(page) = state.list_page.as_ref()
9192 {
9193 unsafe {
9194 wrap.layoutSubtreeIfNeeded();
9195 page.setFrame(wrap.bounds());
9196 }
9197 }
9198 }
9199 }
9200 NavPatch::ListInStack(_) => {}
9204 }
9205 });
9206 }
9207 }
9208 kinds::COVER => {
9214 if let (Some(p), Ok(page)) = (
9215 patch.downcast_ref::<CoverPatch>(),
9216 h.clone().downcast::<DayNavPage>(),
9217 ) {
9218 let node = page.ivars().node;
9219 match p {
9220 CoverPatch::Present { background, .. } => {
9221 if page.ivars().sheet.get() {
9222 if let Some(parent) =
9223 primary_content().and_then(|v| unsafe { v.window() })
9224 {
9225 let bounds = parent.frame().size;
9226 let max = if page.ivars().large.get() {
9227 day_spec::props::LARGE_SHEET_MAX
9228 } else {
9229 day_spec::props::SHEET_MAX
9230 };
9231 let height = if page.ivars().half.get() {
9232 (bounds.height * 0.5).clamp(160.0, max.height)
9233 } else {
9234 (bounds.height - 80.0).clamp(300.0, max.height)
9235 };
9236 let size = NSSize::new(
9237 (bounds.width - 40.0).clamp(320.0, max.width),
9238 height,
9239 );
9240 let window = unsafe {
9241 NSWindow::initWithContentRect_styleMask_backing_defer(
9242 NSWindow::alloc(MainThreadMarker::new().unwrap()),
9243 NSRect::new(NSPoint::new(0.0, 0.0), size),
9244 NSWindowStyleMask::Titled,
9245 NSBackingStoreType::Buffered,
9246 false,
9247 )
9248 };
9249 unsafe {
9250 window.setReleasedWhenClosed(false);
9251 page.removeFromSuperview();
9252 page.setHidden(false);
9253 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9254 window.setContentView(Some(&page));
9255 }
9256 let key = ptr_of(h);
9257 SHEET_NODES.with(|t| {
9258 t.insert(Retained::as_ptr(&window) as usize, node)
9259 });
9260 install_sheet_escape_monitor();
9261 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9262 dispatch2::DispatchQueue::main().exec_async(move || {
9263 ffi_guard::contain((), || {
9264 let window =
9265 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9266 if let (Some(window), Some(parent)) = (
9267 window,
9268 primary_content()
9269 .and_then(|v| unsafe { v.window() }),
9270 ) {
9271 unsafe {
9272 parent.beginSheet_completionHandler(
9273 &window, None,
9274 );
9275 }
9276 }
9277 });
9278 });
9279 emit(
9280 node,
9281 Event::FrameChanged(Size::new(size.width, size.height)),
9282 );
9283 }
9284 return;
9285 }
9286 unsafe {
9290 page.setWantsLayer(true);
9291 if let Some(layer) = page.layer() {
9292 let color = match background {
9293 Some(bg) => nscolor(*bg),
9294 None => NSColor::windowBackgroundColor(),
9295 };
9296 layer.setBackgroundColor(Some(&color.CGColor()));
9297 }
9298 }
9299 if let Some(content) = primary_content() {
9302 if let Some(window) = unsafe { content.window() } {
9303 toolbar::cover_presented(ptr_of(h), &window);
9304 }
9305 let top = title_bar_inset(&content);
9310 let full = content.frame().size;
9311 page.ivars().top_inset.set(top);
9312 unsafe {
9313 page.removeFromSuperview();
9314 content.addSubview(&page);
9315 page.setFrame(NSRect::new(
9316 NSPoint::new(0.0, -top),
9317 NSSize::new(full.width, full.height),
9318 ));
9319 page.setBoundsOrigin(NSPoint::new(0.0, -top));
9320 page.setAutoresizingMask(
9321 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9322 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9323 );
9324 page.setHidden(false);
9325 }
9326 emit(
9327 node,
9328 Event::FrameChanged(Size::new(
9329 full.width,
9330 (full.height - top).max(0.0),
9331 )),
9332 );
9333 }
9334 }
9335 CoverPatch::DismissDisabled(_) => {}
9336 CoverPatch::Dismiss => {
9337 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9338 toolbar::cover_dismissed(ptr_of(h));
9339 unsafe {
9340 page.setHidden(true);
9341 page.removeFromSuperview();
9342 }
9343 emit(node, Event::CoverHidden);
9344 }
9345 }
9346 }
9347 }
9348 kinds::PICKER => picker::update_any(self, h, patch),
9349 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9350 kinds::TEXT_FIELD => {
9351 if let (Some(p), Ok(tf)) = (
9352 patch.downcast_ref::<TextFieldPatch>(),
9353 h.clone().downcast::<NSTextField>(),
9354 ) {
9355 match p {
9356 TextFieldPatch::Text { text, from_native } => {
9357 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9359 unsafe { tf.setStringValue(&NSString::from_str(text)) };
9360 }
9361 }
9362 TextFieldPatch::Placeholder(t) => unsafe {
9363 tf.setPlaceholderString(Some(&NSString::from_str(t)))
9364 },
9365 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9366 }
9367 }
9368 }
9369 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9370 Some(ListPatch::Splice(deltas)) => {
9371 if let Some((table, data)) = list_entry(ptr_of(h)) {
9377 use objc2_app_kit::NSTableViewAnimationOptions;
9378 for d in deltas {
9379 unsafe {
9380 table.beginUpdates();
9381 match d {
9382 day_spec::props::RowDelta::Insert(i) => table
9383 .insertRowsAtIndexes_withAnimation(
9384 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9385 NSTableViewAnimationOptions::SlideDown,
9386 ),
9387 day_spec::props::RowDelta::Remove(i) => table
9388 .removeRowsAtIndexes_withAnimation(
9389 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9390 NSTableViewAnimationOptions::SlideUp,
9391 ),
9392 day_spec::props::RowDelta::Move(from, to) => {
9393 table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9394 }
9395 }
9396 table.endUpdates();
9397 }
9398 }
9399 if let Some(source) = data.ivars().source.borrow().as_ref() {
9403 let n = (source.len)();
9404 *data.ivars().tokens.borrow_mut() =
9405 (0..n).map(|i| (source.token_at)(i)).collect();
9406 }
9407 }
9408 post_realize_visible_rows(ptr_of(h));
9409 }
9410 Some(ListPatch::Reload) => {
9411 if let Some((table, data)) = list_entry(ptr_of(h)) {
9412 let selected = unsafe { table.selectedRowIndexes() };
9416 let tokens: Vec<u64> = data
9417 .ivars()
9418 .tokens
9419 .borrow()
9420 .iter()
9421 .enumerate()
9422 .filter(|(row, _)| selected.containsIndex(*row))
9423 .map(|(_, token)| *token)
9424 .collect();
9425 data.ivars().suppress.set(true);
9426 if let Some(moves) = data.permutation_moves(&table) {
9433 unsafe {
9434 table.beginUpdates();
9435 for (from, to) in moves {
9436 table.moveRowAtIndex_toIndex(from as isize, to as isize);
9437 }
9438 table.endUpdates();
9439 }
9440 } else {
9441 unsafe { table.reloadData() };
9442 }
9443 let restored = objc2_foundation::NSMutableIndexSet::new();
9444 for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9445 if tokens.contains(token) {
9446 restored.addIndex(row);
9447 }
9448 }
9449 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9450 data.ivars().suppress.set(false);
9451 }
9452 post_realize_visible_rows(ptr_of(h));
9458 }
9459 Some(ListPatch::ScrollToRow(row)) => {
9460 let (key, row) = (ptr_of(h), *row);
9463 <AppKit as Platform>::post(Box::new(move || {
9464 if let Some((table, _)) = list_entry(key) {
9465 let rows = unsafe { table.numberOfRows() };
9466 if rows > 0 {
9467 unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9468 }
9469 }
9470 }));
9471 post_realize_visible_rows(ptr_of(h));
9472 }
9473 Some(ListPatch::ScrollToEnd) => {
9474 let key = ptr_of(h);
9479 <AppKit as Platform>::post(Box::new(move || {
9480 if let Some((table, _)) = list_entry(key) {
9481 let rows = unsafe { table.numberOfRows() };
9482 if rows > 0 {
9483 unsafe { table.scrollRowToVisible(rows - 1) };
9484 }
9485 }
9486 }));
9487 post_realize_visible_rows(ptr_of(h));
9489 }
9490 Some(ListPatch::Selected(rows)) => {
9491 if let Some((table, data)) = list_entry(ptr_of(h)) {
9494 data.ivars().suppress.set(true);
9495 unsafe {
9496 if rows.is_empty() {
9497 table.deselectAll(None);
9498 } else {
9499 let set = objc2_foundation::NSMutableIndexSet::new();
9500 let count = table.numberOfRows().max(0) as usize;
9501 for r in rows.iter().copied().filter(|r| *r < count) {
9502 set.addIndex(r);
9503 }
9504 table.selectRowIndexes_byExtendingSelection(&set, false);
9505 }
9506 }
9507 data.ivars().suppress.set(false);
9508 }
9509 }
9510 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9511 if let Some((table, data)) = list_entry(ptr_of(h)) {
9512 data.row_resized(&table, *cell, *height);
9513 }
9514 }
9515 Some(ListPatch::Editing(_)) | None => {}
9518 },
9519 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9520 Some(TreePatch::Reload) => {
9521 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9526 unsafe { outline.reloadData() };
9527 }
9528 post_realize_visible_tree_rows(ptr_of(h));
9529 }
9530 Some(TreePatch::Expand(token, on)) => {
9531 let (key, token, on) = (ptr_of(h), *token, *on);
9536 <AppKit as Platform>::post(Box::new(move || {
9537 if let Some((outline, data)) = tree_entry(key) {
9538 let item = data.intern(token);
9539 data.ivars().suppress.set(true);
9542 unsafe {
9543 if on {
9544 outline.expandItem(Some(&item));
9545 } else {
9546 outline.collapseItem(Some(&item));
9547 }
9548 }
9549 data.ivars().suppress.set(false);
9550 }
9551 day_core::pump_events();
9552 }));
9553 post_realize_visible_tree_rows(ptr_of(h));
9554 }
9555 Some(TreePatch::Selected(tokens)) => {
9556 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9557 data.ivars().suppress.set(true);
9558 unsafe {
9559 if tokens.is_empty() {
9560 outline.deselectAll(None);
9561 } else {
9562 let set = objc2_foundation::NSMutableIndexSet::new();
9563 for t in tokens {
9564 let row = outline.rowForItem(Some(&data.intern(*t)));
9567 if row >= 0 {
9568 set.addIndex(row as usize);
9569 }
9570 }
9571 outline.selectRowIndexes_byExtendingSelection(&set, false);
9572 }
9573 }
9574 data.ivars().suppress.set(false);
9575 }
9576 }
9577 Some(TreePatch::Reveal(token)) => {
9578 let (key, token) = (ptr_of(h), *token);
9581 <AppKit as Platform>::post(Box::new(move || {
9582 if let Some((outline, data)) = tree_entry(key) {
9583 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9584 if row >= 0 {
9585 unsafe { outline.scrollRowToVisible(row) };
9586 }
9587 }
9588 }));
9589 post_realize_visible_tree_rows(ptr_of(h));
9590 }
9591 None => {}
9592 },
9593 _ => {
9594 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9595 update(self, h, patch);
9596 }
9597 }
9598 }
9599 }
9600
9601 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9603 let f = self.registry.get(kind).and_then(|r| r.release);
9606 if let Some(f) = f {
9607 f(self, h);
9608 }
9609 }
9610 fn release(&mut self, h: Handle) {
9611 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9612 self.secondary.retain(|w| {
9616 if ptr_of(&w.content) == ptr_of(&h) {
9617 w.window.close();
9618 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9622 false
9623 } else {
9624 true
9625 }
9626 });
9627 TARGETS.with(|m| {
9628 m.borrow_mut().remove(&ptr_of(&h));
9629 });
9630 LIST_STATE.with(|m| {
9631 m.borrow_mut().remove(&ptr_of(&h));
9632 });
9633 TREE_STATE.with(|m| {
9634 m.borrow_mut().remove(&ptr_of(&h));
9635 });
9636 GESTURES.with(|m| {
9637 m.borrow_mut().remove(&ptr_of(&h));
9638 });
9639 NAV_STATE.with(|m| {
9640 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9641 unsafe {
9649 nav._split_vc.setNextResponder(None);
9650 let split = nav._split_vc.splitView();
9651 if split.nextResponder().is_some_and(|r| {
9652 core::ptr::eq::<objc2::runtime::AnyObject>(
9653 r.as_ref(),
9654 nav._split_vc.as_ref(),
9655 )
9656 }) {
9657 split.setNextResponder(None);
9658 }
9659 }
9660 }
9661 });
9662 NAV_PAGES.with(|set| {
9663 set.borrow_mut().remove(&ptr_of(&h));
9664 });
9665 SPLIT_STATE.with(|m| {
9666 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9667 state.split.setDelegate(None);
9668 }
9669 });
9670 INSPECTOR_STATE.with(|m| {
9671 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9672 unsafe {
9675 insp._split_vc.setNextResponder(None);
9676 let split = insp._split_vc.splitView();
9677 if split.nextResponder().is_some_and(|r| {
9678 core::ptr::eq::<objc2::runtime::AnyObject>(
9679 r.as_ref(),
9680 insp._split_vc.as_ref(),
9681 )
9682 }) {
9683 split.setNextResponder(None);
9684 }
9685 }
9686 }
9687 });
9688 NAV_MENUS.with(|m| {
9689 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9690 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9695 }
9696 });
9697 day_spec::sidetable::sweep(ptr_of(&h));
9703 unsafe { h.removeFromSuperview() };
9704 }
9705
9706 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9707 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9711 unsafe { content_of(parent).addSubview(child) };
9712 adopt_menu_for_tabs(self.mtm(), child);
9713 return;
9714 }
9715 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9718 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9719 let handled = NAV_STATE.with(|m| {
9720 let mut m = m.borrow_mut();
9721 let Some(state) = m.get_mut(&ptr_of(parent)) else {
9722 return false;
9723 };
9724 if page_pane == Some(day_spec::props::Pane::List)
9727 && let Some(wrap) = state.list_wrap.as_ref()
9728 {
9729 state.list_page = Some(child.clone());
9730 unsafe {
9731 child.setFrame(wrap.bounds());
9732 child.setAutoresizingMask(
9733 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9734 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9735 );
9736 wrap.addSubview(child);
9737 }
9738 return true;
9739 }
9740 if is_sidebar_page {
9741 state.sidebar_page = Some(child.clone());
9742 }
9743 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9749 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9754 state.pages.push(child.clone());
9755 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9756 unsafe {
9757 child.setAutoresizingMask(
9758 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9759 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9760 );
9761 item.setView(Some(child));
9762 tabs.view.addTabViewItem(&item);
9763 }
9764 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
9765 sync_tab_labels(tabs, &titles, state.selected);
9766 }
9767 return true;
9768 }
9769 let (wrap, frame) = if to_pane {
9770 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
9771 } else {
9772 state.pages.push(child.clone());
9773 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
9774 (
9775 &state.detail_wrap,
9776 nav_page_frame(&state.detail_wrap, visible),
9777 )
9778 };
9779 unsafe {
9780 child.setFrame(frame);
9781 child.setAutoresizingMask(
9782 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9783 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9784 );
9785 wrap.addSubview(child);
9786 }
9787 true
9788 });
9789 if handled {
9790 return;
9791 }
9792 let split_pane = SPLIT_STATE.with(|m| {
9795 let m = m.borrow();
9796 let Some(state) = m.get(&ptr_of(parent)) else {
9797 return false;
9798 };
9799 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
9800 let wrap = if second {
9801 &state.second_wrap
9802 } else {
9803 &state.first_wrap
9804 };
9805 unsafe {
9806 child.setFrame(wrap.bounds());
9807 child.setAutoresizingMask(
9808 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9809 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9810 );
9811 wrap.addSubview(child);
9812 }
9813 true
9814 });
9815 if split_pane {
9816 return;
9817 }
9818 let inspected = INSPECTOR_STATE.with(|m| {
9821 let m = m.borrow();
9822 let Some(state) = m.get(&ptr_of(parent)) else {
9823 return false;
9824 };
9825 let panel = INSPECTOR_PANES
9826 .with(|t| t.get(ptr_of(child)))
9827 .unwrap_or(false);
9828 let wrap = if panel {
9829 &state.panel_wrap
9830 } else {
9831 &state.content_wrap
9832 };
9833 unsafe {
9834 child.setFrame(wrap.bounds());
9835 child.setAutoresizingMask(
9836 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9837 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9838 );
9839 wrap.addSubview(child);
9840 }
9841 true
9842 });
9843 if !inspected {
9844 unsafe { content_of(parent).addSubview(child) };
9847 }
9848 }
9849
9850 fn remove(&mut self, parent: &Handle, child: &Handle) {
9851 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
9852 let mtm = self.mtm();
9853 NAV_STATE.with(|m| {
9854 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
9855 if let Some(tabs) = state.tabs.as_ref() {
9857 unsafe {
9858 let n = tabs.view.numberOfTabViewItems();
9859 for i in 0..n {
9860 let item = tabs.view.tabViewItemAtIndex(i);
9861 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
9862 tabs.view.removeTabViewItem(&item);
9863 break;
9864 }
9865 }
9866 }
9867 }
9868 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
9869 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
9870 state.sidebar_page = None;
9871 }
9872 }
9873 });
9874 unsafe { child.removeFromSuperview() };
9875 }
9876
9877 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
9878 unsafe { content_of(parent).addSubview(child) };
9879 }
9880
9881 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
9882 match kind {
9883 kinds::LABEL => {
9884 if let Some(tf) = h.downcast_ref::<NSTextField>() {
9885 let w = p.width.unwrap_or(1.0e6);
9886 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
9888 let mut height = s.height.ceil();
9889 if tf.maximumNumberOfLines() == 1 {
9892 thread_local! {
9893 static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
9894 }
9895 if let Some(font) = unsafe { tf.font() } {
9896 height = height.min(
9897 METRICS
9898 .with(|metrics| metrics.defaultLineHeightForFont(&font))
9899 .ceil(),
9900 );
9901 }
9902 }
9903 return Size::new(s.width.ceil().min(w), height);
9904 }
9905 Size::ZERO
9906 }
9907 kinds::BUTTON | kinds::TOGGLE => {
9908 let s = unsafe { h.fittingSize() };
9909 Size::new(s.width.ceil(), s.height.ceil())
9910 }
9911 kinds::SLIDER => {
9912 let s = unsafe { h.fittingSize() };
9913 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
9914 }
9915 kinds::PICKER => picker::measure_any(self, h, p),
9916 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
9917 kinds::TEXT_FIELD => {
9918 let s = unsafe { h.fittingSize() };
9919 Size::new(
9920 p.width.unwrap_or(s.width.max(160.0)),
9921 s.height.max(22.0).ceil(),
9922 )
9923 }
9924 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
9925 kinds::LIST_ITEM => {
9928 let s = h.fittingSize();
9929 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
9930 }
9931 kinds::PROGRESS => {
9932 let indeterminate = h
9934 .clone()
9935 .downcast::<NSProgressIndicator>()
9936 .map(|pi| unsafe { pi.isIndeterminate() })
9937 .unwrap_or(false);
9938 if indeterminate {
9939 let large = h
9940 .downcast_ref::<NSProgressIndicator>()
9941 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
9942 let side = if large { 32.0 } else { 20.0 };
9943 Size::new(side, side)
9944 } else {
9945 Size::new(p.width.unwrap_or(180.0), 20.0)
9946 }
9947 }
9948 kinds::NAV_MENU => {
9949 let rows = NAV_MENUS.with(|m| {
9950 m.borrow()
9951 .get(&ptr_of(h))
9952 .map(|(_, d)| d.ivars().items.borrow().len())
9953 .unwrap_or(0)
9954 });
9955 Size::new(
9956 p.width.unwrap_or(220.0),
9957 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
9958 )
9959 }
9960 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
9962 _ => {
9963 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
9964 measure(self, h, p)
9965 } else {
9966 let s = unsafe { h.fittingSize() };
9967 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
9968 }
9969 }
9970 }
9971 }
9972
9973 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
9974 unsafe {
9975 h.setWantsLayer(true);
9976 }
9977 let v = h.clone();
9978 with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
9979 }
9980
9981 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
9982 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
9985 let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
9986 let v = h.clone();
9987 with_appkit_anim(anim, move || {
9988 if let Some(base) = base {
9989 apply_geometry(&v, base, t);
9990 }
9991 });
9992 }
9993
9994 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
9995 if let Some(label) = h.downcast_ref::<DayLabel>() {
9996 label.ivars().selectable.set(selectable);
9997 label.set_links(label.ivars().has_links.get());
9998 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
9999 unsafe { tf.setSelectable(selectable) };
10000 }
10001 None
10002 }
10003
10004 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10005 let node = text_field_node(h)?;
10006 let old = h.downcast_ref::<NSTextField>()?;
10007 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10010 .then(|| self.swap_text_field(h, old, node, traits.secure));
10011 let tf = swapped.as_deref().unwrap_or(old);
10012 unsafe {
10013 tf.setEditable(!traits.read_only);
10016 tf.setSelectable(true);
10017 }
10018 let content_type = match traits.purpose {
10022 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10023 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10024 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10025 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10026 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10027 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10028 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10029 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10030 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10031 };
10032 unsafe {
10033 tf.setContentType(content_type);
10034 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10037 }
10038 swapped.map(view_of)
10041 }
10042
10043 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10044 let key = Retained::as_ptr(h) as usize;
10045 if cursor == Cursor::Default {
10046 if let Some((owner, area)) = self.cursors.remove(&key) {
10048 unsafe { h.removeTrackingArea(&area) };
10049 if owner.ivars().hiding.replace(false) {
10050 NSCursor::unhide();
10051 }
10052 }
10053 return;
10054 }
10055 let hidden = cursor == Cursor::None;
10056 let shape = if hidden { None } else { ns_cursor(&cursor) };
10057 let mtm = self.mtm;
10058 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10059 let owner = DayCursorOwner::new(mtm);
10060 let opts = NSTrackingAreaOptions::CursorUpdate
10063 | NSTrackingAreaOptions::MouseEnteredAndExited
10064 | NSTrackingAreaOptions::ActiveInKeyWindow
10065 | NSTrackingAreaOptions::InVisibleRect;
10066 let any: &objc2::runtime::AnyObject = &owner;
10067 let area = unsafe {
10068 NSTrackingArea::initWithRect_options_owner_userInfo(
10069 NSTrackingArea::alloc(),
10070 NSRect::ZERO,
10071 opts,
10072 Some(any),
10073 None,
10074 )
10075 };
10076 unsafe { h.addTrackingArea(&area) };
10077 (owner, area)
10078 });
10079 let changed = {
10080 let iv = owner.ivars();
10081 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10082 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10083 (None, None) => true,
10084 _ => false,
10085 };
10086 *iv.cursor.borrow_mut() = shape;
10087 let was_hidden = iv.hidden.replace(hidden);
10088 !same || was_hidden != hidden
10089 };
10090 if changed && let Some(w) = h.window() {
10093 unsafe { w.invalidateCursorRectsForView(h) };
10094 }
10095 }
10096
10097 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10111 if !day_spec::kind_has_baseline(kind) {
10112 return None;
10113 }
10114 let current = unsafe { h.frame() };
10117 if (current.size.height - size.height).abs() > 0.5 {
10118 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10119 }
10120 let insets = unsafe { h.alignmentRectInsets() };
10121 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10122 let font = h
10123 .downcast_ref::<NSControl>()
10124 .and_then(|c| unsafe { c.font() });
10125 let offset = match font {
10126 Some(_) if kind == kinds::TEXT_AREA => reported,
10129 Some(f) => {
10130 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10131 let line = ascender - descender;
10132 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10133 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10134 }
10135 None => reported,
10136 };
10137 (offset > 0.0 && offset < size.height).then_some(offset)
10139 }
10140
10141 fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10142 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10144 return;
10145 }
10146 let r = NSRect::new(
10149 NSPoint::new(frame.origin.x, frame.origin.y),
10150 NSSize::new(frame.size.width, frame.size.height),
10151 );
10152 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10157 let strip = unsafe { split.superview() }
10161 .and_then(|sup| {
10162 let content = unsafe { sup.window() }?.contentView()?;
10163 let mut ancestor = Some(sup.clone());
10167 while let Some(view) = ancestor {
10168 if std::ptr::eq(&*view, &*content) {
10169 break;
10170 }
10171 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10172 return None; }
10174 ancestor = unsafe { view.superview() };
10175 }
10176 let point = unsafe {
10177 sup.convertPoint_toView(
10178 NSPoint::new(frame.origin.x, frame.origin.y),
10179 Some(&content),
10180 )
10181 };
10182 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10183 })
10184 .unwrap_or(0.0);
10185 let r = NSRect::new(
10186 NSPoint::new(r.origin.x, r.origin.y - strip),
10187 NSSize::new(r.size.width, r.size.height + strip),
10188 );
10189 let wraps = NAV_STATE.with(|m| {
10190 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10191 (s.title_strip != strip).then(|| {
10192 s.title_strip = strip;
10193 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10194 w.extend(s.list_wrap.clone());
10195 w
10196 })
10197 })
10198 });
10199 let first = NAV_STATE.with(|m| {
10200 m.borrow_mut()
10201 .get_mut(&ptr_of(h))
10202 .map(|s| {
10203 if !s.presentation.is_split() {
10204 return (false, None);
10205 }
10206 let sidebar = !std::mem::replace(&mut s.positioned, true);
10207 (sidebar, take_list_placement(s))
10212 })
10213 .unwrap_or((false, None))
10214 });
10215 unsafe {
10216 split.setFrame(r);
10217 split.layoutSubtreeIfNeeded();
10218 }
10219 for wrap in wraps.iter().flatten() {
10222 place_below_strip(wrap, strip);
10223 }
10224 unsafe {
10225 if first.0 {
10226 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10227 }
10228 if let Some(w) = first.1 {
10233 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10234 }
10235 }
10236 } else {
10237 BASE_FRAMES.with(|m| {
10238 m.insert(
10239 ptr_of(h),
10240 [
10241 frame.origin.x,
10242 frame.origin.y,
10243 frame.size.width,
10244 frame.size.height,
10245 ],
10246 )
10247 });
10248 match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10250 Some(t) => apply_geometry(
10251 h,
10252 [
10253 frame.origin.x,
10254 frame.origin.y,
10255 frame.size.width,
10256 frame.size.height,
10257 ],
10258 t,
10259 ),
10260 None => unsafe { h.setFrame(r) },
10261 }
10262 }
10263 }
10264
10265 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10266 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10267 && let Some(doc) = unsafe { sv.documentView() }
10268 {
10269 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10270 }
10271 }
10272
10273 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10275 day_spec::RowMetrics {
10276 insets: day_spec::Insets {
10277 top: 4.0,
10278 leading: 8.0,
10279 bottom: 4.0,
10280 trailing: 8.0,
10281 },
10282 min_height: 28.0,
10283 }
10284 }
10285
10286 fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10287 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10288 && let Some(doc) = unsafe { sv.documentView() }
10289 {
10290 unsafe {
10291 doc.scrollRectToVisible(NSRect::new(
10292 NSPoint::new(target.origin.x, target.origin.y),
10293 NSSize::new(target.size.width, target.size.height),
10294 ))
10295 };
10296 }
10297 }
10298
10299 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10300 let Some(window) = h.window() else { return };
10301 let list = list_entry(ptr_of(h));
10303 let responder: &NSResponder = match &list {
10304 Some((table, _)) => table,
10305 None => h,
10306 };
10307 let responder_ptr = responder as *const NSResponder as usize;
10308 if focused {
10309 window.makeFirstResponder(Some(responder));
10310 return;
10311 }
10312 let owns = window
10315 .firstResponder()
10316 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10317 || owns_first_responder(&window, h);
10318 if owns {
10319 window.makeFirstResponder(None);
10320 }
10321 }
10322
10323 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10324 if focusable {
10327 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10328 } else {
10329 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10330 }
10331 }
10332
10333 fn set_event_sink(&mut self, sink: EventSink) {
10334 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10335 }
10336
10337 fn set_edit_state(&mut self, state: &day_spec::EditState) {
10338 EDIT_STATE.with(|s| s.set(*state));
10339 }
10340
10341 fn modifiers(&mut self) -> day_spec::Modifiers {
10342 let f = NSEvent::modifierFlags_class();
10343 day_spec::Modifiers {
10344 shift: f.contains(NSEventModifierFlags::Shift),
10345 primary: f.contains(NSEventModifierFlags::Command),
10346 alt: f.contains(NSEventModifierFlags::Option),
10347 }
10348 }
10349
10350 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10351 let front = undo_front(self.mtm);
10352 *front.ivars().state.borrow_mut() = state.clone();
10353 }
10354
10355 fn attach_list(&mut self, host: &Handle, source: ListSource) {
10356 let key = ptr_of(host);
10357 if let Some((table, data)) = list_entry(key) {
10358 data.ivars().source.replace(Some(source));
10359 unsafe { table.reloadData() };
10361 }
10362 post_realize_visible_rows(key);
10367 }
10368
10369 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10370 let key = ptr_of(host);
10371 if let Some((outline, data)) = tree_entry(key) {
10372 data.ivars().source.replace(Some(source));
10373 unsafe { outline.reloadData() };
10375 }
10376 <AppKit as Platform>::post(Box::new(move || {
10379 if let Some((outline, _)) = tree_entry(key) {
10380 unsafe { outline.layoutSubtreeIfNeeded() };
10381 }
10382 }));
10383 }
10384
10385 fn adopt(&mut self, raw: RawHandle) -> Handle {
10386 let ptr = raw as *mut NSView;
10390 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10391 }
10392
10393 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10394 self.edit_toolbar(h, ops)
10395 }
10396
10397 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10398 self.patch_toolbar(h, patch);
10399 }
10400
10401 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10402 let mtm = self.mtm;
10403 if self.menu_escape_monitor.is_none() {
10404 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10405 ffi_guard::contain(event.as_ptr(), || {
10406 let event_ref = unsafe { event.as_ref() };
10407 let app = NSApplication::sharedApplication(mtm);
10408 if app.modalWindow().is_none()
10411 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10412 && unsafe { event_ref.charactersIgnoringModifiers() }
10413 .is_some_and(|s| s.to_string() == "\u{1b}")
10414 && app
10415 .mainMenu()
10416 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10417 {
10418 std::ptr::null_mut()
10419 } else {
10420 event.as_ptr()
10421 }
10422 })
10423 });
10424 self.menu_escape_monitor = unsafe {
10425 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10426 objc2_app_kit::NSEventMask::KeyDown,
10427 &block,
10428 )
10429 }
10430 .map(MenuEscapeMonitor);
10431 }
10432 let app = NSApplication::sharedApplication(mtm);
10433 let menubar = NSMenu::new(mtm);
10434 let mut items = items.to_vec();
10437 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10438 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10439 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10440 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10441 let services =
10442 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10443 let items =
10448 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10449 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10450 for item in &items {
10452 match item {
10453 day_spec::MenuItem::Submenu { label, items, role } => {
10454 let sub = build_ns_menu(mtm, label, items);
10455 let it = NSMenuItem::new(mtm);
10456 if *role == Some(day_spec::MenuBarRole::Help)
10460 || *label == day_localization::t(day_localization::key::day_help)
10461 {
10462 help_menu = Some((label.clone(), sub));
10463 continue;
10464 }
10465 it.setTitle(&NSString::from_str(label));
10466 it.setSubmenu(Some(&sub));
10467 menubar.addItem(&it);
10468 }
10469 other => {
10470 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10472 let it = NSMenuItem::new(mtm);
10473 it.setSubmenu(Some(&sub));
10474 menubar.addItem(&it);
10475 }
10476 }
10477 }
10478 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10481 install_windows_menu(mtm, &app, &menubar);
10482 }
10483 if let Some((label, help)) = help_menu {
10484 let it = NSMenuItem::new(mtm);
10485 it.setTitle(&NSString::from_str(&label));
10486 it.setSubmenu(Some(&help));
10487 menubar.addItem(&it);
10488 unsafe { app.setHelpMenu(Some(&help)) };
10491 }
10492 app.setMainMenu(Some(&menubar));
10493 unsafe { app.setServicesMenu(Some(&services)) };
10494 }
10495
10496 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10497 let Some(view) = h.downcast_ref::<NSView>() else {
10498 return;
10499 };
10500 if items.is_empty() {
10501 unsafe { view.setMenu(None) };
10502 return;
10503 }
10504 let menu = build_ns_menu(self.mtm, "", items);
10505 unsafe { view.setMenu(Some(&menu)) };
10511 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10512 for sub in v.subviews() {
10513 unsafe { sub.setMenu(Some(menu)) };
10514 apply_to_subviews(&sub, menu);
10515 }
10516 }
10517 apply_to_subviews(view, &menu);
10518 }
10519
10520 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10521 transfer::source(h, source);
10522 }
10523 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10524 transfer::target(h, target);
10525 }
10526 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10527 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10530 }
10531
10532 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10533 let key = ptr_of(h);
10534 if kind == day_spec::GestureKind::Pan {
10538 PAN_NODES.with(|t| t.insert(key, node));
10539 install_container_pan_monitor();
10540 return;
10541 }
10542 if kind == day_spec::GestureKind::Hover {
10546 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10550 HOVER_NODES.with(|t| t.insert(key, node));
10551 if first {
10552 install_tracking_area(h);
10553 }
10554 return;
10555 }
10556 let already = GESTURES.with(|m| {
10558 m.borrow()
10559 .get(&key)
10560 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10561 });
10562 if already {
10563 return;
10564 }
10565 let mtm = self.mtm;
10566 let target = DayGesture::new(mtm, node, kind);
10567 let recognizer: Retained<NSGestureRecognizer> = unsafe {
10568 match kind {
10569 day_spec::GestureKind::Drag => {
10570 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10571 NSPanGestureRecognizer::alloc(mtm),
10572 Some(&target),
10573 Some(sel!(fire:)),
10574 ))
10575 }
10576 day_spec::GestureKind::Pinch => Retained::into_super(
10577 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10578 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10579 Some(&target),
10580 Some(sel!(fire:)),
10581 ),
10582 ),
10583 _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10584 NSClickGestureRecognizer::alloc(mtm),
10585 Some(&target),
10586 Some(sel!(fire:)),
10587 )),
10588 }
10589 };
10590 unsafe { h.addGestureRecognizer(&recognizer) };
10591 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10592 }
10593
10594 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10595 unsafe {
10596 if let Some(id) = &a11y.identifier {
10597 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10598 }
10599 if let Some(label) = &a11y.label {
10600 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10601 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10602 } else {
10603 APP_LABELED.with(|t| t.remove(ptr_of(h)));
10604 }
10605 if let Some(hint) = &a11y.hint {
10606 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10607 }
10608 if let Some(value) = &a11y.value {
10609 let ns = NSString::from_str(value);
10610 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10611 }
10612 if let Some(role) = ns_role(a11y.role) {
10615 h.setAccessibilityRole(Some(role));
10616 }
10617 if a11y.role == day_spec::Role::Tab {
10618 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10619 }
10620 if let Some(on) = a11y.selected {
10621 h.setAccessibilitySelected(on);
10622 }
10623 if a11y.hidden {
10629 h.setAccessibilityElement(false);
10630 h.setAccessibilityChildren(Some(&NSArray::new()));
10631 }
10632 }
10633 }
10634
10635 fn announce(&mut self, text: &str, urgent: bool) {
10639 use objc2_app_kit::{
10640 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10641 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10642 NSAccessibilityPriorityLevel,
10643 };
10644 let app = NSApplication::sharedApplication(self.mtm());
10645 let window = primary_content().and_then(|content| content.window());
10646 let element: &objc2::runtime::AnyObject = match &window {
10647 Some(window) => window,
10648 None => &app,
10649 };
10650 let priority = if urgent {
10652 NSAccessibilityPriorityLevel::High
10653 } else {
10654 NSAccessibilityPriorityLevel::Medium
10655 };
10656 let announcement = NSString::from_str(text);
10657 let priority = NSNumber::new_isize(priority.0);
10658 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10659 unsafe {
10662 let user_info = NSDictionary::from_slices::<NSString>(
10663 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10664 &values,
10665 );
10666 NSAccessibilityPostNotificationWithUserInfo(
10667 element,
10668 NSAccessibilityAnnouncementRequestedNotification,
10669 Some(&user_info),
10670 );
10671 }
10672 }
10673
10674 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10675 unsafe {
10676 let role = h
10677 .accessibilityRole()
10678 .map(|r| day_role_from_ns(&r.to_string()))
10679 .unwrap_or(day_spec::Role::None);
10680 let picker = picker::read_native(h);
10683 day_spec::NativeSnapshot {
10684 found: true,
10685 role,
10686 label: h.accessibilityLabel().map(|s| s.to_string()),
10687 value: h
10688 .accessibilityValue()
10689 .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10690 identifier: h
10691 .accessibilityIdentifier()
10692 .map(|s| s.to_string())
10693 .filter(|s| !s.is_empty()),
10694 text: match &picker {
10695 Some((text, _)) => text.clone(),
10696 None => native_text(h),
10697 },
10698 number: native_number(h),
10699 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10700 match sw.state() {
10701 s if s == NSControlStateValueOn => Some(true),
10702 s if s == NSControlStateValueOff => Some(false),
10703 _ => None,
10705 }
10706 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10707 BUTTON_SELECTED
10710 .with(|m| m.borrow().contains_key(&ptr_of(h)))
10711 .then(|| btn.state() == NSControlStateValueOn)
10712 } else {
10713 None
10714 },
10715 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10718 (Some((_, on)), _) => *on,
10719 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10720 (None, Some(c)) => Some(c.isEnabled()),
10721 (None, None) => None,
10722 },
10723 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10725 frame: native_frame(h),
10726 }
10727 }
10728 }
10729
10730 fn request_frame(
10731 &mut self,
10732 host: &Handle,
10733 cb: day_spec::FrameCallback,
10734 ) -> day_spec::CancelFrame {
10735 frame::request(host, cb)
10736 }
10737
10738 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10739 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10740 unsafe { h.setNeedsDisplay(true) };
10741 }
10742 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10743 NAV_STATE.with(|m| {
10744 let m = m.borrow();
10745 let Some(st) = m.get(&ptr_of(host)) else {
10746 return false;
10747 };
10748 if !matches!(
10751 st.presentation,
10752 NavPresentation::Split | NavPresentation::Rail
10753 ) {
10754 return false;
10755 }
10756 let item = &st.sidebar_item;
10757 let collapsed = unsafe { item.isCollapsed() };
10763 unsafe { item.setCollapsed(!collapsed) };
10764 true
10765 })
10766 }
10767
10768 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
10769 let content = self.content.as_ref().ok_or("no window content")?;
10770 snapshot_view(content)
10771 }
10772
10773 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
10779 use objc2::AllocAnyThread as _;
10780 let data = NSData::with_bytes(bytes);
10781 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
10782 else {
10783 emit(
10784 WINDOW_NODE,
10785 Event::ImageDecoded {
10786 req,
10787 result: Err(day_spec::ImageError::Decode),
10788 },
10789 );
10790 return;
10791 };
10792 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
10793 let info = day_spec::BitmapInfo {
10794 pixels: Size::new(w, h),
10795 scale: 1.0,
10798 format: day_spec::ImageFormat::sniff(bytes),
10799 has_alpha: unsafe { rep.hasAlpha() },
10800 };
10801 let image = unsafe {
10805 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
10806 };
10807 unsafe { image.addRepresentation(&rep) };
10808 BITMAPS.with(|m| {
10809 m.borrow_mut().insert(
10810 id.0,
10811 AppKitBitmap {
10812 image,
10813 rep: Some(rep),
10814 info,
10815 },
10816 )
10817 });
10818 emit(
10819 WINDOW_NODE,
10820 Event::ImageDecoded {
10821 req,
10822 result: Ok(info),
10823 },
10824 );
10825 }
10826
10827 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
10828 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
10829 }
10830
10831 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
10838 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
10839 let mut out = day_spec::ImageProperties::default();
10840 let size = unsafe { rep.size() };
10841 if size.width > 0.0 {
10842 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
10843 if (dpi - 72.0).abs() > 0.5 {
10846 out.dpi = Some(dpi);
10847 }
10848 }
10849 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
10853 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
10854 for key in keys.iter() {
10855 let value: Option<Retained<objc2::runtime::AnyObject>> =
10856 unsafe { msg_send![&*exif, objectForKey: &*key] };
10857 let Some(value) = value else { continue };
10858 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
10859 let (k, v) = (key.to_string(), text.to_string());
10860 match k.as_str() {
10861 "Orientation" => out.orientation = v.parse().ok(),
10862 "DateTimeOriginal" => out.created = Some(v.clone()),
10863 _ => {}
10864 }
10865 out.extra.push((k, v));
10868 }
10869 }
10870 Some(out)
10871 }
10872
10873 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
10877 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
10878 vec![Png, Jpeg, Tiff, Bmp, Gif]
10879 }
10880
10881 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
10882 let result = encode_bitmap(id, spec);
10883 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
10884 }
10885
10886 fn release_image(&mut self, id: day_spec::BitmapId) {
10887 release_bitmap(id);
10888 }
10889
10890 fn render_bitmap(
10894 &mut self,
10895 req: u64,
10896 id: day_spec::BitmapId,
10897 ops: &[DrawOp],
10898 size: Size,
10899 scale: f64,
10900 ) {
10901 let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
10902 let info = bitmap.info;
10903 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
10904 info
10905 });
10906 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
10907 }
10908
10909 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
10910 let result = render_pdf_bytes(pages, info);
10911 emit(WINDOW_NODE, Event::PdfRendered { req, result });
10912 }
10913
10914 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
10918 use day_spec::FontWeight as W;
10919 let mtm =
10920 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
10921 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
10922 let mut out = Vec::new();
10923 for family in unsafe { manager.availableFontFamilies() }.iter() {
10924 let name = family.to_string();
10925 if name.starts_with('.') {
10926 continue;
10927 }
10928 let mut faces = Vec::new();
10929 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
10930 for member in members.iter() {
10931 if member.count() < 4 {
10932 continue;
10933 }
10934 let style = member
10935 .objectAtIndex(1)
10936 .downcast_ref::<NSString>()
10937 .map(|s| s.to_string())
10938 .unwrap_or_default();
10939 let weight = member
10940 .objectAtIndex(2)
10941 .downcast_ref::<objc2_foundation::NSNumber>()
10942 .map(|n| n.integerValue())
10943 .unwrap_or(5);
10944 let traits = member
10945 .objectAtIndex(3)
10946 .downcast_ref::<objc2_foundation::NSNumber>()
10947 .map(|n| n.integerValue())
10948 .unwrap_or(0);
10949 let weight = match weight {
10950 ..=2 => W::UltraLight,
10951 3 => W::Thin,
10952 4 => W::Light,
10953 5 => W::Regular,
10954 6 => W::Medium,
10955 7 | 8 => W::Semibold,
10956 9 => W::Bold,
10957 10 | 11 => W::Heavy,
10958 _ => W::Black,
10959 };
10960 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
10962 name: if style.is_empty() {
10963 day_spec::FontFace::synthesized_name(weight, italic)
10964 } else {
10965 style
10966 },
10967 weight,
10968 italic,
10969 });
10970 }
10971 }
10972 out.push(day_spec::FontFamilyInfo {
10973 family: name,
10974 faces,
10975 });
10976 }
10977 out
10978 }
10979
10980 fn measure_text(
10983 &mut self,
10984 text: &str,
10985 size: f64,
10986 font: &day_spec::CanvasFont,
10987 ) -> Option<day_spec::TextMetrics> {
10988 let nsfont = canvas_nsfont(size, font);
10989 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
10990 let ns = NSString::from_str(text);
10991 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
10992 let unbounded = NSSize::new(f64::MAX, f64::MAX);
10996 let ink: NSRect = unsafe {
10997 msg_send![
10998 &ns,
10999 boundingRectWithSize: unbounded,
11000 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11001 attributes: &*attrs,
11002 ]
11003 };
11004 Some(day_spec::TextMetrics::from_baseline(
11005 sz.width,
11006 nsfont.ascender(),
11007 sz.height - nsfont.ascender(),
11008 nsfont.capHeight(),
11009 day_spec::Rect::new(
11010 ink.origin.x,
11011 -(ink.origin.y + ink.size.height),
11012 ink.size.width,
11013 ink.size.height,
11014 ),
11015 ))
11016 }
11017
11018 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11019 let content = self.content.as_ref().ok_or("no window content")?;
11020 snapshot_view_chrome(content)
11021 }
11022
11023 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11024 snapshot_view(host)
11025 }
11026
11027 fn open_window(
11028 &mut self,
11029 id: NodeId,
11030 options: &WindowOptions,
11031 kind: day_spec::WindowKind,
11032 ) -> day_spec::WindowOpenReply<Handle> {
11033 let prefs = kind.is_panel();
11034 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11035 if prefs {
11036 window.center();
11039 unsafe { window.setExcludedFromWindowsMenu(true) };
11040 } else {
11041 let from = match self.cascade {
11049 Some(p) => p,
11050 None => self
11051 .window
11052 .as_ref()
11053 .map(|w| {
11054 let f = w.frame();
11055 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
11056 unsafe { w.cascadeTopLeftFromPoint(top_left) }
11059 })
11060 .unwrap_or(NSPoint::new(0.0, 0.0)),
11061 };
11062 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
11063 }
11064 window_chrome::place(&window, options.placement);
11065 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11070 center_on_screen_of(&window, self.window.as_deref());
11071 }
11072 let _ = pin_below_title_bar(&window);
11075 if !options.start_hidden {
11076 window.makeKeyAndOrderFront(None);
11077 }
11078 mark_tree_needs_display(&content);
11081 self.secondary.push(SecondaryWin {
11082 window,
11083 delegate,
11084 content: content.clone(),
11085 });
11086 day_spec::WindowOpenReply::Open(content)
11087 }
11088
11089 fn native_window_tabs(&self) -> bool {
11090 true
11091 }
11092 fn group_windows(&mut self, hosts: &[Handle]) {
11093 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11094 let Some(first) = windows.first() else {
11095 return;
11096 };
11097 unsafe {
11098 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11099 }
11100 for window in windows.iter().skip(1) {
11102 unsafe {
11103 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11104 }
11105 }
11106 if let Some(group) = first.tabGroup() {
11107 if !group.isTabBarVisible() {
11108 unsafe {
11109 first.toggleTabBar(None);
11110 }
11111 }
11112 for (i, window) in windows.iter().enumerate() {
11113 group.insertWindow_atIndex(window, i as isize);
11114 }
11115 }
11116 for window in &windows {
11119 if let Some(size) = pin_below_title_bar(window) {
11120 let node = window
11121 .delegate()
11122 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11123 .and_then(|d| d.ivars().node)
11124 .unwrap_or(WINDOW_NODE);
11125 emit(node, Event::WindowResized(size));
11126 }
11127 }
11128 }
11129 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11130 let Some(window) = self.ns_window_for(host) else {
11131 return Vec::new();
11132 };
11133 let windows = window.tabGroup().map(|g| g.windows());
11134 let Some(windows) = windows else {
11135 return Vec::new();
11136 };
11137 windows
11138 .iter()
11139 .filter_map(|window| {
11140 self.secondary
11141 .iter()
11142 .find(|w| std::ptr::eq(&*w.window, &*window))
11143 .and_then(|w| w.delegate.ivars().node)
11144 })
11145 .collect()
11146 }
11147
11148 fn close_window(&mut self, host: &Handle) {
11149 if let Some(w) = self
11152 .secondary
11153 .iter()
11154 .find(|w| ptr_of(&w.content) == ptr_of(host))
11155 {
11156 w.window.close();
11157 }
11158 }
11159
11160 fn focus_window(&mut self, host: &Handle) {
11161 if let Some(w) = self
11162 .secondary
11163 .iter()
11164 .find(|w| ptr_of(&w.content) == ptr_of(host))
11165 {
11166 w.window.makeKeyAndOrderFront(None);
11167 }
11168 }
11169
11170 fn fit_window(&mut self, host: &Handle, size: Size) {
11171 let Some(w) = self
11172 .secondary
11173 .iter()
11174 .find(|w| ptr_of(&w.content) == ptr_of(host))
11175 else {
11176 return;
11177 };
11178 unsafe {
11179 w.window
11183 .setContentSize(NSSize::new(size.width, size.height));
11184 let mask = w.window.styleMask();
11188 w.window
11189 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11190 w.window.center();
11191 }
11192 center_on_screen_of(&w.window, self.window.as_deref());
11193 }
11194
11195 fn set_window_title(&mut self, host: &Handle, title: &str) {
11196 if let Some(w) = self
11197 .secondary
11198 .iter()
11199 .find(|w| ptr_of(&w.content) == ptr_of(host))
11200 {
11201 w.window.setTitle(&NSString::from_str(title));
11202 return;
11203 }
11204 if self
11208 .content
11209 .as_ref()
11210 .is_some_and(|c| ptr_of(c) == ptr_of(host))
11211 && let Some(w) = self.window.as_ref()
11212 {
11213 w.setTitle(&NSString::from_str(title));
11214 }
11215 }
11216
11217 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11218 use day_spec::WindowChange as C;
11219 let Some(window) = self.ns_window_for(host) else {
11220 return;
11221 };
11222 match change {
11223 C::State(state) => set_ns_window_state(&window, *state),
11224 C::ContentProtected(on) => window.setSharingType(if *on {
11226 objc2_app_kit::NSWindowSharingType::None
11227 } else {
11228 objc2_app_kit::NSWindowSharingType::ReadOnly
11229 }),
11230 other => window_chrome::apply_property(&window, other),
11231 }
11232 }
11233
11234 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11235 self.ns_window_for(host)
11236 .map(|w| window_chrome::frame_of(&w))
11237 }
11238
11239 fn monitors(&self) -> Vec<day_spec::Monitor> {
11240 window_chrome::monitors(self.mtm)
11241 }
11242
11243 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11246
11247 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11248 dock::set_app_items(self.mtm, items);
11249 }
11250
11251 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11252 window_chrome::set_drag_region(h, drag);
11253 }
11254
11255 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11256 status_item::set_items(self.mtm, items);
11257 }
11258
11259 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11260 status_item::set_progress(self.mtm, progress);
11261 }
11262
11263 fn set_dock_visible(&mut self, visible: bool) {
11264 status_item::set_dock_visible(self.mtm, visible);
11265 }
11266
11267 fn set_keep_running(&mut self, keep: bool) {
11268 status_item::set_keep_running(keep);
11269 }
11270
11271 fn quit_app(&mut self) {
11272 let app = NSApplication::sharedApplication(self.mtm);
11273 unsafe { app.terminate(None) };
11274 }
11275
11276 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11277 use present::PresentSpec;
11278 let mtm = self.mtm;
11279 let app = NSApplication::sharedApplication(mtm);
11283 let key = app.keyWindow().filter(|k| {
11284 let mut owner = k.clone();
11285 while let Some(parent) = owner.sheetParent() {
11286 owner = parent;
11287 }
11288 self.window
11289 .as_deref()
11290 .is_some_and(|w| std::ptr::eq(w, &*owner))
11291 || self
11292 .secondary
11293 .iter()
11294 .any(|s| std::ptr::eq(&*s.window, &*owner))
11295 });
11296 let Some(mut window) = key.or_else(|| self.window.clone()) else {
11297 emit(
11298 WINDOW_NODE,
11299 Event::PresentResult {
11300 req,
11301 result: present::PresentResult::Dismissed,
11302 },
11303 );
11304 return;
11305 };
11306 while let Some(sheet) = window.attachedSheet() {
11308 window = sheet;
11309 }
11310 match spec {
11312 PresentSpec::OpenFile {
11313 filters, multiple, ..
11314 } => {
11315 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11316 unsafe {
11317 panel.setCanChooseFiles(true);
11318 panel.setCanChooseDirectories(false);
11319 panel.setAllowsMultipleSelection(*multiple);
11320 panel.setMessage(Some(&NSString::from_str(spec.title())));
11321 }
11322 apply_allowed_file_types(&panel, filters);
11323 let p = panel.clone();
11324 let handler: block2::RcBlock<dyn Fn(isize)> =
11327 block2::RcBlock::new(move |resp: isize| {
11328 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11329 });
11330 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11331 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11332 return;
11333 }
11334 PresentSpec::OpenFolder { .. } => {
11336 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11337 unsafe {
11338 panel.setCanChooseFiles(false);
11339 panel.setCanChooseDirectories(true);
11340 panel.setCanCreateDirectories(true);
11341 panel.setAllowsMultipleSelection(false);
11342 panel.setMessage(Some(&NSString::from_str(spec.title())));
11343 }
11344 let p = panel.clone();
11345 let handler: block2::RcBlock<dyn Fn(isize)> =
11346 block2::RcBlock::new(move |resp: isize| {
11347 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11348 });
11349 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11350 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11351 return;
11352 }
11353 PresentSpec::SaveFile { suggested_name, .. } => {
11354 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11355 unsafe {
11356 panel.setMessage(Some(&NSString::from_str(spec.title())));
11357 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11358 }
11359 apply_allowed_file_types(&panel, spec.filters());
11360 let p = panel.clone();
11361 let handler: block2::RcBlock<dyn Fn(isize)> =
11362 block2::RcBlock::new(move |resp: isize| {
11363 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11365 });
11366 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11367 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11368 return;
11369 }
11370 _ => {}
11371 }
11372 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11373 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11374 if let Some(msg) = spec.message() {
11375 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11376 }
11377 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11379 PresentSpec::Dialog { buttons, .. } => {
11380 if buttons
11381 .iter()
11382 .any(|b| b.role == present::ButtonRole::Destructive)
11383 {
11384 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11385 }
11386 for b in buttons {
11387 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11388 }
11389 block2::RcBlock::new(move |resp: isize| {
11390 ffi_guard::contain((), || {
11391 let idx = resp - 1000;
11393 emit(
11394 WINDOW_NODE,
11395 Event::PresentResult {
11396 req,
11397 result: present::PresentResult::Button(idx as i64),
11398 },
11399 );
11400 PRESENT_ALERTS.with(|m| {
11401 m.borrow_mut().remove(&req);
11402 });
11403 })
11404 })
11405 }
11406 PresentSpec::Prompt {
11407 placeholder,
11408 initial,
11409 ok,
11410 cancel,
11411 ..
11412 } => {
11413 let tf = unsafe { NSTextField::new(mtm) };
11414 unsafe {
11415 tf.setFrame(NSRect::new(
11416 NSPoint::new(0.0, 0.0),
11417 NSSize::new(260.0, 24.0),
11418 ));
11419 tf.setEditable(true);
11420 tf.setBezeled(true);
11421 tf.setStringValue(&NSString::from_str(initial));
11422 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11423 alert.setAccessoryView(Some(&tf));
11424 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
11427 block2::RcBlock::new(move |resp: isize| {
11428 ffi_guard::contain((), || {
11429 let result = if resp == 1000 {
11430 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11431 } else {
11432 present::PresentResult::Dismissed
11433 };
11434 emit(WINDOW_NODE, Event::PresentResult { req, result });
11435 PRESENT_ALERTS.with(|m| {
11436 m.borrow_mut().remove(&req);
11437 });
11438 })
11439 })
11440 }
11441 PresentSpec::OpenFile { .. }
11443 | PresentSpec::OpenFolder { .. }
11444 | PresentSpec::SaveFile { .. } => unreachable!(),
11445 };
11446 unsafe {
11447 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11448 }
11449 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11450 }
11451
11452 fn dismiss(&mut self, req: u64) {
11453 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11456 if let Some(alert) = alert {
11457 let sheet = alert.window();
11458 if let Some(parent) = sheet.sheetParent() {
11459 unsafe { parent.endSheet(&sheet) };
11460 }
11461 }
11462 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11464 if let Some(panel) = panel
11465 && let Some(parent) = panel.sheetParent()
11466 {
11467 unsafe { parent.endSheet(&panel) };
11468 }
11469 }
11470
11471 fn application_handlers(
11472 &mut self,
11473 query: &day_spec::applications::HandlerQuery,
11474 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11475 {
11476 applications::handlers(query)
11477 }
11478
11479 fn open_url_with_application(
11480 &mut self,
11481 url: &str,
11482 application: &str,
11483 completion: day_spec::applications::OpenApplicationCompletion,
11484 ) {
11485 applications::open(url, application, completion);
11486 }
11487
11488 fn share_support(&self) -> day_spec::Support {
11489 day_spec::Support::Native
11490 }
11491 fn share_url(&mut self, url: &str, _title: &str) -> bool {
11492 use objc2::{msg_send, runtime::AnyObject};
11493 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11494 let Some(mtm) = objc2::MainThreadMarker::new() else {
11495 return false;
11496 };
11497 let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11498 return false;
11499 };
11500 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11501 let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11502 return false;
11503 };
11504 unsafe {
11505 let items = NSArray::from_retained_slice(&[url]);
11506 let picker: objc2::rc::Allocated<AnyObject> =
11507 msg_send![objc2::class!(NSSharingServicePicker), alloc];
11508 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11509 let bounds = view.bounds();
11510 let y = if view.isFlipped() {
11511 30.0
11512 } else {
11513 bounds.size.height - 30.0
11514 };
11515 let rect = NSRect::new(
11516 NSPoint::new(bounds.size.width - 30.0, y),
11517 NSSize::new(1.0, 1.0),
11518 );
11519 let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11520 self.sharing = Some(picker);
11521 }
11522 true
11523 }
11524 fn open_url(&mut self, url: &str) {
11525 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11528 if let Some(nsurl) = nsurl {
11529 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11530 }
11531 }
11532}
11533
11534#[allow(deprecated)]
11537fn apply_allowed_file_types(
11538 panel: &objc2_app_kit::NSSavePanel,
11539 filters: &[day_spec::present::FileFilter],
11540) {
11541 let exts: Vec<Retained<NSString>> = filters
11542 .iter()
11543 .flat_map(|f| f.extensions.iter())
11544 .map(|e| NSString::from_str(e))
11545 .collect();
11546 if !exts.is_empty() {
11547 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11548 let arr = objc2_foundation::NSArray::from_slice(&refs);
11549 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11550 }
11551}
11552
11553fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11557 let mut paths = Vec::new();
11558 if resp == 1 {
11559 for url in unsafe { panel.URLs() }.iter() {
11560 if let Some(p) = unsafe { url.path() } {
11561 paths.push(p.to_string());
11562 }
11563 }
11564 }
11565 let result = if paths.is_empty() {
11566 present::PresentResult::Dismissed
11567 } else {
11568 present::PresentResult::Files(paths)
11569 };
11570 emit(WINDOW_NODE, Event::PresentResult { req, result });
11571 PRESENT_PANELS.with(|m| {
11572 m.borrow_mut().remove(&req);
11573 });
11574}
11575
11576fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11578 let result = if resp == 1 {
11579 unsafe { panel.URL() }
11580 .and_then(|url| unsafe { url.path() })
11581 .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11582 .unwrap_or(present::PresentResult::Dismissed)
11583 } else {
11584 present::PresentResult::Dismissed
11585 };
11586 emit(WINDOW_NODE, Event::PresentResult { req, result });
11587 PRESENT_PANELS.with(|m| {
11588 m.borrow_mut().remove(&req);
11589 });
11590}
11591
11592impl Platform for AppKit {
11593 const TARGET: &'static str = "macos-appkit";
11594 const TOOLKIT: &'static str = "appkit";
11595
11596 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11597 let mtm = self.mtm;
11598 self.app_name = options
11602 .app_name
11603 .clone()
11604 .unwrap_or_else(|| options.title.clone());
11605 unsafe {
11614 objc2_foundation::NSProcessInfo::processInfo()
11615 .setProcessName(&NSString::from_str(&self.app_name));
11616 let bundle = objc2_foundation::NSBundle::mainBundle();
11617 let info: Option<Retained<objc2_foundation::NSDictionary>> =
11618 msg_send![&bundle, infoDictionary];
11619 if let Some(info) = info {
11620 let key = NSString::from_str("CFBundleName");
11621 let value = NSString::from_str(&self.app_name);
11622 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11626 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11627 }
11628 }
11629 }
11630 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11635 unsafe {
11636 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11637 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11638 .into_super()
11639 .into_super()
11640 .into_super();
11641 let dict = NSDictionary::from_retained_objects(
11642 &[
11643 &*NSString::from_str("AppleTextDirection"),
11644 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11645 ],
11646 &[yes.clone(), yes],
11647 );
11648 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11649 }
11650 }
11651 let app = NSApplication::sharedApplication(mtm);
11652 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11655 || unsafe {
11656 let bundle = objc2_foundation::NSBundle::mainBundle();
11657 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11658 &bundle,
11659 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11660 ];
11661 value.is_some_and(|v| {
11662 let on: bool = msg_send![&v, boolValue];
11663 on
11664 })
11665 };
11666 app.setActivationPolicy(if menu_bar_app {
11667 NSApplicationActivationPolicy::Accessory
11668 } else {
11669 NSApplicationActivationPolicy::Regular
11670 });
11671 let document_delegate = documents::delegate(mtm);
11672 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11673 if let Ok(theme) = std::env::var("DAY_THEME") {
11676 let name = match theme.as_str() {
11677 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11678 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11679 _ => None,
11680 };
11681 if let Some(name) = name {
11682 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11683 unsafe { app.setAppearance(appearance.as_deref()) };
11684 }
11685 }
11686 register_bundled_fonts();
11688
11689 let app_name = self.app_name.clone();
11693 install_main_menu(mtm, &app, &app_name);
11694 install_lifecycle_observers();
11696 install_appearance_observer();
11697 install_reduce_motion_observer();
11698
11699 let (window, delegate, content) = self.make_window(&options, false, None);
11700 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11704 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11705 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11706 _ => None,
11707 };
11708 if let Some(name) = appearance_name
11709 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11710 {
11711 window.setAppearance(Some(&appearance));
11712 }
11713 std::mem::forget(delegate);
11716
11717 self.window = Some(window.clone());
11718 self.content = Some(content.clone());
11719 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11720
11721 let layout = pin_below_title_bar(&window)
11723 .unwrap_or(Size::new(options.size.width, options.size.height));
11724 ready(self, content, layout);
11725
11726 if day_core::windows::new_window_action_id() == 0
11730 && options.tabbing == day_spec::WindowTabbing::Automatic
11731 {
11732 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11733 }
11734 if !day_core::has_app_menu() {
11739 install_main_menu(mtm, &app, &app_name);
11740 }
11741
11742 let deterministic =
11750 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11751 let autosave = NSString::from_str("day.main");
11752 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11753 window.center();
11754 window_chrome::place(&window, options.placement);
11756 }
11757 if let Some(screen) = capture_screen(mtm) {
11761 let (visible, frame) = (screen.visibleFrame(), window.frame());
11762 window.setFrameOrigin(NSPoint::new(
11763 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11764 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
11765 ));
11766 }
11767 if !deterministic {
11768 unsafe { window.setFrameAutosaveName(&autosave) };
11769 }
11770 if !options.start_hidden {
11771 window.makeKeyAndOrderFront(None);
11772 app.activate();
11773 }
11774 if let Some(content) = window.contentView() {
11779 mark_tree_needs_display(&content);
11780 }
11781 if std::env::var_os("DAY_DUMP").is_some() {
11782 std::thread::spawn(|| {
11783 std::thread::sleep(std::time::Duration::from_millis(2000));
11784 Self::post(Box::new(|| {
11785 if let Some(content) = primary_content() {
11787 let desc: Retained<NSString> =
11788 unsafe { msg_send![&*content, _subtreeDescription] };
11789 log::warn!("{desc}");
11790 }
11791 }));
11792 });
11793 }
11794 app.run();
11795 }
11796
11797 fn post(f: Box<dyn FnOnce() + Send>) {
11798 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
11801 }
11802
11803 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
11804 let when =
11808 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
11809 .unwrap_or(dispatch2::DispatchTime::FOREVER);
11810 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
11811 ffi_guard::contain((), f);
11812 }) {
11813 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
11814 }
11815 }
11816
11817 fn locale_hints(&self) -> Vec<String> {
11818 objc2_foundation::NSLocale::preferredLanguages()
11821 .iter()
11822 .map(|s| s.to_string())
11823 .collect()
11824 }
11825}
11826
11827unsafe extern "C" {
11832 fn CGWindowListCreateImage(
11833 bounds: objc2_core_foundation::CGRect,
11834 list_option: u32,
11835 window_id: u32,
11836 image_option: u32,
11837 ) -> *mut objc2_core_graphics::CGImage;
11838}
11839
11840const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
11843const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
11846
11847fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
11854 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
11855 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
11856 objc2_app_kit::NSColorRenderingIntent::Default,
11857 );
11858 let rep = srgb.as_deref().unwrap_or(rep);
11859 let data = unsafe {
11860 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
11861 }
11862 .ok_or("png encode failed")?;
11863 Ok(data.to_vec())
11864}
11865
11866fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
11879 let window = content.window().ok_or("view is not in a window")?;
11880 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
11883 return snapshot_via_window_server(&sheet, chrome);
11884 }
11885 let number = window.windowNumber();
11886 if number <= 0 {
11887 return Err(format!("window {number} is not on screen"));
11888 }
11889 unsafe { content.layoutSubtreeIfNeeded() };
11896 window.displayIfNeeded();
11897 CATransaction::flush();
11898 let null_rect = objc2_core_foundation::CGRect::new(
11900 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
11901 objc2_core_foundation::CGSize::new(0.0, 0.0),
11902 );
11903 let shot = unsafe {
11904 CGWindowListCreateImage(
11905 null_rect,
11906 CG_WINDOW_LIST_INCLUDING_WINDOW,
11907 number as u32,
11908 CG_WINDOW_IMAGE_IGNORE_FRAMING,
11909 )
11910 };
11911 if shot.is_null() {
11912 return Err("the window server has no image for this window".into());
11913 }
11914 let shot = unsafe {
11917 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
11918 };
11919
11920 if chrome {
11923 let rep = unsafe {
11924 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11925 objc2_app_kit::NSBitmapImageRep::alloc(),
11926 &shot,
11927 )
11928 };
11929 return png_of_rep(&rep);
11930 }
11931
11932 let frame = window.frame();
11936 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
11937 return Err("zero-size window".into());
11938 }
11939 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
11940 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
11943 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
11944 let crop = objc2_core_foundation::CGRect::new(
11945 objc2_core_foundation::CGPoint::new(
11946 (in_window.origin.x * scale).round(),
11947 (from_top * scale).round(),
11948 ),
11949 objc2_core_foundation::CGSize::new(
11950 (in_window.size.width * scale).round(),
11951 (in_window.size.height * scale).round(),
11952 ),
11953 );
11954 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
11955 .ok_or("crop to the content view failed")?;
11956 let rep = unsafe {
11957 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11958 objc2_app_kit::NSBitmapImageRep::alloc(),
11959 &cropped,
11960 )
11961 };
11962 png_of_rep(&rep)
11963}
11964
11965fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
11975 let [x, y, w, h] = base;
11976 let (sw, sh) = (w * t.sx, h * t.sy);
11977 let frame = NSRect::new(
11978 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
11979 NSSize::new(sw, sh),
11980 );
11981 unsafe {
11982 v.setFrameCenterRotation(0.0);
11985 v.setFrame(frame);
11986 v.setBoundsSize(NSSize::new(w, h));
11987 if t.rotate_deg != 0.0 {
11988 v.setFrameCenterRotation(t.rotate_deg);
11989 }
11990 }
11991}
11992
11993fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
11994 let modal = content
11995 .window()
11996 .and_then(|w| w.attachedSheet())
11997 .and_then(|s| s.contentView());
11998 let content = modal.as_deref().unwrap_or(content);
11999 match snapshot_via_window_server(content, false) {
12000 Ok(bytes) => Ok(bytes),
12001 Err(_) => snapshot_view_cache(content),
12002 }
12003}
12004
12005fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12013 let modal = content
12014 .window()
12015 .and_then(|w| w.attachedSheet())
12016 .and_then(|s| s.contentView());
12017 let content = modal.as_deref().unwrap_or(content);
12018 match snapshot_via_window_server(content, true) {
12019 Ok(bytes) => Ok(bytes),
12020 Err(_) => snapshot_view_cache(content),
12021 }
12022}
12023
12024fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12028 let bounds = content.bounds();
12029 let rep =
12030 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12031 let ctx =
12035 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12036 NSGraphicsContext::saveGraphicsState_class();
12037 NSGraphicsContext::setCurrentContext(Some(&ctx));
12038 content
12039 .effectiveAppearance()
12040 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
12041 NSColor::windowBackgroundColor().setFill();
12042 objc2_app_kit::NSRectFill(bounds);
12043 }));
12044 NSGraphicsContext::restoreGraphicsState_class();
12045 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
12046 png_of_rep(&rep)
12047}
12048
12049fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
12055 let Some(screen) = primary.and_then(|w| w.screen()) else {
12056 return;
12057 };
12058 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
12059 return;
12060 }
12061 let (visible, frame) = (screen.visibleFrame(), window.frame());
12062 window.setFrameOrigin(NSPoint::new(
12063 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12064 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
12065 ));
12066}
12067
12068fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12069 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12070 .ok()?
12071 .trim()
12072 .parse()
12073 .ok()?;
12074 let key = NSString::from_str("NSScreenNumber");
12075 objc2_app_kit::NSScreen::screens(mtm)
12076 .into_iter()
12077 .find(|screen| {
12078 let number: Option<Retained<objc2_foundation::NSNumber>> =
12079 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12080 number.is_some_and(|n| n.unsignedIntValue() == wanted)
12081 })
12082}
12083
12084fn mark_tree_needs_display(view: &NSView) {
12086 view.setNeedsDisplay(true);
12087 for sub in view.subviews() {
12088 mark_tree_needs_display(&sub);
12089 }
12090}
12091
12092pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12097 phase.is_universal()
12098}
12099
12100fn install_appearance_observer() {
12106 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12107 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12108 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12109 dispatch2::DispatchQueue::main()
12110 .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12111 });
12112 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12113 let token = unsafe {
12114 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12115 };
12116 std::mem::forget(token);
12117}
12118
12119fn install_reduce_motion_observer() {
12127 use objc2_foundation::NSNotification;
12128 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12129 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12130 dispatch2::DispatchQueue::main()
12131 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12132 });
12133 let token = unsafe {
12134 center.addObserverForName_object_queue_usingBlock(
12135 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12136 None,
12137 None,
12138 &block,
12139 )
12140 };
12141 std::mem::forget(token);
12142}
12143
12144fn install_lifecycle_observers() {
12147 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12148 let center = unsafe { NSNotificationCenter::defaultCenter() };
12149 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12150 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12151 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12152 });
12153 let token = unsafe {
12154 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12155 };
12156 std::mem::forget(token); };
12158 unsafe {
12159 observe(
12160 NSApplicationDidBecomeActiveNotification,
12161 day_spec::Lifecycle::DidBecomeActive,
12162 );
12163 observe(
12164 NSApplicationWillResignActiveNotification,
12165 day_spec::Lifecycle::WillResignActive,
12166 );
12167 observe(
12168 NSApplicationWillTerminateNotification,
12169 day_spec::Lifecycle::WillTerminate,
12170 );
12171 observe(
12175 NSApplicationWillTerminateNotification,
12176 day_spec::Lifecycle::DidExit,
12177 );
12178 }
12179}
12180
12181day_localization_ui::locales!();
12182
12183fn install_application_menu(
12186 mtm: MainThreadMarker,
12187 menubar: &NSMenu,
12188 title: &str,
12189 about: Option<day_spec::MenuItem>,
12190 updates: Option<day_spec::MenuItem>,
12191 prefs: Option<day_spec::MenuItem>,
12192 quit: Option<day_spec::MenuItem>,
12193) -> Retained<NSMenu> {
12194 let app = NSApplication::sharedApplication(mtm);
12195 use day_spec::{MenuItem as M, MenuRole as R};
12196 let standard = |role, label| M::Action {
12197 id: None,
12198 action: 0,
12199 label,
12200 shortcut: None,
12201 enabled: true,
12202 checked: None,
12203 role: Some(role),
12204 icon: None,
12205 };
12206 let mut about =
12207 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12208 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12209 for (item, title) in [
12210 (&mut about, res::str::about_app(title).format()),
12211 (&mut quit, res::str::quit_app(title).format()),
12212 ] {
12213 if let M::Action { label, .. } = item {
12214 *label = title;
12215 }
12216 }
12217 if let M::Action { action, .. } = &mut about
12220 && *action == 0
12221 {
12222 *action = day_core::windows::about_action_id();
12223 }
12224 let updates_id = day_core::windows::check_for_updates_action_id();
12227 let updates = updates.or_else(|| {
12228 (updates_id != 0).then(|| {
12229 standard(
12230 R::CheckForUpdates,
12231 day_localization::t(day_localization::key::day_check_for_updates),
12232 )
12233 })
12234 });
12235 let mut head = vec![about];
12236 if let Some(mut updates) = updates {
12237 if let M::Action { action, .. } = &mut updates
12238 && *action == 0
12239 {
12240 *action = updates_id;
12241 }
12242 head.push(updates);
12243 }
12244 head.push(M::Separator);
12245 let menu = build_ns_menu(mtm, title, &head);
12246 if let Some(mut prefs) = prefs {
12247 if let M::Action { label, .. } = &mut prefs {
12248 *label = res::str::settings().format();
12249 }
12250 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12251 for item in section.itemArray() {
12252 section.removeItem(&item);
12253 menu.addItem(&item);
12254 }
12255 }
12256 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12259 if let Some(parent) = unsafe { services.supermenu() } {
12260 let index = parent.indexOfItemWithSubmenu(Some(&services));
12261 if index >= 0 {
12262 parent.itemAtIndex(index).unwrap().setSubmenu(None);
12263 }
12264 }
12265 let services_item = NSMenuItem::new(mtm);
12266 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12267 services_item.setSubmenu(Some(&services));
12268 menu.addItem(&services_item);
12269 menu.addItem(&NSMenuItem::separatorItem(mtm));
12270 for (label, selector, shortcut) in [
12271 (
12272 res::str::hide_app(title).format(),
12273 sel!(hide:),
12274 Some(day_spec::Shortcut::primary("h")),
12275 ),
12276 (
12277 res::str::hide_others().format(),
12278 sel!(hideOtherApplications:),
12279 Some(day_spec::Shortcut::primary("h").alt()),
12280 ),
12281 (
12282 res::str::show_all().format(),
12283 sel!(unhideAllApplications:),
12284 None,
12285 ),
12286 ] {
12287 let item = unsafe {
12288 NSMenuItem::initWithTitle_action_keyEquivalent(
12289 NSMenuItem::alloc(mtm),
12290 &NSString::from_str(&label),
12291 Some(selector),
12292 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12293 )
12294 };
12295 if let Some(shortcut) = shortcut {
12296 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12297 }
12298 unsafe { item.setTarget(Some(&app)) };
12300 menu.addItem(&item);
12301 }
12302 menu.addItem(&NSMenuItem::separatorItem(mtm));
12303 let section = build_ns_menu(mtm, title, &[quit]);
12304 let quit = section.itemAtIndex(0).unwrap();
12305 section.removeItem(&quit);
12306 menu.addItem(&quit);
12307 let item = NSMenuItem::new(mtm);
12308 item.setSubmenu(Some(&menu));
12309 menubar.addItem(&item);
12310 services
12311}
12312
12313fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12316 let menubar = NSMenu::new(mtm);
12317
12318 let prefs_id = day_core::windows::preferences_action_id();
12319 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12320 id: None,
12321 action: prefs_id,
12322 label: res::str::settings().format(),
12323 shortcut: None,
12324 enabled: true,
12325 checked: None,
12326 role: Some(day_spec::MenuRole::Preferences),
12327 icon: None,
12328 });
12329 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12330
12331 let new_window_id = day_core::windows::new_window_action_id();
12336 if new_window_id != 0 {
12337 let file_item = NSMenuItem::new(mtm);
12338 let file_menu = unsafe {
12339 NSMenu::initWithTitle(
12340 NSMenu::alloc(mtm),
12341 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12342 )
12343 };
12344 let new_window = unsafe {
12345 NSMenuItem::initWithTitle_action_keyEquivalent(
12346 NSMenuItem::alloc(mtm),
12347 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12348 Some(sel!(fire:)),
12349 &NSString::from_str("n"),
12350 )
12351 };
12352 let target = menu_target(mtm);
12353 let tobj: &objc2::runtime::AnyObject = target.as_ref();
12354 unsafe { new_window.setTarget(Some(tobj)) };
12355 new_window.setTag(new_window_id as isize);
12356 file_menu.addItem(&new_window);
12357 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12358 let close = unsafe {
12360 NSMenuItem::initWithTitle_action_keyEquivalent(
12361 NSMenuItem::alloc(mtm),
12362 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12363 Some(sel!(performClose:)),
12364 &NSString::from_str("w"),
12365 )
12366 };
12367 file_menu.addItem(&close);
12368 file_item.setSubmenu(Some(&file_menu));
12369 menubar.addItem(&file_item);
12370 }
12371
12372 let edit_item = NSMenuItem::new(mtm);
12373 let edit_menu = unsafe {
12374 NSMenu::initWithTitle(
12375 NSMenu::alloc(mtm),
12376 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12377 )
12378 };
12379 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12380 let item = unsafe {
12381 NSMenuItem::initWithTitle_action_keyEquivalent(
12382 NSMenuItem::alloc(mtm),
12383 &NSString::from_str(&day_localization::t(key)),
12384 Some(action),
12385 &NSString::from_str(accel),
12386 )
12387 };
12388 edit_menu.addItem(&item);
12389 };
12390 add("day_undo", sel!(undo:), "z");
12391 add("day_redo", sel!(redo:), "Z");
12392 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12393 add("day_cut", sel!(cut:), "x");
12394 add("day_copy", sel!(copy:), "c");
12395 add("day_paste", sel!(paste:), "v");
12396 add("day_select_all", sel!(selectAll:), "a");
12397 edit_item.setSubmenu(Some(&edit_menu));
12398 menubar.addItem(&edit_item);
12399
12400 install_windows_menu(mtm, app, &menubar);
12401
12402 app.setMainMenu(Some(&menubar));
12403 unsafe { app.setServicesMenu(Some(&services)) };
12404}
12405
12406fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12411 let menu = unsafe {
12412 NSMenu::initWithTitle(
12413 NSMenu::alloc(mtm),
12414 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12415 )
12416 };
12417 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12418 let item = unsafe {
12419 NSMenuItem::initWithTitle_action_keyEquivalent(
12420 NSMenuItem::alloc(mtm),
12421 &NSString::from_str(&day_localization::t(key)),
12422 Some(action),
12423 &NSString::from_str(accel),
12424 )
12425 };
12426 menu.addItem(&item);
12427 };
12428 add("day_minimize", sel!(performMiniaturize:), "m");
12429 add("day_zoom", sel!(performZoom:), "");
12430 menu.addItem(&NSMenuItem::separatorItem(mtm));
12431 add("day_bring_all_front", sel!(arrangeInFront:), "");
12432 let item = NSMenuItem::new(mtm);
12433 item.setTitle(&NSString::from_str(&day_localization::t(
12434 day_localization::key::day_window,
12435 )));
12436 item.setSubmenu(Some(&menu));
12437 menubar.addItem(&item);
12438 unsafe { app.setWindowsMenu(Some(&menu)) };
12439}
12440
12441fn extract_app_role(
12444 items: &mut Vec<day_spec::MenuItem>,
12445 role: day_spec::MenuRole,
12446) -> Option<day_spec::MenuItem> {
12447 use day_spec::MenuItem as M;
12448 let mut found = None;
12449 let mut remaining = Vec::new();
12450 for mut item in items.drain(..) {
12451 match &mut item {
12452 M::Action { role: Some(r), .. } if *r == role => {
12453 found.get_or_insert(item);
12454 continue;
12455 }
12456 M::Submenu { items, .. } => {
12457 let nested = extract_app_role(items, role);
12458 if found.is_none() {
12459 found = nested;
12460 }
12461 if items.is_empty() {
12462 continue;
12463 }
12464 }
12465 M::Separator
12466 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12467 {
12468 continue;
12469 }
12470 _ => {}
12471 }
12472 remaining.push(item);
12473 }
12474 while matches!(remaining.last(), Some(M::Separator)) {
12475 remaining.pop();
12476 }
12477 *items = remaining;
12478 found
12479}
12480
12481fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12483 items.iter().any(|it| match it {
12484 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12485 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12486 day_spec::MenuItem::Separator => false,
12487 })
12488}
12489
12490define_class!(
12496 #[unsafe(super(NSObject))]
12497 #[thread_kind = MainThreadOnly]
12498 #[name = "DayMenuTarget"]
12499 #[ivars = ()]
12500 struct DayMenuTarget;
12501
12502 unsafe impl NSObjectProtocol for DayMenuTarget {}
12503
12504 impl DayMenuTarget {
12505 #[unsafe(method(fire:))]
12506 fn fire(&self, sender: &NSMenuItem) {
12507 ffi_guard::contain((), || {
12508 let id = sender.tag() as u64;
12509 if id != 0 {
12510 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12511 }
12512 })
12513 }
12514 }
12515);
12516
12517pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12526 let content = window.contentView()?;
12527 let full = content.frame().size;
12528 let layout = unsafe { window.contentLayoutRect() }.size;
12529 let top = (full.height - layout.height).max(0.0);
12530 if window_chrome::is_overlay(window) {
12534 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12535 window_chrome::report_title_bar_inset(window, top);
12536 return Some(Size::new(full.width, full.height));
12537 }
12538 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12539 Some(Size::new(full.width, (full.height - top).max(0.0)))
12540}
12541
12542fn native_text(h: &NSView) -> Option<String> {
12546 if h.downcast_ref::<NSSecureTextField>().is_some() {
12547 return None;
12548 }
12549 if let Some(tf) = h.downcast_ref::<NSTextField>() {
12550 return Some(tf.stringValue().to_string());
12552 }
12553 if let Some(btn) = h.downcast_ref::<NSButton>() {
12554 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12555 return None;
12556 }
12557 return Some(btn.title().to_string());
12558 }
12559 let sv = h.downcast_ref::<NSScrollView>()?;
12561 let doc = sv.documentView()?;
12562 let tv = doc.downcast_ref::<NSTextView>()?;
12563 Some(tv.string().to_string())
12564}
12565
12566fn native_number(h: &NSView) -> Option<f64> {
12569 if let Some(sl) = h.downcast_ref::<NSSlider>() {
12570 return Some(sl.doubleValue());
12571 }
12572 let pi = h.downcast_ref::<NSProgressIndicator>()?;
12573 (!pi.isIndeterminate()).then(|| pi.doubleValue())
12574}
12575
12576fn native_frame(h: &NSView) -> Option<Rect> {
12580 let content = h.window()?.contentView()?;
12581 let r = h.convertRect_toView(h.bounds(), Some(&content));
12582 let y = if content.isFlipped() {
12583 r.origin.y
12584 } else {
12585 let b = content.bounds();
12586 b.origin.y + b.size.height - (r.origin.y + r.size.height)
12587 };
12588 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12589}
12590
12591fn title_bar_inset(content: &NSView) -> f64 {
12593 (-content.bounds().origin.y).max(0.0)
12594}
12595
12596fn primary_content() -> Option<Retained<NSView>> {
12597 PRIMARY_CONTENT.with(|c| c.borrow().clone())
12598}
12599
12600fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12601 MENU_TARGET.with(|t| {
12602 t.borrow_mut()
12603 .get_or_insert_with(|| {
12604 let this = DayMenuTarget::alloc(mtm).set_ivars(());
12605 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12606 obj
12607 })
12608 .clone()
12609 })
12610}
12611
12612fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12613 use objc2_app_kit::NSEventModifierFlags as F;
12614 let mut m = F::empty();
12615 if s.primary {
12616 m |= F::Command;
12617 }
12618 if s.shift {
12619 m |= F::Shift;
12620 }
12621 if s.alt {
12622 m |= F::Option;
12623 }
12624 if s.control {
12625 m |= F::Control;
12626 }
12627 m
12628}
12629
12630fn ns_key_equivalent(key: &str) -> String {
12633 match key {
12634 "Return" | "Enter" => "\r".into(),
12635 "Tab" => "\t".into(),
12636 "Delete" | "Backspace" => "\u{8}".into(),
12637 "Escape" => "\u{1b}".into(),
12638 "Space" => " ".into(),
12639 k if k.chars().count() == 1 => k.to_lowercase(),
12640 _ => String::new(), }
12642}
12643
12644fn role_spec(
12647 role: day_spec::MenuRole,
12648) -> (
12649 &'static str,
12650 Option<objc2::runtime::Sel>,
12651 Option<day_spec::Shortcut>,
12652) {
12653 use day_spec::MenuRole as R;
12654 use day_spec::Shortcut as S;
12655 match role {
12656 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12657 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12658 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12659 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12660 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12661 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12662 R::Delete => ("Delete", Some(sel!(delete:)), None),
12663 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12664 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12665 R::Preferences => ("Settings…", None, Some(S::primary(","))),
12666 R::Minimize => (
12667 "Minimize",
12668 Some(sel!(performMiniaturize:)),
12669 Some(S::primary("m")),
12670 ),
12671 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12672 R::Fullscreen => (
12673 "Enter Full Screen",
12674 Some(sel!(toggleFullScreen:)),
12675 Some(S::primary("f").control()),
12676 ),
12677 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12680 R::CheckForUpdates => ("Check for Updates…", None, None),
12682 }
12683}
12684
12685pub(crate) fn build_ns_menu(
12686 mtm: MainThreadMarker,
12687 title: &str,
12688 items: &[day_spec::MenuItem],
12689) -> Retained<NSMenu> {
12690 use day_spec::MenuItem as MI;
12691 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12692 let target = menu_target(mtm);
12693 for item in items {
12694 match item {
12695 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12696 MI::Submenu { label, items, .. } => {
12697 let sub = build_ns_menu(mtm, label, items);
12698 let it = NSMenuItem::new(mtm);
12699 it.setTitle(&NSString::from_str(label));
12700 it.setSubmenu(Some(&sub));
12701 menu.addItem(&it);
12702 }
12703 MI::Action {
12704 action,
12705 label,
12706 shortcut,
12707 enabled,
12708 checked,
12709 role,
12710 icon,
12711 ..
12712 } => {
12713 let (mut lbl, sel, mut sc) = match role {
12715 Some(r) => {
12716 let (dl, ds, dsc) = role_spec(*r);
12717 (dl.to_string(), ds, dsc)
12718 }
12719 None => (String::new(), None, None),
12720 };
12721 if !label.is_empty() {
12722 lbl = label.clone();
12723 }
12724 if shortcut.is_some() {
12725 sc = shortcut.clone();
12726 }
12727 let responder_role = matches!(
12733 role,
12734 Some(
12735 day_spec::MenuRole::Undo
12736 | day_spec::MenuRole::Redo
12737 | day_spec::MenuRole::Cut
12738 | day_spec::MenuRole::Copy
12739 | day_spec::MenuRole::Paste
12740 | day_spec::MenuRole::SelectAll
12741 )
12742 );
12743 let custom = *action != 0 && !responder_role;
12744 let key = sc
12745 .as_ref()
12746 .map(|s| ns_key_equivalent(&s.key))
12747 .unwrap_or_default();
12748 let it = unsafe {
12749 NSMenuItem::initWithTitle_action_keyEquivalent(
12750 NSMenuItem::alloc(mtm),
12751 &NSString::from_str(&lbl),
12752 if custom { Some(sel!(fire:)) } else { sel },
12753 &NSString::from_str(&key),
12754 )
12755 };
12756 if let Some(s) = &sc {
12757 it.setKeyEquivalentModifierMask(ns_modifiers(s));
12758 it.setAllowsAutomaticKeyEquivalentLocalization(true);
12764 it.setAllowsAutomaticKeyEquivalentMirroring(true);
12765 }
12766 if custom {
12767 let tobj: &objc2::runtime::AnyObject = target.as_ref();
12768 unsafe { it.setTarget(Some(tobj)) };
12769 it.setTag(*action as isize);
12770 }
12771 it.setEnabled(*enabled);
12772 if let Some(on) = checked {
12775 it.setState(if *on {
12776 NSControlStateValueOn
12777 } else {
12778 NSControlStateValueOff
12779 });
12780 }
12781 if let Some(icon) = icon
12784 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
12785 {
12786 img.setSize(NSSize::new(16.0, 16.0));
12787 it.setImage(Some(&img));
12788 }
12789 menu.addItem(&it);
12790 }
12791 }
12792 }
12793 menu
12794}
12795
12796fn release_bitmap(id: day_spec::BitmapId) {
12799 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
12800}
12801
12802#[cfg(test)]
12803mod bitmap_teardown_tests {
12804 use super::*;
12805
12806 #[test]
12807 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
12808 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
12810 if std::env::var_os(CHILD).is_some() {
12811 struct LateRelease;
12812 impl Drop for LateRelease {
12813 fn drop(&mut self) {
12814 assert!(BITMAPS.try_with(|_| ()).is_err());
12815 release_bitmap(day_spec::BitmapId(1));
12817 }
12818 }
12819 std::thread_local! {
12820 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
12821 }
12822 std::thread::spawn(|| {
12823 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
12824 BITMAPS.with(|_| ()); })
12826 .join()
12827 .unwrap();
12828 return;
12829 }
12830 let output = std::process::Command::new(std::env::current_exe().unwrap())
12831 .args([
12832 "--exact",
12833 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
12834 "--nocapture",
12835 ])
12836 .env(CHILD, "1")
12837 .output()
12838 .unwrap();
12839 assert!(
12840 output.status.success(),
12841 "{}",
12842 String::from_utf8_lossy(&output.stderr)
12843 );
12844 }
12845}