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 PAN_NODES: SideTable<NodeId> = SideTable::new();
148 static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149 static HOVER_NODES: SideTable<NodeId> = SideTable::new();
153 static KEY_NODES: SideTable<NodeId> = SideTable::new();
157 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
162
163 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
165 RefCell::new(HashMap::new());
166
167 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
168 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
170 RefCell::new(std::collections::HashSet::new());
171 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
177
178 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
179 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
182
183 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
185 static SPLIT_PANES: SideTable<bool> = SideTable::new();
187
188 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
192
193 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
194 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
196
197 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
202 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
205
206 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
208
209 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
211 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
212 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
213 const { std::cell::RefCell::new(None) };
214
215 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
217 RefCell::new(HashMap::new());
218 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
220 RefCell::new(HashMap::new());
221
222 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
225 const { std::cell::RefCell::new(None) };
226 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
230 const { std::cell::RefCell::new(None) };
231
232}
233
234pub fn emit(id: NodeId, ev: Event) {
236 let sink = SINK.with(|s| s.borrow().clone());
237 if let Some(sink) = sink {
238 sink(id, ev);
239 }
240}
241
242fn ptr_of(v: &NSView) -> usize {
243 (v as *const NSView).cast::<()>() as usize
244}
245
246#[derive(Clone, Copy)]
248struct ImageMode {
249 template: bool,
250 tinted: bool,
251}
252
253impl ImageMode {
254 fn renders_template(self) -> bool {
257 self.template || self.tinted
258 }
259}
260
261struct AppKitBitmap {
268 image: Retained<objc2_app_kit::NSImage>,
269 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
270 info: day_spec::BitmapInfo,
271}
272
273fn scaled_rep(
279 image: &objc2_app_kit::NSImage,
280 pixels: Size,
281 scale: f64,
282) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
283 use objc2::AllocAnyThread as _;
284 let w = (pixels.width * scale).round().max(1.0);
285 let h = (pixels.height * scale).round().max(1.0);
286 let rep = unsafe {
287 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
288 objc2_app_kit::NSBitmapImageRep::alloc(),
289 std::ptr::null_mut(),
290 w as isize,
291 h as isize,
292 8,
293 4,
294 true,
295 false,
296 objc2_app_kit::NSDeviceRGBColorSpace,
297 0,
298 0,
299 )
300 }?;
301 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
302 NSGraphicsContext::saveGraphicsState_class();
303 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
304 unsafe {
305 image.drawInRect_fromRect_operation_fraction(
306 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
307 NSRect::ZERO,
308 objc2_app_kit::NSCompositingOperation::SourceOver,
309 1.0,
310 );
311 }
312 NSGraphicsContext::restoreGraphicsState_class();
313 Some(rep)
314}
315
316fn encode_bitmap(
321 id: day_spec::BitmapId,
322 spec: &day_spec::EncodeSpec,
323) -> Result<Vec<u8>, day_spec::ImageError> {
324 use day_spec::ImageFormat as F;
325 use objc2_app_kit::NSBitmapImageFileType as T;
326 let file_type = match spec.format {
327 F::Png => T::PNG,
328 F::Jpeg => T::JPEG,
329 F::Tiff => T::TIFF,
330 F::Bmp => T::BMP,
331 F::Gif => T::GIF,
332 _ => return Err(day_spec::ImageError::Encode),
336 };
337 let held = BITMAPS.with(|m| {
338 m.borrow()
339 .get(&id.0)
340 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
341 });
342 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
343 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
344
345 let rep = match spec.fit {
348 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
349 let scale = (fit.width / info.pixels.width)
350 .min(fit.height / info.pixels.height)
351 .min(1.0);
352 if scale < 1.0 {
353 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
354 } else {
355 rep
356 }
357 }
358 _ => rep,
359 };
360
361 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
362 Some(q) => {
364 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
365 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
366 let value: &objc2::runtime::AnyObject = &number;
367 NSDictionary::from_slices::<NSString>(&[key], &[value])
368 }
369 None => NSDictionary::new(),
370 };
371 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
372 .ok_or(day_spec::ImageError::Encode)?;
373 Ok(data.to_vec())
374}
375
376fn paint_ops(ops: &[DrawOp]) {
380 for op in ops {
381 draw_op(op);
382 }
383}
384
385fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
393 use objc2_core_graphics::CGContext;
394 CGContext::save_g_state(Some(cg));
395 CGContext::translate_ctm(Some(cg), 0.0, height);
396 CGContext::scale_ctm(Some(cg), scale, -scale);
397 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
398 NSGraphicsContext::saveGraphicsState_class();
399 NSGraphicsContext::setCurrentContext(Some(&ns));
400 paint_ops(ops);
401 NSGraphicsContext::restoreGraphicsState_class();
402 CGContext::restore_g_state(Some(cg));
403}
404
405fn render_bitmap_image(
413 ops: &[DrawOp],
414 size: Size,
415 scale: f64,
416) -> Result<AppKitBitmap, day_spec::ExportError> {
417 use objc2::AllocAnyThread as _;
418 use objc2_core_graphics::{
419 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
420 };
421 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
422 let (pw, ph) = day_spec::export_pixels(size, scale);
423 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
425 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
426 let cg = unsafe {
429 CGBitmapContextCreate(
430 std::ptr::null_mut(),
431 pw as usize,
432 ph as usize,
433 8,
434 0,
435 Some(&space),
436 CGImageAlphaInfo::PremultipliedLast.0,
437 )
438 }
439 .ok_or_else(|| {
440 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
441 })?;
442 paint_flipped(&cg, ph as f64, scale, ops);
444 let cg_image = CGBitmapContextCreateImage(Some(&cg))
445 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
446 let rep = unsafe {
447 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
448 objc2_app_kit::NSBitmapImageRep::alloc(),
449 &cg_image,
450 )
451 };
452 let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
455 unsafe { rep.setSize(points) };
456 let image =
457 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
458 unsafe { image.addRepresentation(&rep) };
459 Ok(AppKitBitmap {
460 image,
461 rep: Some(rep),
462 info: day_spec::BitmapInfo {
463 pixels: Size::new(pw as f64, ph as f64),
464 scale,
465 format: None,
466 has_alpha: true,
467 },
468 })
469}
470
471fn render_pdf_bytes(
476 pages: &[day_spec::PdfPage],
477 info: &day_spec::PdfInfo,
478) -> Result<Vec<u8>, day_spec::ExportError> {
479 use objc2_core_foundation::{
480 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
481 };
482 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
483 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
484 let media =
485 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
486 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
487 let data = CFMutableData::new(None, 0)
488 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
489 let consumer = CGDataConsumer::with_cf_data(Some(&data))
490 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
491
492 let mut keys: Vec<&CFString> = Vec::new();
493 let mut values: Vec<CFRetained<CFString>> = Vec::new();
494 let (title_key, author_key) = unsafe {
496 (
497 objc2_core_graphics::kCGPDFContextTitle,
498 objc2_core_graphics::kCGPDFContextAuthor,
499 )
500 };
501 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
502 if let Some(value) = value {
503 keys.push(key);
504 values.push(CFString::from_str(value));
505 }
506 }
507 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
508 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
509
510 let first_box = media(first.size);
511 let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
514 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
515 for page in pages {
516 let page_box = media(page.size);
517 unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
519 paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
520 CGContext::end_page(Some(&pdf));
521 }
522 CGPDFContextClose(Some(&pdf));
524 drop(pdf);
525 drop(consumer);
526 Ok(data.to_vec())
527}
528
529thread_local! {
530 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
533 std::cell::RefCell::new(std::collections::HashMap::new());
534}
535
536fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
549 use objc2_app_kit::{
550 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
551 };
552 let label = |text: &str, size: f64, secondary: bool| {
553 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
554 unsafe {
555 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
556 if secondary {
557 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
558 }
559 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
560 }
561 tf
562 };
563 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
564 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
565 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
566 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
567 const STRETCH: f32 = 1.0;
570 const HOLD: f32 = 750.0;
571 let stack = NSStackView::new(mtm);
572 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
573 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
574 stack.setAlignment(NSLayoutAttribute::CenterY);
575 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
576 stack.setSpacing(6.0);
577 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
579 top: 4.0,
580 left: 0.0,
581 bottom: 4.0,
582 right: 0.0,
583 });
584 let icon = unsafe { NSImageView::new(mtm) };
585 unsafe {
586 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
587 icon.widthAnchor()
588 .constraintEqualToConstant(16.0)
589 .setActive(true);
590 icon.heightAnchor()
591 .constraintEqualToConstant(16.0)
592 .setActive(true);
593 }
594 stack.addArrangedSubview(&icon);
595 let texts = NSStackView::new(mtm);
598 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
599 texts.setAlignment(NSLayoutAttribute::Width);
600 texts.setSpacing(1.0);
601 texts.setHuggingPriority_forOrientation(
604 HOLD,
605 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
606 );
607 let title = label("", size, false);
608 let subtitle = label("", small, true);
609 for line in [&title, &subtitle] {
611 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
612 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
613 }
614 texts.addArrangedSubview(&title);
615 texts.addArrangedSubview(&subtitle);
616 stack.addArrangedSubview(&texts);
617 let detail = label("", size, true);
618 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
619 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
620 stack.addArrangedSubview(&detail);
621 let check = unsafe { NSImageView::new(mtm) };
622 unsafe {
623 check.setImage(
624 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
625 &NSString::from_str("checkmark"),
626 None,
627 )
628 .as_deref(),
629 );
630 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
631 }
632 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
633 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
634 stack.addArrangedSubview(&check);
635 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
636 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
637 dress_list_item(&view, p, mtm);
638 view
639}
640
641fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
643 use objc2_app_kit::{NSImageView, NSStackView};
644 let Some(stack) = view.downcast_ref::<NSStackView>() else {
645 return;
646 };
647 let parts = stack.arrangedSubviews();
648 if parts.len() < 4 {
649 return;
650 }
651 let icon = parts.objectAtIndex(0);
652 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
653 let image = p
654 .icon
655 .as_ref()
656 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
657 unsafe {
658 iv.setImage(image.as_deref());
659 iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
660 }
661 }
662 icon.setHidden(p.icon.is_none());
663 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
664 let lines = texts.arrangedSubviews();
665 if lines.len() == 2 {
666 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
667 tf.setStringValue(&NSString::from_str(&p.title));
668 }
669 let sub = lines.objectAtIndex(1);
670 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
671 tf.setStringValue(&NSString::from_str(&p.subtitle));
672 }
673 sub.setHidden(p.subtitle.is_empty());
674 }
675 }
676 let detail = parts.objectAtIndex(2);
677 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
678 tf.setStringValue(&NSString::from_str(&p.detail));
679 }
680 detail.setHidden(p.detail.is_empty());
681 parts.objectAtIndex(3).setHidden(!p.checked);
682 let words = [&p.title, &p.subtitle, &p.detail]
683 .into_iter()
684 .filter(|w| !w.is_empty())
685 .map(String::as_str)
686 .collect::<Vec<_>>()
687 .join(", ");
688 unsafe {
689 view.setAccessibilityElement(true);
690 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
691 view.setAccessibilitySelected(p.checked);
692 }
693}
694
695fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
701 use objc2::AllocAnyThread as _;
702 match source {
703 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
708 .or_else(|| day_spec::resource::resolve_image_file(name))
709 .and_then(|path| unsafe {
710 objc2_app_kit::NSImage::initWithContentsOfFile(
711 objc2_app_kit::NSImage::alloc(),
712 &NSString::from_str(&path.to_string_lossy()),
713 )
714 }),
715 day_spec::ImageSource::Bytes(bytes) => unsafe {
718 objc2_app_kit::NSImage::initWithData(
719 objc2_app_kit::NSImage::alloc(),
720 &NSData::with_bytes(bytes),
721 )
722 },
723 day_spec::ImageSource::Decoded(id) => {
725 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
726 }
727 }
728}
729
730fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
733 use day_spec::Role;
734 use objc2_app_kit::{
735 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
736 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
737 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
738 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
739 };
740 unsafe {
741 Some(match role {
742 Role::Button => NSAccessibilityButtonRole,
743 Role::Toggle => NSAccessibilityCheckBoxRole,
744 Role::Tab => NSAccessibilityRadioButtonRole,
747 Role::TabList => NSAccessibilityTabGroupRole,
748 Role::Slider => NSAccessibilitySliderRole,
749 Role::TextInput => NSAccessibilityTextFieldRole,
750 Role::Heading(_) => NSAccessibilityHeadingRole,
755 Role::Image => NSAccessibilityImageRole,
756 Role::Meter => NSAccessibilityLevelIndicatorRole,
757 Role::Group => NSAccessibilityGroupRole,
758 Role::Tree => NSAccessibilityOutlineRole,
761 Role::TreeItem => NSAccessibilityRowRole,
762 Role::None => return None,
763 })
764 }
765}
766
767fn day_role_from_ns(ax: &str) -> day_spec::Role {
769 use day_spec::Role;
770 match ax {
771 "AXButton" => Role::Button,
772 "AXCheckBox" => Role::Toggle,
773 "AXSlider" => Role::Slider,
774 "AXTextField" => Role::TextInput,
775 "AXStaticText" | "AXHeading" => Role::Heading(0),
778 "AXOutline" => Role::Tree,
779 "AXImage" => Role::Image,
780 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
781 "AXGroup" => Role::Group,
782 "AXRadioButton" => Role::Tab,
783 "AXTabGroup" => Role::TabList,
784 _ => Role::None,
785 }
786}
787
788struct TargetIvars {
793 node: NodeId,
794}
795
796define_class!(
797 #[unsafe(super(NSObject))]
798 #[thread_kind = MainThreadOnly]
799 #[name = "DayTarget"]
800 #[ivars = TargetIvars]
801 struct DayTarget;
802
803 unsafe impl NSObjectProtocol for DayTarget {}
804 unsafe impl NSTextFieldDelegate for DayTarget {}
805
806 unsafe impl NSTabViewDelegate for DayTarget {
811 #[unsafe(method(tabView:didSelectTabViewItem:))]
812 fn tab_view_did_select(
813 &self,
814 tab_view: &objc2_app_kit::NSTabView,
815 item: Option<&objc2_app_kit::NSTabViewItem>,
816 ) {
817 ffi_guard::contain((), || {
818 if TAB_PICK_SUPPRESS.with(|s| s.get()) {
819 return;
820 }
821 if let Some(item) = item {
822 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
823 if idx >= 0 {
824 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
825 }
826 }
827 })
828 }
829 }
830
831 impl DayTarget {
832 #[unsafe(method(action:))]
837 fn action(&self, sender: &NSControl) {
838 ffi_guard::contain((), || {
839 let node = self.ivars().node;
840 if sender.downcast_ref::<NSSwitch>().is_some() {
841 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
842 } else if sender.downcast_ref::<NSSlider>().is_some() {
843 let value = unsafe { sender.doubleValue() };
844 emit(node, Event::ValueChanged(value));
846 if slider_value_settled() {
852 emit(node, Event::ValueCommitted(value));
853 }
854 } else {
855 emit(node, Event::Pressed);
856 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
859 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
860 unsafe {
861 btn.setState(if on {
862 NSControlStateValueOn
863 } else {
864 NSControlStateValueOff
865 })
866 };
867 }
868 }
869 })
870 }
871
872 #[unsafe(method(navBack:))]
875 fn nav_back(&self, _sender: &NSControl) {
876 ffi_guard::contain((), || {
877 emit(
878 self.ivars().node,
879 Event::NavBack {
880 already_popped: false,
881 },
882 );
883 })
884 }
885 }
886
887 unsafe impl NSControlTextEditingDelegate for DayTarget {
888 #[unsafe(method(controlTextDidChange:))]
889 fn control_text_did_change(&self, notification: &NSNotification) {
890 ffi_guard::contain((), || {
891 let node = self.ivars().node;
892 if let Some(obj) = unsafe { notification.object() }
893 && let Ok(tf) = obj.downcast::<NSTextField>() {
894 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
895 }
896 })
897 }
898
899 #[unsafe(method(controlTextDidEndEditing:))]
903 fn control_text_did_end_editing(&self, notification: &NSNotification) {
904 ffi_guard::contain((), || {
905 let node = self.ivars().node;
906 let movement = unsafe { notification.userInfo() }
907 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
908 .and_then(|n| n.downcast::<NSNumber>().ok())
909 .map(|n| NSTextMovement(n.integerValue()))
910 .unwrap_or(NSTextMovement::Other);
911 if movement == NSTextMovement::Return {
912 emit(node, Event::Submitted);
913 } else {
914 emit(node, Event::FocusChanged(false));
915 }
916 })
917 }
918 }
919);
920
921impl DayTarget {
922 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
923 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
924 unsafe { msg_send![super(this), init] }
925 }
926}
927
928struct CursorIvars {
933 cursor: RefCell<Option<Retained<NSCursor>>>,
935 hidden: Cell<bool>,
937 hiding: Cell<bool>,
939}
940
941define_class!(
947 #[unsafe(super(NSObject))]
948 #[thread_kind = MainThreadOnly]
949 #[name = "DayCursorOwner"]
950 #[ivars = CursorIvars]
951 struct DayCursorOwner;
952
953 unsafe impl NSObjectProtocol for DayCursorOwner {}
954
955 impl DayCursorOwner {
956 #[unsafe(method(cursorUpdate:))]
957 fn cursor_update(&self, _event: &NSEvent) {
958 let iv = self.ivars();
959 if iv.hidden.get() {
960 if !iv.hiding.replace(true) {
961 NSCursor::hide();
962 }
963 return;
964 }
965 if let Some(c) = iv.cursor.borrow().as_ref() {
966 c.set();
967 }
968 }
969
970 #[unsafe(method(mouseExited:))]
971 fn mouse_exited(&self, _event: &NSEvent) {
972 if self.ivars().hiding.replace(false) {
973 NSCursor::unhide();
974 }
975 }
976 }
977);
978
979impl DayCursorOwner {
980 fn new(mtm: MainThreadMarker) -> Retained<Self> {
981 let this = Self::alloc(mtm).set_ivars(CursorIvars {
982 cursor: RefCell::new(None),
983 hidden: Cell::new(false),
984 hiding: Cell::new(false),
985 });
986 unsafe { msg_send![super(this), init] }
987 }
988}
989
990#[allow(deprecated)]
998fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
999 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1000 Some(match c {
1001 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1002 Cursor::Pointer => NSCursor::pointingHandCursor(),
1003 Cursor::Text => NSCursor::IBeamCursor(),
1004 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1005 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1006 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1007 Cursor::Grabbing => NSCursor::closedHandCursor(),
1008 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1009 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1010 Cursor::Copy => NSCursor::dragCopyCursor(),
1011 Cursor::Alias => NSCursor::dragLinkCursor(),
1012 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1013 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1014 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1015 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1016 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1017 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1018 NSCursor::frameResizeCursorFromPosition_inDirections(
1019 NSCursorFrameResizePosition::TopRight,
1020 NSCursorFrameResizeDirections::All,
1021 )
1022 }
1023 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1024 NSCursor::frameResizeCursorFromPosition_inDirections(
1025 NSCursorFrameResizePosition::TopLeft,
1026 NSCursorFrameResizeDirections::All,
1027 )
1028 }
1029 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1030 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1031 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1032 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1033 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1034 Cursor::None => return None,
1035 Cursor::Native(name) => match &**name {
1036 "disappearingItem" => NSCursor::disappearingItemCursor(),
1037 "dragCopy" => NSCursor::dragCopyCursor(),
1038 "dragLink" => NSCursor::dragLinkCursor(),
1039 "contextualMenu" => NSCursor::contextualMenuCursor(),
1040 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1041 _ => return None,
1042 },
1043 })
1044}
1045
1046fn slider_value_settled() -> bool {
1053 let Some(mtm) = MainThreadMarker::new() else {
1054 return false;
1055 };
1056 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1057 return false;
1058 };
1059 matches!(
1060 unsafe { event.r#type() },
1061 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1062 )
1063}
1064
1065struct FieldIvars {
1070 node: NodeId,
1071}
1072
1073define_class!(
1074 #[unsafe(super(NSTextField))]
1075 #[thread_kind = MainThreadOnly]
1076 #[name = "DayTextField"]
1077 #[ivars = FieldIvars]
1078 struct DayTextField;
1079
1080 impl DayTextField {
1081 #[unsafe(method(becomeFirstResponder))]
1086 fn become_first_responder(&self) -> bool {
1087 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1088 if ok {
1089 field_gained_focus(self.ivars().node);
1090 }
1091 ok
1092 }
1093 }
1094);
1095
1096impl DayTextField {
1097 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1098 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1099 unsafe { msg_send![super(this), init] }
1100 }
1101}
1102
1103define_class!(
1108 #[unsafe(super(NSSecureTextField))]
1109 #[thread_kind = MainThreadOnly]
1110 #[name = "DaySecureTextField"]
1111 #[ivars = FieldIvars]
1112 struct DaySecureTextField;
1113
1114 impl DaySecureTextField {
1115 #[unsafe(method(becomeFirstResponder))]
1117 fn become_first_responder(&self) -> bool {
1118 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1119 if ok {
1120 field_gained_focus(self.ivars().node);
1121 }
1122 ok
1123 }
1124 }
1125);
1126
1127impl DaySecureTextField {
1128 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1129 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1130 unsafe { msg_send![super(this), init] }
1131 }
1132}
1133
1134thread_local! {
1135 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1138}
1139
1140fn field_gained_focus(node: NodeId) {
1143 if FIELD_SWAP.with(|s| s.get()) {
1144 return;
1145 }
1146 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1149}
1150
1151fn text_field_node(v: &NSView) -> Option<NodeId> {
1154 v.downcast_ref::<DayTextField>()
1155 .map(|f| f.ivars().node)
1156 .or_else(|| {
1157 v.downcast_ref::<DaySecureTextField>()
1158 .map(|f| f.ivars().node)
1159 })
1160}
1161
1162fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1166 let target = DayTarget::new(mtm, node);
1167 let tf: Retained<NSTextField> = if secure {
1170 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1171 } else {
1172 Retained::into_super(DayTextField::new(mtm, node))
1173 };
1174 unsafe {
1175 tf.setEditable(true);
1176 tf.setBezeled(true);
1177 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1178 }
1179 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1180 tf
1181}
1182
1183fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1187 window.firstResponder().is_some_and(|fr| {
1188 if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1189 return true;
1190 }
1191 fr.downcast::<NSText>().is_ok_and(|text| {
1192 unsafe { text.delegate() }
1193 .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1194 })
1195 })
1196}
1197
1198fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1203 unsafe extern "C" {
1204 fn dlsym(
1205 handle: *mut std::ffi::c_void,
1206 symbol: *const std::ffi::c_char,
1207 ) -> *mut std::ffi::c_void;
1208 }
1209 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1211 unsafe {
1215 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1216 if slot.is_null() {
1217 None
1218 } else {
1219 (*slot).as_ref()
1220 }
1221 }
1222}
1223
1224fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1226 if let Some(v) = table.take(old) {
1227 table.insert(new, v);
1228 }
1229}
1230
1231struct LabelIvars {
1236 node: NodeId,
1237 has_links: Cell<bool>,
1238 has_runs: Cell<bool>,
1239 selectable: Cell<bool>,
1240}
1241
1242define_class!(
1243 #[unsafe(super(NSTextField))]
1244 #[thread_kind = MainThreadOnly]
1245 #[name = "DayLabel"]
1246 #[ivars = LabelIvars]
1247 struct DayLabel;
1248
1249 impl DayLabel {
1250 #[unsafe(method_id(menuForEvent:))]
1251 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1252 ffi_guard::contain(None, || {
1253 if !self.isSelectable()
1254 && let Some(menu) = inherited_context_menu(self, event)
1255 {
1256 return menu;
1257 }
1258 unsafe { msg_send![super(self), menuForEvent: event] }
1259 })
1260 }
1261
1262 #[unsafe(method(drawRect:))]
1263 fn draw_rect(&self, dirty: NSRect) {
1264 let mut ancestor = unsafe { self.superview() };
1268 let mut selection_color = None;
1269 if !self.ivars().has_runs.get() {
1270 while let Some(view) = ancestor {
1271 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1272 if unsafe { row.isSelected() } {
1273 selection_color = Some(unsafe {
1274 if row.isEmphasized() {
1275 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1276 } else {
1277 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1278 }
1279 });
1280 }
1281 break;
1282 }
1283 ancestor = unsafe { view.superview() };
1284 }
1285 }
1286 let cell = unsafe { self.cell() }
1287 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1288 if let (Some(color), Some(cell)) = (selection_color, cell) {
1289 let original = unsafe { cell.textColor() };
1290 unsafe {
1293 cell.setTextColor(Some(&color));
1294 let _: () = msg_send![super(self), drawRect: dirty];
1295 cell.setTextColor(original.as_deref());
1296 }
1297 } else {
1298 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1299 }
1300 }
1301 }
1302
1303 unsafe impl NSObjectProtocol for DayLabel {}
1304 unsafe impl NSTextDelegate for DayLabel {}
1305
1306 unsafe impl NSTextViewDelegate for DayLabel {
1307 #[unsafe(method(textView:clickedOnLink:atIndex:))]
1308 fn clicked_on_link(
1309 &self,
1310 _tv: &NSTextView,
1311 link: &objc2::runtime::AnyObject,
1312 _index: usize,
1313 ) -> bool {
1314 ffi_guard::contain(true, || {
1315 let url: Retained<NSString> = unsafe { msg_send![link, description] };
1317 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1318 true })
1320 }
1321 }
1322);
1323
1324impl DayLabel {
1325 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1326 let this = Self::alloc(mtm).set_ivars(LabelIvars {
1327 node,
1328 has_links: Cell::new(false),
1329 has_runs: Cell::new(false),
1330 selectable: Cell::new(false),
1331 });
1332 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1333 unsafe {
1334 this.setStringValue(&NSString::from_str(text));
1335 this.setEditable(false);
1336 this.setSelectable(false);
1337 this.setBordered(false);
1338 this.setBezeled(false);
1339 this.setDrawsBackground(false);
1340 }
1341 this
1342 }
1343
1344 fn set_links(&self, has_links: bool) {
1345 self.ivars().has_links.set(has_links);
1346 unsafe {
1347 self.setSelectable(has_links || self.ivars().selectable.get());
1348 self.setAllowsEditingTextAttributes(has_links);
1349 }
1350 }
1351}
1352
1353struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1354impl Drop for PanMonitor {
1355 fn drop(&mut self) {
1356 unsafe { NSEvent::removeMonitor(&self.0) };
1357 }
1358}
1359
1360fn install_container_pan_monitor() {
1363 PAN_MONITOR.with(|slot| {
1364 if slot.borrow().is_some() {
1365 return;
1366 }
1367 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1368 let event = unsafe { raw.as_ref() };
1369 ffi_guard::contain(raw.as_ptr(), || {
1370 let dx = unsafe { event.scrollingDeltaX() };
1371 let dy = unsafe { event.scrollingDeltaY() };
1372 if dx.abs() <= dy.abs() {
1373 return raw.as_ptr();
1374 }
1375 let Some(mtm) = MainThreadMarker::new() else {
1376 return raw.as_ptr();
1377 };
1378 let Some(window) = event.window(mtm) else {
1379 return raw.as_ptr();
1380 };
1381 let Some(content) = window.contentView() else {
1382 return raw.as_ptr();
1383 };
1384 let point =
1385 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1386 let mut view = content.hitTest(point);
1387 while let Some(v) = view {
1388 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1389 if v.downcast_ref::<DayCanvas>().is_some() {
1390 return raw.as_ptr();
1391 }
1392 let raw_phase = unsafe { event.phase() };
1393 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1394 day_spec::DragPhase::Began
1395 } else if raw_phase.intersects(
1396 objc2_app_kit::NSEventPhase::Ended
1397 | objc2_app_kit::NSEventPhase::Cancelled,
1398 ) {
1399 day_spec::DragPhase::Ended
1400 } else {
1401 day_spec::DragPhase::Changed
1402 };
1403 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1404 emit(
1405 node,
1406 Event::Pan {
1407 phase,
1408 delta: Point::new(dx, dy),
1409 location: Point::new(p.x, p.y),
1410 },
1411 );
1412 return std::ptr::null_mut();
1413 }
1414 view = unsafe { v.superview() };
1415 }
1416 raw.as_ptr()
1417 })
1418 });
1419 *slot.borrow_mut() = unsafe {
1420 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1421 objc2_app_kit::NSEventMask::ScrollWheel,
1422 &block,
1423 )
1424 }
1425 .map(PanMonitor);
1426 });
1427}
1428
1429type Surface = (f64, f64, f64, f64, f64);
1435
1436#[derive(Default)]
1437struct FlippedIvars {
1438 surface: Cell<Option<Surface>>,
1439 section_card: Cell<Option<f64>>,
1442 pane_backdrop: Cell<bool>,
1449}
1450
1451define_class!(
1452 #[unsafe(super(NSView))]
1453 #[thread_kind = MainThreadOnly]
1454 #[name = "DayFlipped"]
1455 #[ivars = FlippedIvars]
1456 struct DayFlipped;
1457
1458 impl DayFlipped {
1459 #[unsafe(method_id(menuForEvent:))]
1460 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1461 ffi_guard::contain(None, || {
1462 inherited_context_menu(self, event)
1463 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1464 })
1465 }
1466
1467 #[unsafe(method(isFlipped))]
1468 fn is_flipped(&self) -> bool {
1469 true
1470 }
1471
1472 #[unsafe(method(acceptsFirstResponder))]
1476 fn accepts_first_responder(&self) -> bool {
1477 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1478 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1479 }
1480
1481 #[unsafe(method(mouseDown:))]
1485 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1486 if transfer::pressed(self, event) { return; }
1487 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1488 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1489 && let Some(window) = self.window()
1490 {
1491 window.makeFirstResponder(Some(self));
1492 }
1493 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1494 }
1495
1496 #[unsafe(method(becomeFirstResponder))]
1497 fn become_first_responder(&self) -> bool {
1498 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1499 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1500 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1501 }
1502 true
1503 }
1504
1505 #[unsafe(method(resignFirstResponder))]
1506 fn resign_first_responder(&self) -> bool {
1507 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1508 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1509 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1510 }
1511 true
1512 }
1513
1514 #[unsafe(method(keyDown:))]
1518 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1519 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1520 let handled = ffi_guard::contain(false, || {
1521 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1522 return false;
1523 };
1524 let Some(key) = key_name(event) else {
1525 return false;
1526 };
1527 if !day_spec::keys::handled(node) {
1528 return false;
1529 }
1530 emit(
1531 node,
1532 Event::Key(day_spec::KeyEvent {
1533 key: key.to_string(),
1534 modifiers: key_modifiers(event.modifierFlags()),
1535 }),
1536 );
1537 true
1538 });
1539 if !handled {
1540 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1541 }
1542 }
1543
1544 #[unsafe(method(rightMouseDown:))]
1548 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1549 if let Some(menu) = self.menuForEvent(event) {
1550 unsafe {
1551 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1552 };
1553 } else {
1554 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1555 }
1556 }
1557
1558 #[unsafe(method(drawRect:))]
1559 fn draw_rect(&self, _dirty: NSRect) {
1560 let paint = || {
1561 if self.ivars().pane_backdrop.get() {
1562 let bounds = self.bounds();
1563 unsafe {
1564 NSColor::windowBackgroundColor().setFill();
1567 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1568 }
1569 }
1570 if let Some(radius) = self.ivars().section_card.get() {
1571 let bounds = self.bounds();
1572 unsafe {
1573 let cls = objc2::class!(NSColor);
1576 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1577 let color: objc2::rc::Retained<NSColor> = if has {
1578 msg_send![cls, quaternarySystemFillColor]
1579 } else {
1580 msg_send![cls, controlBackgroundColor]
1581 };
1582 color.setFill();
1583 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1584 bounds, radius, radius,
1585 );
1586 path.fill();
1587 }
1588 }
1589 if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1590 let bounds = self.bounds();
1591 unsafe {
1592 NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1593 let path = if radius > 0.0 {
1594 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1595 bounds, radius, radius,
1596 )
1597 } else {
1598 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1599 };
1600 path.fill();
1601 }
1602 }
1603 };
1604 unsafe {
1613 let names = objc2_foundation::NSArray::from_slice(&[
1614 objc2_app_kit::NSAppearanceNameAqua,
1615 objc2_app_kit::NSAppearanceNameDarkAqua,
1616 ]);
1617 let standard = self
1618 .effectiveAppearance()
1619 .bestMatchFromAppearancesWithNames(&names)
1620 .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1621 match standard {
1622 Some(appearance) => {
1623 let block = block2::StackBlock::new(paint);
1624 appearance.performAsCurrentDrawingAppearance(&block);
1625 }
1626 None => paint(),
1627 }
1628 }
1629 }
1630 }
1631 unsafe impl NSObjectProtocol for DayFlipped {}
1632 unsafe impl NSDraggingSource for DayFlipped {
1633 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1634 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1635 }
1636 impl DayFlipped {
1637 #[unsafe(method(mouseDragged:))]
1638 fn transfer_dragged(&self, event: &NSEvent) {
1639 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1640 }
1641 #[unsafe(method(draggingEntered:))]
1642 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1643 #[unsafe(method(draggingUpdated:))]
1644 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1645 #[unsafe(method(performDragOperation:))]
1646 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1647 }
1648
1649);
1650
1651impl DayFlipped {
1652 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1653 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1654 unsafe { msg_send![super(this), init] }
1655 }
1656
1657 fn set_section_card(&self, corner_radius: f64) {
1663 self.ivars().section_card.set(Some(corner_radius));
1664 unsafe {
1665 let _: () = msg_send![self, setNeedsDisplay: true];
1666 }
1667 }
1668
1669 fn set_pane_backdrop(&self) {
1671 self.ivars().pane_backdrop.set(true);
1672 unsafe {
1673 let _: () = msg_send![self, setNeedsDisplay: true];
1674 }
1675 }
1676
1677 fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1678 self.ivars()
1679 .surface
1680 .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1681 unsafe {
1682 let _: () = msg_send![self, setNeedsDisplay: true];
1683 if clips || corner_radius > 0.0 {
1684 let _: () = msg_send![self, setWantsLayer: true];
1685 let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1686 if !layer.is_null() {
1687 let _: () = msg_send![layer, setCornerRadius: corner_radius];
1688 let _: () = msg_send![layer, setMasksToBounds: true];
1689 }
1690 }
1691 }
1692 }
1693}
1694
1695struct CanvasIvars;
1700
1701define_class!(
1702 #[unsafe(super(NSView))]
1703 #[thread_kind = MainThreadOnly]
1704 #[name = "DayCanvas"]
1705 #[ivars = CanvasIvars]
1706 struct DayCanvas;
1707
1708 impl DayCanvas {
1709 #[unsafe(method(isFlipped))]
1710 fn is_flipped(&self) -> bool {
1711 true
1712 }
1713
1714 #[unsafe(method_id(menuForEvent:))]
1718 fn menu_for_event(
1719 &self,
1720 event: &objc2_app_kit::NSEvent,
1721 ) -> Option<Retained<NSMenu>> {
1722 let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1723 let Some(f) = f else {
1724 return unsafe { msg_send![super(self), menuForEvent: event] };
1725 };
1726 ffi_guard::contain(None, || {
1728 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1729 let items = f(day_spec::Point::new(p.x, p.y));
1730 if items.is_empty() {
1731 return None;
1732 }
1733 Some(build_ns_menu(self.mtm(), "", &items))
1734 })
1735 }
1736
1737 #[unsafe(method(acceptsFirstResponder))]
1742 fn accepts_first_responder(&self) -> bool {
1743 true
1744 }
1745
1746 #[unsafe(method(mouseDown:))]
1750 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1751 if let Some(window) = self.window() {
1752 window.makeFirstResponder(Some(self));
1753 }
1754 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1755 }
1756
1757 #[unsafe(method(becomeFirstResponder))]
1760 fn become_first_responder(&self) -> bool {
1761 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1762 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1763 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1764 }
1765 true
1766 }
1767
1768 #[unsafe(method(resignFirstResponder))]
1769 fn resign_first_responder(&self) -> bool {
1770 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1771 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1772 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1773 }
1774 true
1775 }
1776
1777 #[unsafe(method(keyDown:))]
1781 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1782 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1783 let handled = ffi_guard::contain(false, || {
1784 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1785 return false;
1786 };
1787 let Some(key) = key_name(event) else {
1788 return false;
1789 };
1790 if !day_spec::keys::handled(node) {
1794 return false;
1795 }
1796 emit(
1797 node,
1798 Event::Key(day_spec::KeyEvent {
1799 key: key.to_string(),
1800 modifiers: key_modifiers(event.modifierFlags()),
1801 }),
1802 );
1803 true
1804 });
1805 if !handled {
1806 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1807 }
1808 }
1809
1810 #[unsafe(method(drawRect:))]
1811 fn draw_rect(&self, _dirty: NSRect) {
1812 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1813 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1814 paint_ops(&ops);
1815 }
1816
1817 #[unsafe(method(mouseEntered:))]
1820 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1821 self.report_hover(event, day_spec::DragPhase::Began);
1822 }
1823
1824 #[unsafe(method(mouseMoved:))]
1825 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1826 self.report_hover(event, day_spec::DragPhase::Changed);
1827 }
1828
1829 #[unsafe(method(mouseExited:))]
1830 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1831 self.report_hover(event, day_spec::DragPhase::Ended);
1832 }
1833
1834 #[unsafe(method(scrollWheel:))]
1835 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1836 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1837 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1838 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1839 return;
1840 };
1841 ffi_guard::contain((), || {
1842 let raw = unsafe { event.phase() };
1845 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1846 day_spec::DragPhase::Began
1847 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1848 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1849 {
1850 day_spec::DragPhase::Ended
1851 } else {
1852 day_spec::DragPhase::Changed
1853 };
1854 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1855 event.scrollingDeltaY()
1856 });
1857 let win = unsafe { event.locationInWindow() };
1858 let loc = self.convertPoint_fromView(win, None);
1859 emit(
1860 node,
1861 Event::Pan {
1862 phase,
1863 delta,
1864 location: Point::new(loc.x, loc.y),
1865 },
1866 );
1867 })
1868 }
1869 }
1870);
1871
1872impl DayCanvas {
1873 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1874 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
1875 unsafe { msg_send![super(this), init] }
1876 }
1877
1878 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
1886 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1887 let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
1888 return;
1889 };
1890 ffi_guard::contain((), || {
1891 let win = unsafe { event.locationInWindow() };
1892 let loc = self.convertPoint_fromView(win, None);
1893 let b = self.bounds();
1894 let inside = loc.x >= b.origin.x
1895 && loc.x <= b.origin.x + b.size.width
1896 && loc.y >= b.origin.y
1897 && loc.y <= b.origin.y + b.size.height;
1898 if !inside && phase != day_spec::DragPhase::Ended {
1901 return;
1902 }
1903 emit(
1904 node,
1905 Event::Hover {
1906 phase,
1907 location: Point::new(loc.x, loc.y),
1908 },
1909 );
1910 });
1911 }
1912}
1913
1914fn install_tracking_area(h: &NSView) {
1918 let opts = NSTrackingAreaOptions::MouseEnteredAndExited
1919 | NSTrackingAreaOptions::MouseMoved
1920 | NSTrackingAreaOptions::ActiveInKeyWindow
1921 | NSTrackingAreaOptions::InVisibleRect;
1922 let any: &objc2::runtime::AnyObject = h;
1923 let area = unsafe {
1924 NSTrackingArea::initWithRect_options_owner_userInfo(
1925 NSTrackingArea::alloc(),
1926 NSRect::ZERO,
1927 opts,
1928 Some(any),
1929 None,
1930 )
1931 };
1932 unsafe { h.addTrackingArea(&area) };
1933}
1934
1935struct GestureIvars {
1940 node: NodeId,
1941 kind: day_spec::GestureKind,
1942}
1943
1944define_class!(
1945 #[unsafe(super(NSObject))]
1946 #[thread_kind = MainThreadOnly]
1947 #[name = "DayGesture"]
1948 #[ivars = GestureIvars]
1949 struct DayGesture;
1950
1951 unsafe impl NSObjectProtocol for DayGesture {}
1952
1953 impl DayGesture {
1954 #[unsafe(method(fire:))]
1955 fn fire(&self, g: &NSGestureRecognizer) {
1956 ffi_guard::contain((), || {
1957 let node = self.ivars().node;
1958 let view = g.view();
1959 let loc = g.locationInView(view.as_deref());
1960 let at = Point::new(loc.x, loc.y);
1961 let phase = match g.state() {
1962 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
1963 NSGestureRecognizerState::Ended
1964 | NSGestureRecognizerState::Cancelled
1965 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
1966 _ => day_spec::DragPhase::Changed,
1967 };
1968 let obj: &objc2::runtime::AnyObject = g.as_ref();
1969 match self.ivars().kind {
1970 day_spec::GestureKind::Drag => {
1971 let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
1972 let t = unsafe { pan.translationInView(view.as_deref()) };
1973 Point::new(t.x, t.y)
1974 } else {
1975 Point::ZERO
1976 };
1977 emit(node, Event::Drag { phase, location: at, translation });
1978 }
1979 day_spec::GestureKind::Pinch => {
1980 let scale = if let Some(m) =
1983 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
1984 {
1985 1.0 + unsafe { m.magnification() }
1986 } else {
1987 1.0
1988 };
1989 emit(node, Event::Pinch { phase, scale, location: at });
1990 }
1991 _ => emit(node, Event::Tap(at)),
1992 }
1993 })
1994 }
1995 }
1996);
1997
1998impl DayGesture {
1999 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2000 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2001 unsafe { msg_send![super(this), init] }
2002 }
2003}
2004
2005struct NavHeader {
2014 bar: Retained<NSView>,
2015 title: Retained<NSTextField>,
2016 titles: Vec<String>,
2018 _target: Retained<DayTarget>,
2019}
2020
2021const NAV_HEADER_H: f64 = 34.0;
2023
2024use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2028
2029fn take_list_placement(state: &mut NavState) -> Option<f64> {
2033 if !state.list_visible || state.list_positioned {
2034 return None;
2035 }
2036 state.list_positioned = true;
2037 state.list_width
2038}
2039
2040const NAV_TABVIEW_INSET: f64 = 12.0;
2043const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2044
2045struct TabHost {
2057 view: Retained<objc2_app_kit::NSTabView>,
2058 target: Option<Retained<DayTarget>>,
2061}
2062
2063thread_local! {
2064 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2067}
2068
2069fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2073 unsafe {
2074 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2075 for (i, title) in titles.iter().enumerate().take(n) {
2076 tabs.view
2077 .tabViewItemAtIndex(i as isize)
2078 .setLabel(&NSString::from_str(title));
2079 }
2080 if n > 0 {
2081 TAB_PICK_SUPPRESS.with(|s| s.set(true));
2082 tabs.view
2083 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2084 TAB_PICK_SUPPRESS.with(|s| s.set(false));
2085 }
2086 }
2087}
2088
2089fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2093 let Some((titles, node)) = NAV_MENUS.with(|m| {
2094 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2095 let ivars = d.ivars();
2096 (
2097 ivars
2098 .items
2099 .borrow()
2100 .iter()
2101 .map(|s| s.to_string())
2102 .collect::<Vec<String>>(),
2103 ivars.node,
2104 )
2105 })
2106 }) else {
2107 return;
2108 };
2109 let mut up = unsafe { menu.superview() };
2110 while let Some(v) = up {
2111 let reached = NAV_STATE.with(|m| {
2112 let mut m = m.borrow_mut();
2113 let Some(s) = m.get_mut(&ptr_of(&v)) else {
2114 return false;
2115 };
2116 let selected = s.selected;
2117 if let Some(tabs) = s.tabs.as_mut() {
2118 if tabs.target.is_none() {
2119 let target = DayTarget::new(mtm, node);
2120 unsafe {
2121 tabs.view
2122 .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2123 };
2124 tabs.target = Some(target);
2125 }
2126 sync_tab_labels(tabs, &titles, selected);
2127 }
2128 true
2129 });
2130 if reached {
2131 return;
2132 }
2133 up = unsafe { v.superview() };
2134 }
2135}
2136
2137struct NavState {
2138 sidebar_wrap: Retained<NSView>,
2139 detail_wrap: Retained<NSView>,
2140 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2145 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2149 list_wrap: Option<Retained<NSView>>,
2155 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2156 list_width: Option<f64>,
2159 list_visible: bool,
2163 list_positioned: bool,
2169 pages: Vec<Retained<NSView>>,
2172 sidebar_page: Option<Retained<NSView>>,
2175 list_page: Option<Retained<NSView>>,
2178 positioned: bool,
2179 presentation: NavPresentation,
2183 selected: usize,
2186 tabs: Option<TabHost>,
2190 header: Option<NavHeader>,
2192 root_title: String,
2195 node: NodeId,
2197 title_strip: f64,
2201}
2202
2203fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2215 let pane = view_of(DayFlipped::new(mtm));
2216 unsafe {
2217 wrap.setFrame(pane.bounds());
2218 wrap.setAutoresizingMask(
2219 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2220 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2221 );
2222 pane.addSubview(wrap);
2223 }
2224 pane
2225}
2226
2227fn place_below_strip(wrap: &NSView, strip: f64) {
2229 let Some(pane) = (unsafe { wrap.superview() }) else {
2230 return;
2231 };
2232 let b = pane.bounds();
2233 unsafe {
2234 wrap.setFrame(NSRect::new(
2235 NSPoint::new(0.0, strip),
2236 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2237 ))
2238 };
2239}
2240
2241fn build_nav_header(
2249 mtm: MainThreadMarker,
2250 id: NodeId,
2251 detail_wrap: &NSView,
2252 root_title: &str,
2253) -> NavHeader {
2254 let bar = view_of(DayFlipped::new(mtm));
2255 let target = DayTarget::new(mtm, id);
2256 let back = unsafe {
2257 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2260 .expect("NSGoBackTemplate");
2261 let tobj: &objc2::runtime::AnyObject = target.as_ref();
2262 objc2_app_kit::NSButton::buttonWithImage_target_action(
2263 &img,
2264 Some(tobj),
2265 Some(sel!(navBack:)),
2266 mtm,
2267 )
2268 };
2269 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2270 unsafe {
2271 back.setFrame(NSRect::new(
2272 NSPoint::new(6.0, 4.0),
2273 NSSize::new(30.0, NAV_HEADER_H - 8.0),
2274 ));
2275 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2276 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2277 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2278 title.setFrame(NSRect::new(
2279 NSPoint::new(44.0, 9.0),
2280 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2281 ));
2282 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2283 bar.setFrame(NSRect::new(
2284 NSPoint::new(0.0, 0.0),
2285 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2286 ));
2287 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2288 bar.addSubview(&back);
2289 bar.addSubview(&title);
2290 bar.setHidden(true);
2291 detail_wrap.addSubview(&bar);
2292 }
2293 NavHeader {
2294 bar,
2295 title,
2296 titles: vec![root_title.to_string()],
2297 _target: target,
2298 }
2299}
2300
2301fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2305 let b = wrap.bounds();
2306 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2307 NSRect::new(
2308 NSPoint::new(0.0, top),
2309 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2310 )
2311}
2312
2313fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2320 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2321 if out.is_some() {
2322 return;
2323 }
2324 let found = NAV_MENUS.with(|m| {
2325 m.borrow()
2326 .get(&(v as *const NSView as usize))
2327 .map(|(_, d)| {
2328 let ivars = d.ivars();
2329 (
2330 ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2331 ivars.node,
2332 )
2333 })
2334 });
2335 if found.is_some() {
2336 *out = found;
2337 return;
2338 }
2339 for sub in unsafe { v.subviews() }.iter() {
2340 walk(&sub, out);
2341 }
2342 }
2343 let mut out = None;
2344 walk(page, &mut out);
2345 out
2346}
2347
2348fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2351 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2352 unsafe {
2353 item.setCanCollapse(shown);
2354 item.setCollapsed(!shown);
2355 match pres {
2356 NavPresentation::Split => {
2357 item.setAllowsFullHeightLayout(true);
2358 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2359 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2360 }
2361 NavPresentation::Rail => {
2367 item.setAllowsFullHeightLayout(true);
2368 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2369 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2370 }
2371 NavPresentation::Stack | NavPresentation::Tabs => {
2374 item.setMinimumThickness(0.0);
2375 item.setMaximumThickness(0.0);
2376 }
2377 }
2378 }
2379}
2380
2381pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2387 NAV_STATE.with(|m| {
2388 m.borrow()
2389 .values()
2390 .find(|st| {
2391 st.list_item.is_some()
2392 && st
2393 .sidebar_wrap
2394 .window()
2395 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2396 })
2397 .map(|st| unsafe { st._split_vc.splitView() })
2398 })
2399}
2400
2401fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2402 let visible = pages.len() >= 2;
2403 hdr.bar.setHidden(!visible);
2404 unsafe {
2405 hdr.title.setStringValue(&NSString::from_str(
2406 hdr.titles.last().map(String::as_str).unwrap_or(""),
2407 ));
2408 }
2409 let frame = nav_page_frame(wrap, visible);
2410 for page in pages {
2411 unsafe { page.setFrame(frame) };
2412 }
2413}
2414
2415fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2430 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2431 NAV_STATE.with(|m| {
2432 let st = m.borrow();
2433 let s = st.get(&ptr_of(host))?;
2434 Some((
2435 s.sidebar_page.clone(),
2436 s.detail_wrap.clone(),
2437 s.sidebar_wrap.clone(),
2438 s.sidebar_item.clone(),
2439 s.presentation,
2440 s.root_title.clone(),
2441 s.node,
2442 s.selected,
2443 ))
2444 })
2445 else {
2446 return;
2447 };
2448 if was == next {
2449 return;
2450 }
2451 apply_sidebar_item(&sidebar_item, next);
2452 NAV_STATE.with(|m| {
2457 if let Some(s) = m.borrow().get(&ptr_of(host)) {
2458 unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2459 }
2460 });
2461 let stacked = next == NavPresentation::Stack;
2464 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2465 if stacked && header.is_none() {
2466 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2467 }
2468 if let Some(hdr) = header.as_ref() {
2469 hdr.bar.setHidden(true);
2470 }
2471 let mut pages = NAV_STATE.with(|m| {
2477 m.borrow()
2478 .get(&ptr_of(host))
2479 .map(|s| s.pages.clone())
2480 .unwrap_or_default()
2481 });
2482 let shown_page = pages.get(sel).cloned();
2483 if let Some(page) = sidebar_page {
2486 pages.retain(|p| ptr_of(p) != ptr_of(&page));
2487 unsafe {
2488 if stacked {
2489 detail_wrap.addSubview(&page);
2490 pages.insert(0, page.clone());
2491 } else {
2492 page.setFrame(sidebar_wrap.bounds());
2493 sidebar_wrap.addSubview(&page);
2494 }
2495 }
2496 page.setHidden(false);
2498 }
2499 let shown = shown_page
2500 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2501 .unwrap_or_else(|| pages.len().saturating_sub(1));
2502 for (i, page) in pages.iter().enumerate() {
2503 page.setHidden(i != shown);
2504 }
2505 NAV_STATE.with(|m| {
2506 let mut m = m.borrow_mut();
2507 if let Some(s) = m.get_mut(&ptr_of(host)) {
2508 s.presentation = next;
2509 s.pages = pages;
2510 s.selected = shown;
2511 s.header = header;
2512 if let Some(hdr) = s.header.as_ref() {
2513 if stacked {
2515 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2516 } else {
2517 hdr.bar.setHidden(true);
2518 }
2519 }
2520 if !stacked {
2521 let frame = nav_page_frame(&s.detail_wrap, false);
2524 for page in &s.pages {
2525 unsafe { page.setFrame(frame) };
2526 }
2527 }
2528 }
2529 });
2530}
2531
2532struct CoverSheet(Retained<NSWindow>);
2541impl Drop for CoverSheet {
2542 fn drop(&mut self) {
2543 let raw = Retained::into_raw(self.0.clone()) as usize;
2546 dispatch2::DispatchQueue::main().exec_async(move || {
2547 ffi_guard::contain((), || unsafe {
2548 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2549 if let Some(parent) = window.sheetParent() {
2550 parent.endSheet(&window);
2551 }
2552 window.orderOut(None);
2553 window.setContentView(None);
2554 });
2555 });
2556 }
2557}
2558struct NavPageIvars {
2559 node: NodeId,
2560 top_inset: Cell<f64>,
2564 sheet: Cell<bool>,
2565 half: Cell<bool>,
2567}
2568
2569define_class!(
2570 #[unsafe(super(NSView))]
2571 #[thread_kind = MainThreadOnly]
2572 #[name = "DayNavPage"]
2573 #[ivars = NavPageIvars]
2574 struct DayNavPage;
2575
2576 impl DayNavPage {
2577 #[unsafe(method(isFlipped))]
2578 fn is_flipped(&self) -> bool {
2579 true
2580 }
2581
2582 #[unsafe(method(setFrameSize:))]
2583 fn set_frame_size(&self, size: NSSize) {
2584 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2585 ffi_guard::contain((), || {
2588 let inset = self.ivars().top_inset.get();
2589 emit(
2590 self.ivars().node,
2591 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2592 );
2593 })
2594 }
2595 }
2596);
2597
2598impl DayNavPage {
2599 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2600 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2601 node,
2602 top_inset: Cell::new(0.0),
2603 sheet: Cell::new(false),
2604 half: Cell::new(false),
2605 });
2606 unsafe { msg_send![super(this), init] }
2607 }
2608}
2609
2610struct InspectorState {
2619 content_wrap: Handle,
2620 panel_wrap: Handle,
2621 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2623 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2624}
2625
2626struct SplitState {
2634 split: Retained<objc2_app_kit::NSSplitView>,
2635 first_wrap: Handle,
2636 second_wrap: Handle,
2637 delegate: Retained<DaySplitDelegate>,
2638}
2639
2640struct SplitDelegateIvars {
2641 node: NodeId,
2642 min_pane: f64,
2643 share: Cell<f64>,
2646 positioned: Cell<bool>,
2648 suppress: Cell<bool>,
2650}
2651
2652define_class!(
2653 #[unsafe(super(NSObject))]
2654 #[thread_kind = MainThreadOnly]
2655 #[name = "DaySplitDelegate"]
2656 #[ivars = SplitDelegateIvars]
2657 struct DaySplitDelegate;
2658
2659 unsafe impl NSObjectProtocol for DaySplitDelegate {}
2660
2661 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2662 #[unsafe(method(splitViewDidResizeSubviews:))]
2663 fn did_resize(&self, notification: &NSNotification) {
2664 ffi_guard::contain((), || {
2665 let Some(obj) = notification.object() else {
2666 return;
2667 };
2668 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2669 return;
2670 };
2671 let iv = self.ivars();
2672 let usable = split_usable(&sv);
2673 if usable <= 0.0 {
2674 return;
2675 }
2676 if !iv.positioned.replace(true) {
2678 split_place(&sv, iv);
2679 return;
2680 }
2681 if iv.suppress.get() {
2682 return;
2683 }
2684 let Some(first) = sv.subviews().iter().next() else {
2685 return;
2686 };
2687 let f = first.frame();
2688 let a = if sv.isVertical() {
2689 f.size.width
2690 } else {
2691 f.size.height
2692 };
2693 let share = (a / usable).clamp(0.0, 1.0);
2694 if (share - iv.share.get()).abs() > 1e-4 {
2695 iv.share.set(share);
2696 emit(iv.node, Event::ValueChanged(share));
2697 }
2698 })
2699 }
2700
2701 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2702 fn constrain_min(
2703 &self,
2704 _sv: &objc2_app_kit::NSSplitView,
2705 proposed: f64,
2706 _index: isize,
2707 ) -> f64 {
2708 proposed.max(self.ivars().min_pane)
2709 }
2710
2711 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2712 fn constrain_max(
2713 &self,
2714 sv: &objc2_app_kit::NSSplitView,
2715 proposed: f64,
2716 _index: isize,
2717 ) -> f64 {
2718 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2719 }
2720 }
2721);
2722
2723impl DaySplitDelegate {
2724 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2725 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2726 node,
2727 min_pane,
2728 share: Cell::new(share.clamp(0.0, 1.0)),
2729 positioned: Cell::new(false),
2730 suppress: Cell::new(false),
2731 });
2732 unsafe { msg_send![super(this), init] }
2733 }
2734}
2735
2736fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2738 let frame = sv.frame();
2739 let len = if sv.isVertical() {
2740 frame.size.width
2741 } else {
2742 frame.size.height
2743 };
2744 (len - sv.dividerThickness()).max(0.0)
2745}
2746
2747fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2749 let usable = split_usable(sv);
2750 if usable <= 0.0 {
2751 return;
2752 }
2753 iv.suppress.set(true);
2754 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2755 iv.suppress.set(false);
2756}
2757
2758struct NavMenuIvars {
2765 node: NodeId,
2766 items: RefCell<Vec<Retained<NSString>>>,
2767 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2771 icon_fills: RefCell<Vec<f64>>,
2774 tints: RefCell<Vec<Option<day_spec::Color>>>,
2777 badges: RefCell<Vec<Option<Retained<NSString>>>>,
2779 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2782 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2783 badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2785 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2788 movable: RefCell<Vec<bool>>,
2790 regroup: std::cell::Cell<bool>,
2792 sorted: RefCell<Vec<bool>>,
2794 rows: RefCell<Vec<Option<usize>>>,
2798 row_objects: RefCell<Vec<Retained<NSString>>>,
2800 row_ids: RefCell<Vec<Retained<NSNumber>>>,
2805 suppress: std::cell::Cell<bool>,
2807}
2808
2809struct NavCellIvars {
2810 accessory: RefCell<Option<Retained<NSView>>>,
2813 count: RefCell<Option<Retained<NSTextField>>>,
2815 icon_fill: std::cell::Cell<f64>,
2817}
2818
2819define_class!(
2820 #[unsafe(super(objc2_app_kit::NSTableCellView))]
2825 #[thread_kind = MainThreadOnly]
2826 #[name = "DayNavCell"]
2827 #[ivars = NavCellIvars]
2828 struct DayNavCell;
2829
2830 unsafe impl NSObjectProtocol for DayNavCell {}
2831
2832 impl DayNavCell {
2833 #[unsafe(method(layout))]
2834 fn layout(&self) {
2835 let _: () = unsafe { msg_send![super(self), layout] };
2836 ffi_guard::contain((), || self.fit_accessories());
2837 }
2838 }
2839);
2840
2841impl DayNavCell {
2842 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2843 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
2844 accessory: RefCell::new(None),
2845 count: RefCell::new(None),
2846 icon_fill: std::cell::Cell::new(1.0),
2847 });
2848 unsafe { msg_send![super(this), init] }
2849 }
2850
2851 fn fit_accessories(&self) {
2856 let label = unsafe { self.textField() };
2857 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
2858 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
2859 (f.pointSize() - 2.0).max(9.0)
2860 });
2861 if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
2862 unsafe {
2863 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
2864 size,
2865 objc2_app_kit::NSFontWeightRegular,
2866 )));
2867 }
2868 self.layoutSubtreeIfNeeded();
2869 }
2870 }
2871 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
2872 let mut frame = label.frame();
2873 let end = accessory.frame().origin.x - 6.0;
2874 if frame.origin.x + frame.size.width > end {
2875 frame.size.width = (end - frame.origin.x).max(0.0);
2876 label.setFrame(frame);
2877 }
2878 }
2879 if let Some(icon) = unsafe { self.imageView() } {
2880 fit_nav_icon(&icon, self.ivars().icon_fill.get());
2881 nav_progress::fit(&icon);
2882 }
2883 }
2884}
2885
2886thread_local! {
2887 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
2889}
2890
2891fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
2900 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
2901 return;
2902 };
2903 let slot = icon.frame();
2904 let key = config.hash() as u64;
2907 let side = NAV_GLYPH_SIDES
2908 .with(|m| m.borrow().get(&key).copied())
2909 .or_else(|| {
2910 let symbol =
2911 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
2912 &NSString::from_str("gearshape"),
2913 None,
2914 )?;
2915 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
2916 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
2917 Some(side)
2918 });
2919 let Some(side) = side
2922 .filter(|s| *s > 0.0)
2923 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
2924 else {
2925 return;
2926 };
2927 if slot.size.width <= side && slot.size.height <= side {
2928 return;
2929 }
2930 icon.setFrame(NSRect::new(
2931 NSPoint::new(
2932 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
2933 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
2934 ),
2935 NSSize::new(side, side),
2936 ));
2937}
2938
2939define_class!(
2940 #[unsafe(super(objc2_app_kit::NSTableRowView))]
2941 #[thread_kind = MainThreadOnly]
2942 #[name = "DayNavRowView"]
2943 struct DayNavRowView;
2944
2945 unsafe impl NSObjectProtocol for DayNavRowView {}
2946
2947 impl DayNavRowView {
2948 #[unsafe(method(isEmphasized))]
2954 fn is_emphasized(&self) -> bool {
2955 true
2956 }
2957 }
2958);
2959
2960define_class!(
2961 #[unsafe(super(objc2_app_kit::NSOutlineView))]
2962 #[thread_kind = MainThreadOnly]
2963 #[name = "DayNavOutlineView"]
2964 struct DayNavOutlineView;
2965
2966 unsafe impl NSObjectProtocol for DayNavOutlineView {}
2967
2968 impl DayNavOutlineView {
2969 #[unsafe(method_id(menuForEvent:))]
2973 fn menu_for_event(
2974 &self,
2975 event: &objc2_app_kit::NSEvent,
2976 ) -> Option<Retained<NSMenu>> {
2977 ffi_guard::contain(None, || {
2978 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2979 let row = unsafe { self.rowAtPoint(point) };
2980 let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
2981 match data {
2983 None => None,
2984 Some(d) => {
2985 let items = d
2986 .item_of_row(row)
2987 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
2988 .unwrap_or_default();
2989 if items.is_empty() {
2990 None
2991 } else {
2992 Some(build_ns_menu(d.mtm(), "", &items))
2993 }
2994 }
2995 }
2996 })
2997 }
2998 }
2999);
3000
3001define_class!(
3002 #[unsafe(super(NSObject))]
3003 #[thread_kind = MainThreadOnly]
3004 #[name = "DayNavMenuData"]
3005 #[ivars = NavMenuIvars]
3006 struct DayNavMenuData;
3007
3008 unsafe impl NSObjectProtocol for DayNavMenuData {}
3009
3010 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3011 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3012 fn number_of_children(
3013 &self,
3014 _ov: &objc2_app_kit::NSOutlineView,
3015 item: Option<&objc2::runtime::AnyObject>,
3016 ) -> isize {
3017 if item.is_none() {
3018 self.ivars().row_objects.borrow().len() as isize
3019 } else {
3020 0
3021 }
3022 }
3023
3024 #[unsafe(method_id(outlineView:child:ofItem:))]
3025 fn child_of_item(
3026 &self,
3027 _ov: &objc2_app_kit::NSOutlineView,
3028 index: isize,
3029 _item: Option<&objc2::runtime::AnyObject>,
3030 ) -> Retained<objc2::runtime::AnyObject> {
3031 let ids = self.ivars().row_ids.borrow();
3032 let id = ids
3036 .get(index as usize)
3037 .cloned()
3038 .unwrap_or_else(|| NSNumber::new_isize(-1));
3039 unsafe { objc2::rc::Retained::cast_unchecked(id) }
3040 }
3041
3042 #[unsafe(method(outlineView:isItemExpandable:))]
3043 fn is_expandable(
3044 &self,
3045 _ov: &objc2_app_kit::NSOutlineView,
3046 _item: &objc2::runtime::AnyObject,
3047 ) -> bool {
3048 false
3049 }
3050
3051 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3058 fn pasteboard_writer_for_item(
3059 &self,
3060 _ov: &objc2_app_kit::NSOutlineView,
3061 item: &objc2::runtime::AnyObject,
3062 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3063 let make = || {
3064 let row = Self::outline_row(item);
3065 let index = self.item_of_row(row)?;
3066 if !self.is_movable(index) {
3067 return None;
3068 }
3069 let pbitem = objc2_app_kit::NSPasteboardItem::new();
3070 unsafe {
3071 pbitem.setString_forType(
3072 &NSString::from_str(&row.to_string()),
3073 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3074 );
3075 }
3076 Some(ProtocolObject::from_retained(pbitem))
3077 };
3078 ffi_guard::contain(None, make)
3079 }
3080
3081 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3082 fn validate_drop(
3083 &self,
3084 ov: &objc2_app_kit::NSOutlineView,
3085 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3086 item: Option<&objc2::runtime::AnyObject>,
3087 child_index: isize,
3088 ) -> objc2_app_kit::NSDragOperation {
3089 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3090 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3091 return objc2_app_kit::NSDragOperation::None;
3092 };
3093 if drop.retarget {
3095 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3096 }
3097 objc2_app_kit::NSDragOperation::Move
3098 })
3099 }
3100
3101 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3102 fn accept_drop(
3103 &self,
3104 ov: &objc2_app_kit::NSOutlineView,
3105 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3106 item: Option<&objc2::runtime::AnyObject>,
3107 child_index: isize,
3108 ) -> bool {
3109 ffi_guard::contain(false, || {
3110 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3111 return false;
3112 };
3113 match drop.moves {
3116 Some(NavMove::Reorder { from, to }) => {
3117 emit(self.ivars().node, Event::ListReorder { from, to });
3118 }
3119 Some(NavMove::Regroup {
3120 from,
3121 section,
3122 before,
3123 }) => emit(
3124 self.ivars().node,
3125 Event::NavRegroup {
3126 from,
3127 section,
3128 before,
3129 },
3130 ),
3131 None => {}
3132 }
3133 true
3134 })
3135 }
3136 }
3137
3138 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3139
3140 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3141 #[unsafe(method(outlineView:isGroupItem:))]
3144 fn is_group_item(
3145 &self,
3146 _ov: &objc2_app_kit::NSOutlineView,
3147 item: &objc2::runtime::AnyObject,
3148 ) -> bool {
3149 let row = Self::outline_row(item);
3150 row >= 0 && self.item_of_row(row).is_none()
3151 }
3152
3153 #[unsafe(method(outlineView:shouldSelectItem:))]
3154 fn should_select(
3155 &self,
3156 _ov: &objc2_app_kit::NSOutlineView,
3157 item: &objc2::runtime::AnyObject,
3158 ) -> bool {
3159 self.item_of_row(Self::outline_row(item)).is_some()
3160 }
3161
3162 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3163 fn view_for(
3164 &self,
3165 ov: &objc2_app_kit::NSOutlineView,
3166 _col: Option<&objc2_app_kit::NSTableColumn>,
3167 item: &objc2::runtime::AnyObject,
3168 ) -> Option<Retained<NSView>> {
3169 let mtm = self.mtm();
3170 let row = Self::outline_row(item);
3171 let text = self
3172 .ivars()
3173 .row_objects
3174 .borrow()
3175 .get(usize::try_from(row).unwrap_or(usize::MAX))
3176 .cloned();
3177 text.map(|text| {
3179 let text: &NSString = &text;
3180 let Some(index) = self.item_of_row(row) else {
3181 let cell = DayNavCell::new(mtm);
3184 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3185 unsafe {
3186 label.cell().inspect(|c| {
3187 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3188 });
3189 cell.addSubview(&label);
3190 cell.setTextField(Some(&label));
3191 }
3192 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3193 };
3194 let icon = self
3195 .ivars()
3196 .icons
3197 .borrow()
3198 .get(index)
3199 .and_then(|o| o.clone());
3200 let badge = self
3201 .ivars()
3202 .badges
3203 .borrow()
3204 .get(index)
3205 .and_then(|o| o.clone());
3206 let badge_icon = self
3207 .ivars()
3208 .badge_icons
3209 .borrow()
3210 .get(index)
3211 .and_then(|o| o.clone());
3212 let badge_tint = self
3213 .ivars()
3214 .badge_tints
3215 .borrow()
3216 .get(index)
3217 .copied()
3218 .flatten();
3219 let cell = DayNavCell::new(mtm);
3223 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3224 unsafe {
3225 label.cell().inspect(|c| {
3228 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3229 });
3230 cell.addSubview(&label);
3231 cell.setTextField(Some(&label));
3232 let accessory = objc2_app_kit::NSStackView::new(mtm);
3239 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3240 accessory.setOrientation(
3241 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3242 );
3243 accessory.setSpacing(4.0);
3244 let mut has_accessory = false;
3245 let trailing: Retained<NSView> = match &badge {
3246 Some(text) => {
3247 let b = NSTextField::labelWithString(text, mtm);
3248 b.setTranslatesAutoresizingMaskIntoConstraints(false);
3249 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3250 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3251 b.setFont(Some(
3252 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3253 objc2_app_kit::NSFont::smallSystemFontSize(),
3254 objc2_app_kit::NSFontWeightRegular,
3255 ),
3256 ));
3257 b.setContentCompressionResistancePriority_forOrientation(
3258 objc2_app_kit::NSLayoutPriorityRequired,
3259 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3260 );
3261 *cell.ivars().count.borrow_mut() = Some(b.clone());
3262 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3263 objc2::rc::Retained::into_super(b),
3264 ));
3265 has_accessory = true;
3266 let v: Retained<NSView> =
3267 objc2::rc::Retained::into_super(accessory.clone());
3268 v
3269 }
3270 None => objc2::rc::Retained::into_super(accessory.clone()),
3271 };
3272 if let Some(img) = &badge_icon {
3277 let iv = objc2_app_kit::NSImageView::new(mtm);
3278 iv.setImage(Some(img));
3279 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3280 if let Some(c) = badge_tint {
3281 iv.setContentTintColor(Some(&nscolor(c)));
3282 }
3283 iv.setContentCompressionResistancePriority_forOrientation(
3284 objc2_app_kit::NSLayoutPriorityRequired,
3285 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3286 );
3287 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3288 has_accessory = true;
3289 }
3290 cell.addSubview(&trailing);
3291 if has_accessory {
3292 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3293 }
3294 objc2_app_kit::NSLayoutConstraint::activateConstraints(
3295 &objc2_foundation::NSArray::from_retained_slice(&[
3296 trailing
3297 .trailingAnchor()
3298 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3299 trailing
3300 .centerYAnchor()
3301 .constraintEqualToAnchor(&cell.centerYAnchor()),
3302 ]),
3303 );
3304 }
3305 if let Some(img) = icon {
3306 let fill = self.ivars().icon_fills.borrow().get(index).copied();
3307 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3308 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3309 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3310 unsafe {
3311 iv.setImage(Some(&img));
3312 if let Some(t) = tint {
3315 iv.setContentTintColor(Some(&nscolor(t)));
3316 }
3317 iv.setImageScaling(
3318 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3319 );
3320 cell.addSubview(&iv);
3321 cell.setImageView(Some(&iv));
3322 let progress = self
3323 .ivars()
3324 .icon_progress
3325 .borrow()
3326 .iter()
3327 .find(|(row, _)| *row == index)
3328 .map(|(_, f)| *f);
3329 nav_progress::update(&iv, progress);
3330 }
3331 }
3332 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3333 })
3334 }
3335
3336 #[unsafe(method_id(outlineView:rowViewForItem:))]
3337 fn row_view_for(
3338 &self,
3339 _ov: &objc2_app_kit::NSOutlineView,
3340 _item: &objc2::runtime::AnyObject,
3341 ) -> Retained<objc2_app_kit::NSTableRowView> {
3342 let row: Retained<DayNavRowView> =
3343 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3344 objc2::rc::Retained::into_super(row)
3345 }
3346
3347 #[unsafe(method(outlineViewSelectionDidChange:))]
3348 fn selection_did_change(&self, notification: &NSNotification) {
3349 ffi_guard::contain((), || {
3350 if self.ivars().suppress.get() {
3351 return;
3352 }
3353 let Some(obj) = (unsafe { notification.object() }) else {
3354 return;
3355 };
3356 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3357 return;
3358 };
3359 let row = unsafe { ov.selectedRow() };
3360 if let Some(item) = self.item_of_row(row) {
3361 emit(self.ivars().node, Event::SelectionChanged(item as i64));
3362 }
3363 })
3364 }
3365 }
3366);
3367
3368thread_local! {
3369 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3372}
3373
3374fn nav_icon_fills(
3376 names: &[Option<String>],
3377 images: &[Option<Retained<objc2_app_kit::NSImage>>],
3378) -> Vec<f64> {
3379 names
3380 .iter()
3381 .zip(images)
3382 .map(|(name, image)| match (name, image) {
3383 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3384 *m.borrow_mut()
3385 .entry(name.clone())
3386 .or_insert_with(|| nav_icon_fill(image))
3387 }),
3388 _ => 1.0,
3389 })
3390 .collect()
3391}
3392
3393fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3398 const PX: f64 = 64.0;
3399 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3400 return 1.0;
3401 };
3402 let (w, h) = (
3403 rep.pixelsWide().max(0) as usize,
3404 rep.pixelsHigh().max(0) as usize,
3405 );
3406 let stride = rep.bytesPerRow().max(0) as usize;
3407 let data = unsafe { rep.bitmapData() };
3408 if data.is_null() || stride < w * 4 {
3409 return 1.0;
3410 }
3411 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3414 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3415 for y in 0..h {
3416 for x in 0..w {
3417 if bytes[y * stride + x * 4 + 3] > 24 {
3418 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3419 }
3420 }
3421 }
3422 if x1 <= x0 || y1 <= y0 {
3423 return 1.0;
3424 }
3425 let size = image.size();
3428 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3429 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3430 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3431}
3432
3433fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3434 icons
3436 .iter()
3437 .map(|ic| {
3438 let name = ic.as_deref()?;
3439 let path = day_spec::resource::resolve_vector_svg(name)
3441 .or_else(|| day_spec::resource::resolve_image_file(name))?;
3442 use objc2::AllocAnyThread as _;
3443 let img = unsafe {
3444 objc2_app_kit::NSImage::initWithContentsOfFile(
3445 objc2_app_kit::NSImage::alloc(),
3446 &NSString::from_str(&path.to_string_lossy()),
3447 )
3448 }?;
3449 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3451 Some(img)
3452 })
3453 .collect()
3454}
3455
3456impl DayNavMenuData {
3457 #[allow(clippy::too_many_arguments)]
3458 fn new(
3459 mtm: MainThreadMarker,
3460 node: NodeId,
3461 items: &[String],
3462 icons: &[Option<String>],
3463 badges: &[Option<String>],
3464 badge_icons: &[Option<String>],
3465 badge_tints: &[Option<day_spec::Color>],
3466 sections: &[Option<String>],
3467 tints: &[Option<day_spec::Color>],
3468 menus: &[Vec<day_spec::MenuItem>],
3469 ) -> Retained<Self> {
3470 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3471 node,
3472 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3473 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3474 icons: RefCell::new(resolve_nav_icons(icons)),
3475 tints: RefCell::new(tints.to_vec()),
3476 menus: RefCell::new(menus.to_vec()),
3477 movable: RefCell::new(Vec::new()),
3478 regroup: std::cell::Cell::new(false),
3479 sorted: RefCell::new(Vec::new()),
3480 badges: RefCell::new(ns_badges(badges)),
3481 icon_progress: RefCell::new(Vec::new()),
3482 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3483 badge_tints: RefCell::new(badge_tints.to_vec()),
3484 rows: RefCell::new(Vec::new()),
3485 row_objects: RefCell::new(Vec::new()),
3486 row_ids: RefCell::new(Vec::new()),
3487 suppress: std::cell::Cell::new(false),
3488 });
3489 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3490 this.rebuild_rows(items, sections);
3491 this
3492 }
3493
3494 #[allow(clippy::too_many_arguments)]
3498 fn set_items(
3499 &self,
3500 items: &[String],
3501 icons: &[Option<String>],
3502 badges: &[Option<String>],
3503 badge_icons: &[Option<String>],
3504 badge_tints: &[Option<day_spec::Color>],
3505 sections: &[Option<String>],
3506 tints: &[Option<day_spec::Color>],
3507 menus: &[Vec<day_spec::MenuItem>],
3508 ) {
3509 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3510 let resolved = resolve_nav_icons(icons);
3511 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3512 *self.ivars().icons.borrow_mut() = resolved;
3513 *self.ivars().tints.borrow_mut() = tints.to_vec();
3514 *self.ivars().menus.borrow_mut() = menus.to_vec();
3515 *self.ivars().badges.borrow_mut() = ns_badges(badges);
3516 self.ivars().icon_progress.borrow_mut().clear();
3517 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3518 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3519 self.rebuild_rows(items, sections);
3520 }
3521
3522 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3526 let mut rows = Vec::with_capacity(items.len());
3527 let mut objects = Vec::with_capacity(items.len());
3528 for (i, label) in items.iter().enumerate() {
3529 if let Some(Some(header)) = sections.get(i) {
3530 rows.push(None);
3531 objects.push(NSString::from_str(header));
3532 }
3533 rows.push(Some(i));
3534 objects.push(NSString::from_str(label));
3535 }
3536 let ids = (0..objects.len())
3537 .map(|i| NSNumber::new_isize(i as isize))
3538 .collect();
3539 *self.ivars().rows.borrow_mut() = rows;
3540 *self.ivars().row_objects.borrow_mut() = objects;
3541 *self.ivars().row_ids.borrow_mut() = ids;
3542 }
3543
3544 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3547 item.downcast_ref::<NSNumber>()
3548 .map(|n| n.integerValue())
3549 .unwrap_or(-1)
3550 }
3551
3552 fn item_of_row(&self, row: isize) -> Option<usize> {
3554 if row < 0 {
3555 return None;
3556 }
3557 self.ivars()
3558 .rows
3559 .borrow()
3560 .get(row as usize)
3561 .copied()
3562 .flatten()
3563 }
3564
3565 fn row_of_item(&self, item: usize) -> Option<usize> {
3567 self.ivars()
3568 .rows
3569 .borrow()
3570 .iter()
3571 .position(|r| *r == Some(item))
3572 }
3573
3574 fn is_movable(&self, item: usize) -> bool {
3575 self.ivars()
3576 .movable
3577 .borrow()
3578 .get(item)
3579 .copied()
3580 .unwrap_or(false)
3581 }
3582
3583 fn nav_drop(
3588 &self,
3589 ov: &objc2_app_kit::NSOutlineView,
3590 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3591 item: Option<&objc2::runtime::AnyObject>,
3592 child_index: isize,
3593 ) -> Option<NavDrop> {
3594 let src = unsafe { info.draggingSource() }?;
3595 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3596 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3597 {
3598 return None;
3599 }
3600 let pb = unsafe { info.draggingPasteboard() };
3601 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3602 .to_string()
3603 .parse::<usize>()
3604 .ok()?;
3605 let rows = self.ivars().rows.borrow();
3606 let proposed = match item {
3609 Some(item) => Self::outline_row(item),
3610 None => child_index,
3611 };
3612 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3613 if self.ivars().regroup.get() {
3614 regroup_gap(
3615 &rows,
3616 &self.ivars().movable.borrow(),
3617 &self.ivars().sorted.borrow(),
3618 from_row,
3619 proposed,
3620 item.is_some(),
3621 )
3622 } else {
3623 reorder_gap(
3624 &rows,
3625 &self.ivars().movable.borrow(),
3626 from_row,
3627 proposed,
3628 item.is_some(),
3629 )
3630 }
3631 }
3632}
3633
3634#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3636struct NavDrop {
3637 gap: usize,
3639 retarget: bool,
3641 moves: Option<NavMove>,
3643}
3644
3645#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3647enum NavMove {
3648 Reorder { from: usize, to: usize },
3650 Regroup {
3653 from: usize,
3654 section: usize,
3655 before: Option<usize>,
3656 },
3657}
3658
3659fn reorder_gap(
3664 rows: &[Option<usize>],
3665 movable: &[bool],
3666 from_row: usize,
3667 proposed: usize,
3668 onto: bool,
3669) -> Option<NavDrop> {
3670 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3671 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3672 let in_run = |r: usize| rows[r].is_some_and(is_movable);
3673 let first = (0..from_row)
3674 .rev()
3675 .take_while(|r| in_run(*r))
3676 .last()
3677 .unwrap_or(from_row);
3678 let last = (from_row + 1..rows.len())
3679 .take_while(|r| in_run(*r))
3680 .last()
3681 .unwrap_or(from_row);
3682 let gap = proposed.clamp(first, last + 1);
3683 let target_row = if gap > from_row { gap - 1 } else { gap };
3685 let moves = (target_row != from_row)
3686 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3687 .flatten();
3688 Some(NavDrop {
3689 gap,
3690 retarget: gap != proposed || onto,
3691 moves,
3692 })
3693}
3694
3695fn regroup_gap(
3703 rows: &[Option<usize>],
3704 movable: &[bool],
3705 sorted: &[bool],
3706 from_row: usize,
3707 proposed: usize,
3708 onto: bool,
3709) -> Option<NavDrop> {
3710 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3711 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3712 let gap = match rows.get(proposed) {
3713 Some(None) if onto => proposed + 1,
3714 _ => proposed.min(rows.len()),
3715 };
3716 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3718 Some(header) => Some(header + 1),
3719 None => rows.first().copied().flatten().map(|_| 0),
3720 };
3721 let first = section_start(gap)?;
3722 let end = (first..rows.len())
3723 .find(|r| rows[*r].is_none())
3724 .unwrap_or(rows.len());
3725 let section = rows.get(first).copied().flatten()?;
3726 if !rows[first..end]
3727 .iter()
3728 .all(|r| r.is_some_and(|i| flag(movable, i)))
3729 {
3730 return None;
3731 }
3732 let own = section_start(from_row) == Some(first);
3733 if own && flag(sorted, from) {
3734 return None;
3735 }
3736 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3737 from,
3738 section,
3739 before: rows.get(gap).copied().flatten(),
3740 });
3741 Some(NavDrop {
3742 gap,
3743 retarget: gap != proposed || onto,
3744 moves,
3745 })
3746}
3747
3748#[cfg(test)]
3749mod nav_gap_tests {
3750 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3751
3752 const ROWS: [Option<usize>; 10] = [
3754 Some(0),
3755 None,
3756 Some(1),
3757 Some(2),
3758 Some(3),
3759 None,
3760 Some(4),
3761 Some(5),
3762 None,
3763 Some(6),
3764 ];
3765 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3767 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3768 const UNSORTED: [bool; 7] = [false; 7];
3769
3770 fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3771 Some(NavMove::Regroup {
3772 from,
3773 section,
3774 before,
3775 })
3776 }
3777
3778 #[test]
3779 fn regroup_gaps_name_the_section_above_and_the_row_below() {
3780 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3781 assert_eq!(
3783 at(2, 6),
3784 Some(NavDrop {
3785 gap: 6,
3786 retarget: false,
3787 moves: regroup(1, 4, Some(4)),
3788 })
3789 );
3790 assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3792 assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3794 assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3795 }
3796
3797 #[test]
3798 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
3799 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3800 for gap in [0, 1, 9, 10] {
3802 assert_eq!(at(2, gap), None, "gap {gap}");
3803 }
3804 for gap in [2, 3, 4, 5] {
3806 assert_eq!(at(2, gap), None, "gap {gap}");
3807 }
3808 assert_eq!(at(0, 6), None);
3810 assert_eq!(at(1, 6), None);
3811 assert_eq!(at(9, 6), None);
3812 }
3813
3814 #[test]
3815 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
3816 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
3817 assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
3819 assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
3821 for gap in [2, 3] {
3823 let drop = at(2, gap).expect("offered");
3824 assert_eq!(drop.moves, None, "gap {gap}");
3825 }
3826 }
3827
3828 #[test]
3829 fn regroup_drops_onto_a_row_move_to_a_gap() {
3830 assert_eq!(
3832 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
3833 Some(NavDrop {
3834 gap: 6,
3835 retarget: true,
3836 moves: regroup(1, 4, Some(4)),
3837 })
3838 );
3839 assert_eq!(
3840 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
3841 Some(NavDrop {
3842 gap: 7,
3843 retarget: true,
3844 moves: regroup(1, 4, Some(5)),
3845 })
3846 );
3847 }
3848
3849 #[test]
3850 fn regroup_offers_nothing_above_a_leading_header() {
3851 let rows = [None, Some(0), None, Some(1)];
3853 let movable = [true, true];
3854 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
3855 assert_eq!(at(0), None);
3856 assert_eq!(at(1).map(|d| d.moves), Some(None));
3857 assert_eq!(at(2).map(|d| d.moves), Some(None));
3858 assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
3859 assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
3860 }
3861
3862 #[test]
3863 fn reorder_gaps_clamp_to_the_run() {
3864 assert_eq!(
3866 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
3867 Some(NavDrop {
3868 gap: 5,
3869 retarget: true,
3870 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
3871 })
3872 );
3873 assert_eq!(
3875 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
3876 Some(None)
3877 );
3878 assert_eq!(
3880 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
3881 Some(NavMove::Reorder { from: 2, to: 1 })
3882 );
3883 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
3884 }
3885}
3886
3887const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
3889
3890fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
3892 badges
3893 .iter()
3894 .map(|b| b.as_deref().map(NSString::from_str))
3895 .collect()
3896}
3897
3898fn post_realize_visible_rows(key: usize) {
3904 <AppKit as Platform>::post(Box::new(move || {
3905 if let Some((table, data)) = list_entry(key) {
3906 unsafe { table.layoutSubtreeIfNeeded() };
3907 let range = unsafe { table.rowsInRect(table.visibleRect()) };
3908 if let Some(source) = data.ivars().source.borrow().clone()
3909 && let Some(report) = &source.first_visible
3910 {
3911 report(range.location.min((source.len)().saturating_sub(1)));
3912 }
3913 for row in range.location..range.location + range.length {
3914 let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
3915 if let Some(cell) = cell
3919 && cell.subviews().is_empty()
3920 {
3921 let source = data.ivars().source.borrow().clone();
3922 if let Some(source) = source {
3923 (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
3924 }
3925 }
3926 }
3927 }
3928 day_core::pump_events();
3931 }));
3932}
3933
3934fn post_settle_list_drop(key: usize) {
3939 <AppKit as Platform>::post(Box::new(move || {
3940 day_core::pump_events();
3943 let Some((table, data)) = list_entry(key) else {
3944 return;
3945 };
3946 let Some(scroll) = table.enclosingScrollView() else {
3947 return;
3948 };
3949 let clip = scroll.contentView();
3950 let origin = clip.bounds().origin;
3951 let selected = table.selectedRowIndexes();
3952 let suppressed = data.ivars().suppress.replace(true);
3953 table.reloadData();
3954 table.layoutSubtreeIfNeeded();
3956 let restored = objc2_foundation::NSMutableIndexSet::new();
3957 for row in 0..table.numberOfRows().max(0) as usize {
3958 if selected.containsIndex(row) {
3959 restored.addIndex(row);
3960 }
3961 }
3962 table.selectRowIndexes_byExtendingSelection(&restored, false);
3963 let mut bounds = clip.bounds();
3964 bounds.origin = origin;
3965 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
3966 scroll.reflectScrolledClipView(&clip);
3967 data.ivars().suppress.set(suppressed);
3968 post_realize_visible_rows(key);
3969 }));
3970}
3971
3972define_class!(
3981 #[unsafe(super(NSTableView))]
3982 #[thread_kind = MainThreadOnly]
3983 #[name = "DayListView"]
3984 struct DayListView;
3985 unsafe impl NSObjectProtocol for DayListView {}
3986 impl DayListView {
3987 #[unsafe(method_id(menuForEvent:))]
3990 fn menu_for_event(
3991 &self,
3992 event: &objc2_app_kit::NSEvent,
3993 ) -> Option<Retained<NSMenu>> {
3994 ffi_guard::contain(None, || {
3995 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3996 let row = unsafe { self.rowAtPoint(point) };
3997 let provider = if row >= 0 {
3998 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
3999 .and_then(|cell| list_row_menu_provider(&cell))
4000 } else {
4001 None
4002 };
4003 match provider {
4004 Some((view, provider)) => {
4005 let point = view.convertPoint_fromView(
4006 unsafe { event.locationInWindow() }, None,
4007 );
4008 let items = provider(day_spec::Point::new(point.x, point.y));
4009 if items.is_empty() {
4010 None
4011 } else {
4012 Some(build_ns_menu(self.mtm(), "", &items))
4013 }
4014 }
4015 None => unsafe { msg_send![super(self), menuForEvent: event] },
4016 }
4017 })
4018 }
4019
4020 #[unsafe(method(becomeFirstResponder))]
4021 fn become_first_responder(&self) -> bool {
4022 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4023 if accepted {
4024 self.report_focus(true);
4025 }
4026 accepted
4027 }
4028
4029 #[unsafe(method(resignFirstResponder))]
4030 fn resign_first_responder(&self) -> bool {
4031 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4032 if accepted {
4033 self.report_focus(false);
4034 }
4035 accepted
4036 }
4037
4038 #[unsafe(method(keyDown:))]
4039 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4040 ffi_guard::contain((), || {
4041 let key = unsafe { event.keyCode() };
4042 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4043 let row = unsafe { self.selectedRow() };
4044 if row >= 0 && let Some(target) = unsafe { self.target() } {
4045 let _: () = unsafe { msg_send![&*target, activateRow: self] };
4046 return;
4047 }
4048 }
4049 let _: () = unsafe { msg_send![super(self), keyDown: event] };
4050 });
4051 }
4052 }
4053);
4054
4055fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4058 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4059 return Some((view.retain(), provider));
4060 }
4061 view.subviews()
4062 .iter()
4063 .find_map(|view| list_row_menu_provider(&view))
4064}
4065
4066fn inherited_context_menu(
4070 view: &NSView,
4071 event: &objc2_app_kit::NSEvent,
4072) -> Option<Option<Retained<NSMenu>>> {
4073 let mut current = Some(view.retain());
4074 while let Some(view) = current {
4075 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4076 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4077 let items = provider(day_spec::Point::new(point.x, point.y));
4078 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4079 }
4080 current = unsafe { view.superview() };
4081 }
4082 None
4083}
4084
4085impl DayListView {
4086 fn report_focus(&self, focused: bool) {
4087 ffi_guard::contain((), || {
4088 if let Some(target) = unsafe { self.target() }
4089 && let Some(data) = target.downcast_ref::<DayListData>()
4090 {
4091 emit(data.ivars().node, Event::FocusChanged(focused));
4092 }
4093 });
4094 }
4095}
4096
4097struct ListIvars {
4098 node: NodeId,
4099 source: RefCell<Option<ListSource>>,
4101 selectable: std::cell::Cell<bool>,
4102 multi: std::cell::Cell<bool>,
4104 suppress: std::cell::Cell<bool>,
4106 tokens: RefCell<Vec<u64>>,
4109 automatic: bool,
4113 sections: bool,
4117 header_estimate: std::cell::Cell<f64>,
4119 heights: RefCell<std::collections::HashMap<u64, f64>>,
4122 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4125 estimate: std::cell::Cell<f64>,
4128 heights_pending: std::cell::Cell<bool>,
4130}
4131
4132define_class!(
4133 #[unsafe(super(NSObject))]
4134 #[thread_kind = MainThreadOnly]
4135 #[name = "DayListData"]
4136 #[ivars = ListIvars]
4137 struct DayListData;
4138
4139 unsafe impl NSObjectProtocol for DayListData {}
4140 unsafe impl NSControlTextEditingDelegate for DayListData {}
4141
4142 impl DayListData {
4143 #[unsafe(method(respondsToSelector:))]
4147 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4148 if selector == objc2::sel!(tableView:heightOfRow:)
4149 && !self.ivars().automatic
4150 && !self.ivars().sections
4151 {
4152 false
4153 } else {
4154 unsafe { msg_send![super(self), respondsToSelector: selector] }
4155 }
4156 }
4157
4158 #[unsafe(method(listViewportChanged:))]
4159 fn list_viewport_changed(&self, notification: &NSNotification) {
4160 ffi_guard::contain((), || {
4161 let source = self.ivars().source.borrow().clone();
4162 if let Some(source) = source && let Some(report) = &source.first_visible
4163 && let Some(object) = notification.object()
4164 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4165 && let Some(document) = clip.documentView()
4166 && let Some(table) = document.downcast_ref::<NSTableView>() {
4167 let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4168 report(visible.location.min((source.len)().saturating_sub(1)));
4169 }
4170 });
4171 }
4172
4173 #[unsafe(method(activateRow:))]
4174 fn activate_row(&self, table: &NSTableView) {
4175 ffi_guard::contain((), || {
4176 let row = unsafe { table.selectedRow() };
4177 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4178 });
4179 }
4180 #[unsafe(method(doubleClickRow:))]
4181 fn double_click_row(&self, table: &NSTableView) {
4182 ffi_guard::contain((), || {
4183 let row = unsafe { table.clickedRow() };
4184 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4185 });
4186 }
4187 }
4188
4189 unsafe impl NSTableViewDataSource for DayListData {
4190 #[unsafe(method(numberOfRowsInTableView:))]
4191 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4192 ffi_guard::contain(0, || {
4196 self.ivars()
4197 .source
4198 .borrow()
4199 .as_ref()
4200 .map(|s| (s.len)() as isize)
4201 .unwrap_or(0)
4202 })
4203 }
4204
4205 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4211 fn pasteboard_writer_for_row(
4212 &self,
4213 _tv: &NSTableView,
4214 row: isize,
4215 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4216 let make = || {
4219 let reorderable = self
4221 .ivars()
4222 .source
4223 .borrow()
4224 .as_ref()
4225 .is_some_and(|s| s.reorder.is_some());
4226 if !reorderable || row < 0 || self.is_header(row) {
4228 return None;
4229 }
4230 let item = objc2_app_kit::NSPasteboardItem::new();
4231 unsafe {
4232 item.setString_forType(
4233 &NSString::from_str(&row.to_string()),
4234 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4235 );
4236 }
4237 Some(ProtocolObject::from_retained(item))
4238 };
4239 ffi_guard::contain(None, make)
4240 }
4241
4242 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4243 fn validate_drop(
4244 &self,
4245 tv: &NSTableView,
4246 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4247 row: isize,
4248 _op: objc2_app_kit::NSTableViewDropOperation,
4249 ) -> objc2_app_kit::NSDragOperation {
4250 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4252 let Some((from, len)) = self.drag_context(tv, info) else {
4253 return objc2_app_kit::NSDragOperation::None;
4254 };
4255 let ins = row.clamp(0, len as isize) as usize;
4258 let to = insertion_to_target(from, ins, len);
4259 let accepted = self.can_move(from, to);
4260 if accepted < 0 {
4261 return objc2_app_kit::NSDragOperation::None;
4262 }
4263 let accepted = (accepted as usize).min(len.saturating_sub(1));
4264 if accepted != to {
4265 unsafe {
4267 tv.setDropRow_dropOperation(
4268 target_to_insertion(from, accepted) as isize,
4269 objc2_app_kit::NSTableViewDropOperation::Above,
4270 );
4271 }
4272 }
4273 objc2_app_kit::NSDragOperation::Move
4274 })
4275 }
4276
4277 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4278 fn accept_drop(
4279 &self,
4280 tv: &NSTableView,
4281 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4282 row: isize,
4283 _op: objc2_app_kit::NSTableViewDropOperation,
4284 ) -> bool {
4285 let drop = || {
4287 let Some((from, len)) = self.drag_context(tv, info) else {
4288 return false;
4289 };
4290 let ins = row.clamp(0, len as isize) as usize;
4291 let to = insertion_to_target(from, ins, len);
4292 let accepted = self.can_move(from, to);
4293 if accepted < 0 {
4294 return false;
4295 }
4296 let accepted = (accepted as usize).min(len.saturating_sub(1));
4297 if accepted == from {
4298 return true; }
4300 let mv = self
4304 .ivars()
4305 .source
4306 .borrow()
4307 .as_ref()
4308 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4309 let Some(mv) = mv else { return false };
4310 mv(from, accepted);
4311 {
4314 let mut toks = self.ivars().tokens.borrow_mut();
4315 if from < toks.len() && accepted < toks.len() {
4316 let t = toks.remove(from);
4317 toks.insert(accepted, t);
4318 }
4319 }
4320 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4321 if let Some(scroll) = tv.enclosingScrollView() {
4322 post_settle_list_drop(ptr_of(&scroll));
4323 }
4324 true
4325 };
4326 ffi_guard::contain(false, drop)
4328 }
4329 }
4330
4331 unsafe impl NSTableViewDelegate for DayListData {
4332 #[unsafe(method(tableView:heightOfRow:))]
4337 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4338 ffi_guard::contain(44.0, || {
4339 let ivars = self.ivars();
4340 let header = self.is_header(row);
4341 if !header && !ivars.automatic {
4343 return unsafe { tv.rowHeight() };
4344 }
4345 let token = ivars
4346 .source
4347 .borrow()
4348 .as_ref()
4349 .filter(|s| row >= 0 && (row as usize) < (s.len)())
4350 .map(|s| (s.token_at)(row as usize));
4351 token
4352 .and_then(|t| ivars.heights.borrow().get(&t).copied())
4353 .unwrap_or_else(|| {
4354 if header {
4355 ivars.header_estimate.get()
4356 } else {
4357 ivars.estimate.get()
4358 }
4359 })
4360 })
4361 }
4362
4363 #[unsafe(method(tableView:isGroupRow:))]
4367 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4368 ffi_guard::contain(false, || self.is_header(row))
4369 }
4370
4371 #[unsafe(method(tableView:shouldSelectRow:))]
4373 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4374 ffi_guard::contain(true, || !self.is_header(row))
4375 }
4376
4377 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4378 fn view_for_row(
4379 &self,
4380 tv: &NSTableView,
4381 _col: Option<&NSTableColumn>,
4382 row: isize,
4383 ) -> Option<Retained<NSView>> {
4384 ffi_guard::contain(None, || {
4386 let mtm = self.mtm();
4387 let header = self.is_header(row);
4389 let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4390 let cell: Retained<NSView> =
4392 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4393 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4394 unsafe { v.setIdentifier(Some(&ident)) };
4395 v
4396 });
4397 let source = self.ivars().source.borrow().clone();
4401 if let Some(source) = source {
4402 let raw = Retained::as_ptr(&cell) as RawHandle;
4403 (source.bind_row)(row as usize, raw);
4404 if self.ivars().automatic || header {
4405 self.note_row_height(tv, &source, row, raw, header);
4406 }
4407 }
4408 Some(cell)
4409 })
4410 }
4411
4412 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4413 fn did_remove_row_view(
4414 &self,
4415 _tv: &NSTableView,
4416 row_view: &objc2_app_kit::NSTableRowView,
4417 _row: isize,
4418 ) {
4419 ffi_guard::contain((), || {
4425 let Some(cell) = row_view.subviews().iter().find(|sub| {
4426 sub.identifier()
4427 .map(|i| {
4428 let i = i.to_string();
4429 i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4430 })
4431 .unwrap_or(false)
4432 }) else {
4433 return;
4434 };
4435 let cell = Retained::into_raw(cell) as usize;
4438 let Some(this) = (unsafe {
4439 Retained::retain(self as *const DayListData as *mut DayListData)
4440 }) else {
4441 return;
4442 };
4443 let this = Retained::into_raw(this) as usize;
4444 <AppKit as Platform>::post(Box::new(move || {
4445 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4447 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4448 let (Some(this), Some(cell)) = (this, cell) else {
4449 return;
4450 };
4451 if cell.window().is_some() {
4452 return; }
4454 let recycle = this
4455 .ivars()
4456 .source
4457 .borrow()
4458 .as_ref()
4459 .map(|s| s.recycle.clone());
4460 if let Some(recycle) = recycle {
4461 recycle(Retained::as_ptr(&cell) as RawHandle);
4462 }
4463 }));
4464 })
4465 }
4466
4467 #[unsafe(method(tableViewSelectionDidChange:))]
4468 fn selection_did_change(&self, notification: &NSNotification) {
4469 ffi_guard::contain((), || {
4470 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4471 return;
4472 }
4473 let Some(obj) = (unsafe { notification.object() }) else {
4474 return;
4475 };
4476 let Ok(tv) = obj.downcast::<NSTableView>() else {
4477 return;
4478 };
4479 if self.ivars().multi.get() {
4480 let idx = unsafe { tv.selectedRowIndexes() };
4482 let mut rows = Vec::with_capacity(idx.count());
4483 let mut i = idx.firstIndex();
4484 while i != objc2_foundation::NSNotFound as usize {
4485 rows.push(i as i64);
4486 i = unsafe { idx.indexGreaterThanIndex(i) };
4487 }
4488 emit(self.ivars().node, Event::SelectionSet(rows));
4489 } else {
4490 let row = unsafe { tv.selectedRow() };
4491 if row >= 0 {
4492 emit(self.ivars().node, Event::SelectionChanged(row as i64));
4493 } else {
4494 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4502 }
4503 }
4504 })
4505 }
4506
4507 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4513 fn row_actions_for_row(
4514 &self,
4515 tv: &NSTableView,
4516 row: isize,
4517 edge: objc2_app_kit::NSTableRowActionEdge,
4518 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4519 ffi_guard::contain(NSArray::new(), || {
4521 let sw = self
4522 .ivars()
4523 .source
4524 .borrow()
4525 .as_ref()
4526 .and_then(|s| s.swipe.clone());
4527 let Some(sw) = sw else {
4528 return NSArray::new();
4529 };
4530 if row < 0 {
4531 return NSArray::new();
4532 }
4533 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4535 day_spec::SwipeEdge::Leading
4536 } else {
4537 day_spec::SwipeEdge::Trailing
4538 };
4539 let offer = (sw.actions_at)(row as usize, day_edge);
4540 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4541 .iter()
4542 .enumerate()
4543 .map(|(i, a)| {
4544 let style = if a.destructive {
4545 objc2_app_kit::NSTableViewRowActionStyle::Destructive
4546 } else {
4547 objc2_app_kit::NSTableViewRowActionStyle::Regular
4548 };
4549 let perform = sw.perform.clone();
4550 let table = tv.retain();
4553 let handler = block2::RcBlock::new(
4554 move |_action: std::ptr::NonNull<
4555 objc2_app_kit::NSTableViewRowAction,
4556 >,
4557 row: isize| {
4558 ffi_guard::contain((), || {
4559 perform(row as usize, day_edge, i);
4560 unsafe { table.setRowActionsVisible(false) };
4563 })
4564 },
4565 );
4566 let action =
4567 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4568 style,
4569 &NSString::from_str(&a.label),
4570 &handler,
4571 );
4572 if let Some(t) = a.tint {
4573 unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4574 }
4575 if let Some(sym) = a.symbol {
4579 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4580 &NSString::from_str(day_spec::sf_symbol_name(sym)),
4581 None,
4582 );
4583 if let Some(img) = img {
4584 unsafe { action.setImage(Some(&img)) };
4585 }
4586 }
4587 action
4588 })
4589 .collect();
4590 NSArray::from_retained_slice(&actions)
4591 })
4592 }
4593 }
4594);
4595
4596impl DayListData {
4597 fn new(
4598 mtm: MainThreadMarker,
4599 node: NodeId,
4600 selectable: bool,
4601 multi: bool,
4602 automatic: bool,
4603 sections: bool,
4604 ) -> Retained<Self> {
4605 let this = Self::alloc(mtm).set_ivars(ListIvars {
4606 node,
4607 source: RefCell::new(None),
4608 selectable: std::cell::Cell::new(selectable),
4609 multi: std::cell::Cell::new(multi),
4610 suppress: std::cell::Cell::new(false),
4611 tokens: RefCell::new(Vec::new()),
4612 automatic,
4613 sections,
4614 header_estimate: std::cell::Cell::new(28.0),
4615 heights: RefCell::new(std::collections::HashMap::new()),
4616 cell_tokens: RefCell::new(std::collections::HashMap::new()),
4617 estimate: std::cell::Cell::new(44.0),
4618 heights_pending: std::cell::Cell::new(false),
4619 });
4620 unsafe { msg_send![super(this), init] }
4621 }
4622
4623 fn note_row_height(
4627 &self,
4628 table: &NSTableView,
4629 source: &ListSource,
4630 row: isize,
4631 cell: RawHandle,
4632 header: bool,
4633 ) {
4634 let height = (source.cell_height)(cell);
4635 if height <= 0.0 || row < 0 {
4636 return;
4637 }
4638 let token = (source.token_at)(row as usize);
4639 self.ivars()
4640 .cell_tokens
4641 .borrow_mut()
4642 .insert(cell as usize, token);
4643 self.ivars().heights.borrow_mut().insert(token, height);
4644 if header {
4645 self.ivars().header_estimate.set(height);
4646 } else {
4647 self.ivars().estimate.set(height);
4648 }
4649 let drawn = unsafe { table.rectOfRow(row) }.size.height;
4650 if (drawn - height).abs() > 0.5 {
4651 self.post_row_heights(table);
4652 }
4653 }
4654
4655 fn is_header(&self, row: isize) -> bool {
4657 row >= 0
4658 && self
4659 .ivars()
4660 .source
4661 .borrow()
4662 .as_ref()
4663 .and_then(|s| s.is_header.clone())
4664 .is_some_and(|is_header| is_header(row as usize))
4665 }
4666
4667 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4670 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4671 if let Some(token) = token {
4672 self.ivars().heights.borrow_mut().insert(token, height);
4673 self.post_row_heights(table);
4674 }
4675 }
4676
4677 fn post_row_heights(&self, table: &NSTableView) {
4681 if self.ivars().heights_pending.replace(true) {
4682 return;
4683 }
4684 let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4687 return;
4688 };
4689 let this = Retained::into_raw(this) as usize;
4690 let table = Retained::into_raw(table.retain()) as usize;
4691 <AppKit as Platform>::post(Box::new(move || {
4692 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4694 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4695 let (Some(this), Some(table)) = (this, table) else {
4696 return;
4697 };
4698 this.ivars().heights_pending.set(false);
4699 ffi_guard::contain((), || this.apply_row_heights(&table));
4700 }));
4701 }
4702
4703 fn apply_row_heights(&self, table: &NSTableView) {
4704 let Some(source) = self.ivars().source.borrow().clone() else {
4705 return;
4706 };
4707 let count = unsafe { table.numberOfRows() }.max(0) as usize;
4708 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4709 let first = shown.location.saturating_sub(8);
4711 let last = (shown.location + shown.length + 8)
4712 .min(count)
4713 .min((source.len)());
4714 let changed = objc2_foundation::NSMutableIndexSet::new();
4715 {
4716 let heights = self.ivars().heights.borrow();
4717 for row in first..last {
4718 if let Some(&height) = heights.get(&(source.token_at)(row)) {
4719 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4720 if (drawn - height).abs() > 0.5 {
4721 unsafe { changed.addIndex(row) };
4722 }
4723 }
4724 }
4725 }
4726 if changed.count() == 0 {
4727 return;
4728 }
4729 NSAnimationContext::beginGrouping();
4731 NSAnimationContext::currentContext().setDuration(0.0);
4732 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4733 NSAnimationContext::endGrouping();
4734 }
4735
4736 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4748 let source = self.ivars().source.borrow();
4749 let source = source.as_ref()?;
4750 let n = (source.len)();
4751 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4752 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4753 if old.len() != n || n == 0 || old == new {
4754 return None;
4755 }
4756 let (mut so, mut sn) = (old.clone(), new.clone());
4757 so.sort_unstable();
4758 sn.sort_unstable();
4759 if so != sn {
4760 return None;
4761 }
4762 for i in 0..n {
4763 if old[i] != new[i]
4764 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4765 {
4766 return None;
4767 }
4768 }
4769 let mut work = old;
4770 let mut moves = Vec::new();
4771 for i in 0..n {
4772 if work[i] == new[i] {
4773 continue;
4774 }
4775 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4776 let t = work.remove(j);
4777 work.insert(i, t);
4778 moves.push((j, i));
4779 }
4780 Some(moves)
4781 }
4782
4783 fn drag_context(
4787 &self,
4788 tv: &NSTableView,
4789 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4790 ) -> Option<(usize, usize)> {
4791 let src = unsafe { info.draggingSource() }?;
4792 if Retained::as_ptr(&src) as *const std::ffi::c_void
4793 != tv as *const NSTableView as *const std::ffi::c_void
4794 {
4795 return None;
4796 }
4797 let pb = unsafe { info.draggingPasteboard() };
4798 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
4799 .to_string()
4800 .parse::<usize>()
4801 .ok()?;
4802 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
4803 (from < len).then_some((from, len))
4804 }
4805
4806 fn can_move(&self, from: usize, to: usize) -> i64 {
4808 self.ivars()
4809 .source
4810 .borrow()
4811 .as_ref()
4812 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
4813 .unwrap_or(-1)
4814 }
4815}
4816
4817const DAY_ROW_CELL: &str = "day.cell";
4819const DAY_HEADER_CELL: &str = "day.header";
4820
4821const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
4823
4824fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
4827 let to = if ins > from { ins - 1 } else { ins };
4828 to.min(len.saturating_sub(1))
4829}
4830
4831fn target_to_insertion(from: usize, to: usize) -> usize {
4833 if to > from { to + 1 } else { to }
4834}
4835
4836type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
4838
4839fn list_entry(key: usize) -> Option<ListEntry> {
4846 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
4847}
4848
4849struct TreeIvars {
4854 node: NodeId,
4855 source: RefCell<Option<TreeSource>>,
4857 selectable: std::cell::Cell<bool>,
4858 suppress: std::cell::Cell<bool>,
4860 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
4864}
4865
4866define_class!(
4867 #[unsafe(super(NSObject))]
4868 #[thread_kind = MainThreadOnly]
4869 #[name = "DayTreeData"]
4870 #[ivars = TreeIvars]
4871 struct DayTreeData;
4872
4873 unsafe impl NSObjectProtocol for DayTreeData {}
4874
4875 unsafe impl NSOutlineViewDataSource for DayTreeData {
4876 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4877 fn number_of_children(
4878 &self,
4879 _ov: &objc2_app_kit::NSOutlineView,
4880 item: Option<&objc2::runtime::AnyObject>,
4881 ) -> isize {
4882 ffi_guard::contain(0, || {
4886 let parent = item.and_then(Self::token_of_item);
4887 if item.is_some() && parent.is_none() {
4888 return 0; }
4890 self.ivars()
4891 .source
4892 .borrow()
4893 .as_ref()
4894 .map(|s| (s.children_len)(parent) as isize)
4895 .unwrap_or(0)
4896 })
4897 }
4898
4899 #[unsafe(method_id(outlineView:child:ofItem:))]
4900 fn child_of_item(
4901 &self,
4902 _ov: &objc2_app_kit::NSOutlineView,
4903 index: isize,
4904 item: Option<&objc2::runtime::AnyObject>,
4905 ) -> Retained<objc2::runtime::AnyObject> {
4906 let token = ffi_guard::contain(0, || {
4910 let parent = item.and_then(Self::token_of_item);
4911 self.ivars()
4912 .source
4913 .borrow()
4914 .as_ref()
4915 .map(|s| (s.child_token)(parent, index.max(0) as usize))
4916 .unwrap_or(0)
4917 });
4918 let ns = self.intern(token);
4919 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
4920 }
4921
4922 #[unsafe(method(outlineView:isItemExpandable:))]
4923 fn is_expandable(
4924 &self,
4925 _ov: &objc2_app_kit::NSOutlineView,
4926 item: &objc2::runtime::AnyObject,
4927 ) -> bool {
4928 ffi_guard::contain(false, || {
4929 let Some(token) = Self::token_of_item(item) else {
4930 return false;
4931 };
4932 self.ivars()
4933 .source
4934 .borrow()
4935 .as_ref()
4936 .map(|s| (s.expandable)(token))
4937 .unwrap_or(false)
4938 })
4939 }
4940
4941 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
4947 fn pasteboard_writer_for_item(
4948 &self,
4949 _ov: &objc2_app_kit::NSOutlineView,
4950 item: &objc2::runtime::AnyObject,
4951 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4952 let make = || {
4953 let movable = self
4954 .ivars()
4955 .source
4956 .borrow()
4957 .as_ref()
4958 .is_some_and(|s| s.moves.is_some());
4959 let token = Self::token_of_item(item)?;
4960 if !movable {
4961 return None;
4962 }
4963 let pbitem = objc2_app_kit::NSPasteboardItem::new();
4964 unsafe {
4965 pbitem.setString_forType(
4966 &NSString::from_str(&token.to_string()),
4967 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
4968 );
4969 }
4970 Some(ProtocolObject::from_retained(pbitem))
4971 };
4972 ffi_guard::contain(None, make)
4973 }
4974
4975 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
4976 fn validate_drop(
4977 &self,
4978 ov: &objc2_app_kit::NSOutlineView,
4979 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4980 item: Option<&objc2::runtime::AnyObject>,
4981 child_index: isize,
4982 ) -> objc2_app_kit::NSDragOperation {
4983 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4984 match self.drop_proposal(ov, info, item, child_index) {
4985 Some((token, parent, index)) if self.can_move(token, parent, index) => {
4986 objc2_app_kit::NSDragOperation::Move
4987 }
4988 _ => objc2_app_kit::NSDragOperation::None,
4989 }
4990 })
4991 }
4992
4993 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
4994 fn accept_drop(
4995 &self,
4996 ov: &objc2_app_kit::NSOutlineView,
4997 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4998 item: Option<&objc2::runtime::AnyObject>,
4999 child_index: isize,
5000 ) -> bool {
5001 let drop = || {
5002 let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5003 else {
5004 return false;
5005 };
5006 if !self.can_move(token, parent, index) {
5007 return false;
5008 }
5009 let mv = self
5012 .ivars()
5013 .source
5014 .borrow()
5015 .as_ref()
5016 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5017 let Some(mv) = mv else { return false };
5018 mv(token, parent, index);
5019 true
5020 };
5021 ffi_guard::contain(false, drop)
5022 }
5023 }
5024
5025 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5026
5027 unsafe impl NSOutlineViewDelegate for DayTreeData {
5028 #[unsafe(method(outlineView:isGroupItem:))]
5029 fn is_group_item(
5030 &self,
5031 _ov: &objc2_app_kit::NSOutlineView,
5032 item: &objc2::runtime::AnyObject,
5033 ) -> bool {
5034 Self::token_of_item(item).is_some_and(|t| {
5035 self.ivars()
5036 .source
5037 .borrow()
5038 .as_ref()
5039 .is_some_and(|s| (s.section_header)(t))
5040 })
5041 }
5042 #[unsafe(method(outlineView:shouldSelectItem:))]
5043 fn should_select_item(
5044 &self,
5045 _ov: &objc2_app_kit::NSOutlineView,
5046 item: &objc2::runtime::AnyObject,
5047 ) -> bool {
5048 Self::token_of_item(item).is_some_and(|t| {
5049 self.ivars()
5050 .source
5051 .borrow()
5052 .as_ref()
5053 .is_some_and(|s| !(s.section_header)(t))
5054 })
5055 }
5056
5057 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5058 fn view_for_item(
5059 &self,
5060 ov: &objc2_app_kit::NSOutlineView,
5061 _col: Option<&NSTableColumn>,
5062 item: &objc2::runtime::AnyObject,
5063 ) -> Option<Retained<NSView>> {
5064 ffi_guard::contain(None, || {
5066 let mtm = self.mtm();
5067 let token = Self::token_of_item(item)?;
5068 let ident = NSString::from_str("day.tree.cell");
5069 let cell: Retained<NSView> =
5073 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5074 let v: Retained<NSView> =
5075 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5076 unsafe { v.setIdentifier(Some(&ident)) };
5077 v
5078 });
5079 if let Some(source) = self.ivars().source.borrow().as_ref() {
5080 let raw = Retained::as_ptr(&cell) as RawHandle;
5081 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5082 unsafe {
5083 cell.setTextField(None);
5084 }
5085 }
5086 (source.bind_row)(token, raw);
5087 if (source.section_header)(token) {
5090 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5091 for child in unsafe { view.subviews() }.iter() {
5092 if let Ok(label) = child.clone().downcast::<NSTextField>() {
5093 return Some(label);
5094 }
5095 if let Some(label) = label_in(&child) {
5096 return Some(label);
5097 }
5098 }
5099 None
5100 }
5101 if let Some(label) = label_in(&cell) {
5102 let cell = cell.downcast_ref::<DayTreeCell>()?;
5103 unsafe {
5104 cell.setTextField(Some(&label));
5105 }
5106 }
5107 }
5108 }
5109 Some(cell)
5110 })
5111 }
5112
5113 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5114 fn type_select_string(
5115 &self,
5116 _ov: &objc2_app_kit::NSOutlineView,
5117 _col: Option<&NSTableColumn>,
5118 item: &objc2::runtime::AnyObject,
5119 ) -> Option<Retained<NSString>> {
5120 ffi_guard::contain(None, || {
5121 let token = Self::token_of_item(item)?;
5122 let text = self
5123 .ivars()
5124 .source
5125 .borrow()
5126 .as_ref()
5127 .map(|s| (s.type_select_text)(token))
5128 .unwrap_or_default();
5129 (!text.is_empty()).then(|| NSString::from_str(&text))
5131 })
5132 }
5133
5134 #[unsafe(method_id(outlineView:rowViewForItem:))]
5135 fn row_view_for_item(
5136 &self,
5137 ov: &objc2_app_kit::NSOutlineView,
5138 _item: &objc2::runtime::AnyObject,
5139 ) -> Retained<objc2_app_kit::NSTableRowView> {
5140 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5141 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5143 } else {
5144 let rv: Retained<DayTreeRowView> =
5146 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5147 Retained::into_super(rv)
5148 }
5149 }
5150
5151 #[unsafe(method(outlineViewSelectionDidChange:))]
5152 fn selection_did_change(&self, notification: &NSNotification) {
5153 ffi_guard::contain((), || {
5154 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5155 return;
5156 }
5157 let Some(obj) = (unsafe { notification.object() }) else {
5158 return;
5159 };
5160 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5161 return;
5162 };
5163 let idx = unsafe { ov.selectedRowIndexes() };
5165 let mut tokens = Vec::with_capacity(idx.count());
5166 let mut i = idx.firstIndex();
5167 while i != objc2_foundation::NSNotFound as usize {
5168 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5169 && let Some(tok) = Self::token_of_item(&item)
5170 {
5171 tokens.push(tok);
5172 }
5173 i = unsafe { idx.indexGreaterThanIndex(i) };
5174 }
5175 emit(self.ivars().node, Event::TreeSelection(tokens));
5176 })
5177 }
5178
5179 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5180 fn did_remove_row_view(
5181 &self,
5182 ov: &objc2_app_kit::NSOutlineView,
5183 row_view: &objc2_app_kit::NSTableRowView,
5184 _row: isize,
5185 ) {
5186 ffi_guard::contain((), || {
5192 let mut cell_ptr: Option<usize> = None;
5193 for sub in row_view.subviews().iter() {
5194 let is_cell = sub
5195 .identifier()
5196 .map(|i| i.to_string() == "day.tree.cell")
5197 .unwrap_or(false);
5198 if is_cell {
5199 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5200 }
5201 }
5202 let Some(cell) = cell_ptr else { return };
5203 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5204 return;
5205 };
5206 let key = Retained::as_ptr(&scroll) as usize;
5207 let retained =
5211 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5212 as usize;
5213 <AppKit as Platform>::post(Box::new(move || {
5214 let cell_view: Retained<NSView> =
5217 match unsafe { Retained::from_raw(retained as *mut NSView) } {
5218 Some(v) => v,
5219 None => return,
5220 };
5221 let recycle = tree_entry(key).and_then(|(_, data)| {
5222 data.ivars()
5223 .source
5224 .borrow()
5225 .as_ref()
5226 .map(|s| s.recycle.clone())
5227 });
5228 let Some(recycle) = recycle else { return };
5229 if cell_view.window().is_some() {
5230 return; }
5232 recycle(cell as RawHandle);
5233 }));
5234 })
5235 }
5236
5237 #[unsafe(method(outlineViewItemDidExpand:))]
5238 fn item_did_expand(&self, notification: &NSNotification) {
5239 self.report_disclosure(notification, true);
5240 }
5241
5242 #[unsafe(method(outlineViewItemDidCollapse:))]
5243 fn item_did_collapse(&self, notification: &NSNotification) {
5244 self.report_disclosure(notification, false);
5245 }
5246 }
5247);
5248
5249impl DayTreeData {
5250 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5251 let this = Self::alloc(mtm).set_ivars(TreeIvars {
5252 node,
5253 source: RefCell::new(None),
5254 selectable: std::cell::Cell::new(selectable),
5255 suppress: std::cell::Cell::new(false),
5256 items: RefCell::new(HashMap::new()),
5257 });
5258 unsafe { msg_send![super(this), init] }
5259 }
5260
5261 fn intern(&self, token: u64) -> Retained<NSNumber> {
5263 self.ivars()
5264 .items
5265 .borrow_mut()
5266 .entry(token)
5267 .or_insert_with(|| NSNumber::new_u64(token))
5268 .clone()
5269 }
5270
5271 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5272 item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5273 }
5274
5275 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5278 ffi_guard::contain((), || {
5279 if self.ivars().suppress.get() {
5280 return;
5281 }
5282 let token = unsafe { notification.userInfo() }
5283 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5284 .and_then(|item| Self::token_of_item(&item));
5285 if let Some(token) = token {
5286 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5287 }
5288 })
5289 }
5290
5291 fn drop_proposal(
5295 &self,
5296 ov: &objc2_app_kit::NSOutlineView,
5297 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5298 item: Option<&objc2::runtime::AnyObject>,
5299 child_index: isize,
5300 ) -> Option<(u64, Option<u64>, Option<usize>)> {
5301 let src = unsafe { info.draggingSource() }?;
5302 if Retained::as_ptr(&src) as *const std::ffi::c_void
5303 != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5304 {
5305 return None;
5306 }
5307 let pb = unsafe { info.draggingPasteboard() };
5308 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5309 .to_string()
5310 .parse::<u64>()
5311 .ok()?;
5312 let parent = match item {
5313 Some(i) => Some(Self::token_of_item(i)?), None => None,
5315 };
5316 let index = (child_index >= 0).then_some(child_index as usize);
5317 Some((token, parent, index))
5318 }
5319
5320 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5322 self.ivars()
5323 .source
5324 .borrow()
5325 .as_ref()
5326 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5327 .map(|v| v == MoveVerdict::Allow)
5328 .unwrap_or(false)
5329 }
5330}
5331
5332define_class!(
5338 #[unsafe(super(objc2_app_kit::NSOutlineView))]
5339 #[thread_kind = MainThreadOnly]
5340 #[name = "DayOutlineView"]
5341 struct DayOutlineView;
5342
5343 impl DayOutlineView {
5344 #[unsafe(method(layout))]
5345 fn layout(&self) {
5346 sync_tree_width(self);
5347 let _: () = unsafe { msg_send![super(self), layout] };
5348 }
5349
5350 #[unsafe(method_id(menuForEvent:))]
5353 fn menu_for_event(
5354 &self,
5355 event: &objc2_app_kit::NSEvent,
5356 ) -> Option<Retained<NSMenu>> {
5357 ffi_guard::contain(None, || {
5358 let scroll = unsafe { self.enclosingScrollView() }?;
5359 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5360 let row_menu = data
5361 .ivars()
5362 .source
5363 .borrow()
5364 .as_ref()
5365 .and_then(|s| s.row_menu.clone())?;
5366 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5367 let row = unsafe { self.rowAtPoint(p) };
5368 if row < 0 {
5369 return None;
5370 }
5371 let token =
5372 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5373 let items = row_menu(token);
5374 if items.is_empty() {
5375 return None;
5376 }
5377 Some(build_ns_menu(self.mtm(), "", &items))
5378 })
5379 }
5380 }
5381);
5382
5383define_class!(
5390 #[unsafe(super(objc2_app_kit::NSTableRowView))]
5391 #[thread_kind = MainThreadOnly]
5392 #[name = "DayTreeRowView"]
5393 struct DayTreeRowView;
5394
5395 impl DayTreeRowView {
5396 #[unsafe(method(drawSelectionInRect:))]
5397 fn draw_selection_in_rect(&self, _dirty: NSRect) {
5398 if !unsafe { self.isSelected() } {
5399 return;
5400 }
5401 let color = if unsafe { self.isEmphasized() } {
5402 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5403 } else {
5404 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5405 };
5406 let b = self.bounds();
5407 let pill = NSRect::new(
5408 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5409 NSSize::new(
5410 (b.size.width - 10.0).max(0.0),
5411 (b.size.height - 2.0).max(0.0),
5412 ),
5413 );
5414 unsafe {
5415 color.setFill();
5416 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5417 pill, 5.0, 5.0,
5418 )
5419 .fill();
5420 }
5421 }
5422 }
5423);
5424
5425define_class!(
5429 #[unsafe(super(objc2_app_kit::NSTableCellView))]
5430 #[thread_kind = MainThreadOnly]
5431 #[name = "DayTreeCell"]
5432 struct DayTreeCell;
5433
5434 impl DayTreeCell {
5435 #[unsafe(method(isFlipped))]
5436 fn is_flipped(&self) -> bool {
5437 true
5438 }
5439
5440 #[unsafe(method(layout))]
5441 fn layout(&self) {
5442 let _: () = unsafe { msg_send![super(self), layout] };
5443 ffi_guard::contain((), || {
5444 let width = self.bounds().size.width;
5445 if width <= 0.0 {
5446 return;
5447 }
5448 let mut cur = unsafe { self.superview() };
5452 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5453 while let Some(v) = cur {
5454 cur = unsafe { v.superview() };
5455 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5456 outline = Some(ov);
5457 break;
5458 }
5459 }
5460 let Some(ov) = outline else { return };
5461 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5462 return;
5463 };
5464 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5465 .and_then(|(_, data)| {
5466 data.ivars()
5467 .source
5468 .borrow()
5469 .as_ref()
5470 .map(|s| s.layout_cell_size.clone())
5471 });
5472 if let Some(f) = f {
5473 f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5474 }
5475 })
5476 }
5477 }
5478);
5479
5480impl DayTreeCell {
5481 fn new(mtm: MainThreadMarker) -> Retained<Self> {
5482 unsafe { msg_send![Self::alloc(mtm), init] }
5483 }
5484}
5485
5486const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5488
5489type TreeEntry = (
5491 Retained<objc2_app_kit::NSOutlineView>,
5492 Retained<DayTreeData>,
5493);
5494
5495fn tree_entry(key: usize) -> Option<TreeEntry> {
5498 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5499}
5500
5501fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5505 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5506 return;
5507 };
5508 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5509 let f = outline.frame();
5510 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5511 unsafe {
5512 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5513 outline.sizeLastColumnToFit();
5514 }
5515 }
5516}
5517
5518fn post_realize_visible_tree_rows(key: usize) {
5521 <AppKit as Platform>::post(Box::new(move || {
5522 if let Some((outline, _)) = tree_entry(key) {
5523 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5524 for row in range.location..range.location + range.length {
5525 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5526 }
5527 }
5528 day_core::pump_events();
5529 }));
5530}
5531
5532type NavMenuEntry = (
5534 Retained<objc2_app_kit::NSOutlineView>,
5535 Retained<DayNavMenuData>,
5536);
5537
5538fn ns_rect(r: day_spec::Rect) -> NSRect {
5539 NSRect::new(
5540 NSPoint::new(r.origin.x, r.origin.y),
5541 NSSize::new(r.size.width, r.size.height),
5542 )
5543}
5544
5545fn draw_op(op: &DrawOp) {
5546 unsafe {
5547 match op {
5548 DrawOp::Stamp(st) => {
5554 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5555 for p in &st.at {
5556 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5557 unsafe { batch.appendBezierPath(©) };
5558 }
5559 }
5560 let color = match &st.paint {
5561 day_spec::Paint::Solid(c) => *c,
5562 _ => day_spec::Color::WHITE,
5565 };
5566 match &st.stroke {
5567 None => {
5568 nscolor(color).setFill();
5569 unsafe { batch.fill() };
5570 }
5571 Some(style) => {
5572 nscolor(color).setStroke();
5573 apply_stroke_style(&batch, style);
5574 unsafe { batch.stroke() };
5575 }
5576 }
5577 }
5578 DrawOp::Fill(shape, paint) => match paint {
5579 day_spec::Paint::Solid(color) => {
5580 nscolor(*color).setFill();
5581 if let Some(p) = bezier(shape) {
5582 p.fill();
5583 }
5584 }
5585 day_spec::Paint::Linear(g) => {
5586 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5589 let b = shape.bounds();
5590 let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5591 NSGraphicsContext::saveGraphicsState_class();
5592 p.addClip();
5593 grad.drawFromPoint_toPoint_options(
5594 NSPoint::new(s.x, s.y),
5595 NSPoint::new(e.x, e.y),
5596 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5597 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5598 );
5599 NSGraphicsContext::restoreGraphicsState_class();
5600 }
5601 }
5602 day_spec::Paint::Radial(g) => {
5603 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5606 let b = shape.bounds();
5607 NSGraphicsContext::saveGraphicsState_class();
5608 p.addClip();
5609 concat_unit_to_bounds(b);
5610 let c = NSPoint::new(g.center.x, g.center.y);
5611 grad.drawFromCenter_radius_toCenter_radius_options(
5612 c,
5613 0.0,
5614 c,
5615 g.radius,
5616 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5617 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5618 );
5619 NSGraphicsContext::restoreGraphicsState_class();
5620 }
5621 }
5622 },
5623 DrawOp::Stroke(shape, paint, style) => {
5624 if let Some(p) = bezier(shape) {
5625 apply_stroke_style(&p, style);
5626 match paint {
5627 day_spec::Paint::Solid(color) => {
5628 nscolor(*color).setStroke();
5629 p.stroke();
5630 }
5631 _ => {
5637 let Some(ctx) = NSGraphicsContext::currentContext() else {
5638 return;
5639 };
5640 let cg = ctx.CGContext();
5641 NSGraphicsContext::saveGraphicsState_class();
5642 objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5643 objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5644 &cg,
5645 ));
5646 objc2_core_graphics::CGContext::clip(Some(&cg));
5647 draw_gradient_in(paint, shape.bounds());
5648 NSGraphicsContext::restoreGraphicsState_class();
5649 }
5650 }
5651 }
5652 }
5653 DrawOp::Clip(shape) => {
5654 if let Some(p) = bezier(shape) {
5656 p.addClip();
5657 }
5658 }
5659 DrawOp::Text {
5660 text,
5661 at,
5662 size,
5663 color,
5664 anchor,
5665 font,
5666 } => {
5667 let font = canvas_nsfont(*size, font);
5668 let attrs = canvas_text_attrs(&font, *color);
5669 let ns = NSString::from_str(text);
5670 let mut origin = NSPoint::new(at.x, at.y);
5671 if *anchor != day_spec::TextAnchor::LEADING {
5676 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5677 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5678 origin.x += dx;
5679 origin.y += dy;
5680 }
5681 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5682 }
5683 DrawOp::Image {
5687 image,
5688 rect,
5689 opacity,
5690 } => {
5691 let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5692 if let Some(img) = img {
5693 let dest = NSRect::new(
5694 NSPoint::new(rect.origin.x, rect.origin.y),
5695 NSSize::new(rect.size.width, rect.size.height),
5696 );
5697 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5701 dest,
5702 NSRect::ZERO,
5703 objc2_app_kit::NSCompositingOperation::SourceOver,
5704 *opacity,
5705 true,
5706 None,
5707 );
5708 }
5709 }
5710 DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5711 DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5712 DrawOp::Concat(m) => {
5713 let t = NSAffineTransform::new();
5714 t.setTransformStruct(NSAffineTransformStruct {
5715 m11: m.a,
5716 m12: m.b,
5717 m21: m.c,
5718 m22: m.d,
5719 tX: m.tx,
5720 tY: m.ty,
5721 });
5722 t.concat();
5723 }
5724 }
5725 }
5726}
5727
5728fn nsgradient(
5730 stops: &[(f64, day_spec::Color)],
5731) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5732 if stops.is_empty() {
5733 return None;
5734 }
5735 let colors = objc2_foundation::NSArray::from_retained_slice(
5736 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5737 );
5738 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5739 unsafe {
5740 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5741 objc2_app_kit::NSGradient::alloc(),
5742 &colors,
5743 locations.as_ptr(),
5744 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5745 )
5746 }
5747}
5748
5749fn concat_unit_to_bounds(b: day_spec::Rect) {
5752 let t = NSAffineTransform::new();
5753 t.setTransformStruct(NSAffineTransformStruct {
5754 m11: b.size.width,
5755 m12: 0.0,
5756 m21: 0.0,
5757 m22: b.size.height,
5758 tX: b.origin.x,
5759 tY: b.origin.y,
5760 });
5761 unsafe { t.concat() };
5762}
5763
5764fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5770 use day_spec::{LineCap, LineJoin};
5771 unsafe {
5772 p.setLineWidth(style.width);
5773 p.setLineCapStyle(match style.cap {
5774 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5775 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5776 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5777 });
5778 if style.is_plain() {
5779 return;
5780 }
5781 p.setLineJoinStyle(match style.join {
5782 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5783 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5784 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5785 });
5786 p.setMiterLimit(style.miter_limit);
5787 if !style.dash.is_empty() {
5788 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5789 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5790 }
5791 }
5792}
5793
5794fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
5798 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5799 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
5800 match paint {
5801 day_spec::Paint::Linear(g) => {
5802 if let Some(grad) = nsgradient(&g.stops) {
5803 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
5804 unsafe {
5805 grad.drawFromPoint_toPoint_options(
5806 NSPoint::new(s.x, s.y),
5807 NSPoint::new(e.x, e.y),
5808 opts,
5809 )
5810 };
5811 }
5812 }
5813 day_spec::Paint::Radial(g) => {
5814 if let Some(grad) = nsgradient(&g.stops) {
5815 NSGraphicsContext::saveGraphicsState_class();
5816 concat_unit_to_bounds(bounds);
5817 let c = NSPoint::new(g.center.x, g.center.y);
5818 unsafe {
5819 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
5820 };
5821 NSGraphicsContext::restoreGraphicsState_class();
5822 }
5823 }
5824 day_spec::Paint::Solid(_) => {}
5825 }
5826}
5827
5828fn apply_button_content(
5829 btn: &NSButton,
5830 title: &str,
5831 icon: Option<&day_spec::Icon>,
5832 icon_only: bool,
5833) {
5834 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
5835 if let Some(image) = &image {
5836 let size = image.size();
5837 let longest = size.width.max(size.height);
5838 if longest > 0.0 {
5839 image.setSize(objc2_foundation::NSSize::new(
5840 size.width * 20.0 / longest,
5841 size.height * 20.0 / longest,
5842 ));
5843 }
5844 }
5845 let style = BUTTON_STYLES
5846 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
5847 .unwrap_or_default();
5848 BUTTON_IMAGES.with(|images| {
5849 images.remove(ptr_of(btn));
5850 if let Some(image) = &image {
5851 images.insert(ptr_of(btn), image.clone());
5852 }
5853 });
5854 set_button_title(btn, title, style);
5855 unsafe {
5858 btn.setImagePosition(if image.is_none() {
5859 objc2_app_kit::NSCellImagePosition::NoImage
5860 } else if icon_only {
5861 objc2_app_kit::NSCellImagePosition::ImageOnly
5862 } else {
5863 objc2_app_kit::NSCellImagePosition::ImageLeading
5864 });
5865 }
5866 set_button_image(btn, style);
5867 unsafe {
5868 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
5871 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
5872 }
5873 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
5874 btn.setToolTip(tooltip.as_deref());
5875 }
5876}
5877
5878fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
5882 use day_spec::props::ButtonStyleSpec as S;
5883 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
5884 let image = image.map(|source| {
5885 let S::Tinted(fill) = style else {
5886 return source;
5887 };
5888 let size = source.size();
5889 let ink = nscolor(S::on_tint(fill));
5890 let draw = block2::RcBlock::new(move |rect: NSRect| {
5891 source.drawInRect_fromRect_operation_fraction(
5892 rect,
5893 NSRect::ZERO,
5894 objc2_app_kit::NSCompositingOperation::SourceOver,
5895 1.0,
5896 );
5897 unsafe {
5898 ink.setFill();
5899 objc2_app_kit::NSRectFillUsingOperation(
5900 rect,
5901 objc2_app_kit::NSCompositingOperation::SourceIn,
5902 );
5903 }
5904 objc2::runtime::Bool::YES
5905 });
5906 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
5907 });
5908 unsafe {
5909 let position = btn.imagePosition();
5910 let image = image.map(|source| {
5915 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
5918 return source;
5919 }
5920 let size = source.size();
5921 let template = source.isTemplate();
5922 let padded = NSSize::new(size.width + 8.0, size.height);
5923 let draw = block2::RcBlock::new(move |_rect: NSRect| {
5924 source.drawInRect_fromRect_operation_fraction(
5925 NSRect::new(NSPoint::new(0.0, 0.0), size),
5926 NSRect::ZERO,
5927 objc2_app_kit::NSCompositingOperation::SourceOver,
5928 1.0,
5929 );
5930 objc2::runtime::Bool::YES
5931 });
5932 let out =
5933 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
5934 out.setTemplate(template);
5935 out
5936 });
5937 btn.setImage(image.as_deref());
5938 btn.setImagePosition(position);
5939 btn.setImageHugsTitle(true);
5940 }
5941}
5942
5943fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
5949 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
5950 unsafe {
5951 if on {
5952 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
5953 }
5954 btn.setState(if on {
5955 NSControlStateValueOn
5956 } else {
5957 NSControlStateValueOff
5958 });
5959 }
5960}
5961
5962const TINT_CORNER_RADIUS: f64 = 6.0;
5965
5966fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
5976 use day_spec::props::ButtonStyleSpec as S;
5977 let title = unsafe { btn.title() }.to_string();
5978 unsafe {
5979 btn.setKeyEquivalent(&NSString::from_str(""));
5981 btn.setBezelColor(None);
5982 btn.setBordered(!matches!(style, S::Plain));
5983 match style {
5984 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
5985 S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
5986 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
5989 }
5990 btn.setWantsLayer(true);
5991 if let Some(layer) = btn.layer() {
5992 match style {
5993 S::Tinted(c) => {
5994 layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
5995 layer.setCornerRadius(TINT_CORNER_RADIUS);
5996 }
5997 _ => layer.setBackgroundColor(None),
5998 }
5999 }
6000 }
6001 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6002 let ink = match style {
6003 S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6004 _ => None,
6005 };
6006 unsafe {
6007 btn.setContentTintColor(ink.as_deref());
6008 }
6009 set_button_title(btn, &title, style);
6010 set_button_image(btn, style);
6011}
6012
6013fn set_button_title(
6023 btn: &objc2_app_kit::NSButton,
6024 title: &str,
6025 style: day_spec::props::ButtonStyleSpec,
6026) {
6027 use day_spec::props::ButtonStyleSpec as S;
6028 let position = unsafe { btn.imagePosition() };
6031 let S::Tinted(fill) = style else {
6032 unsafe {
6034 btn.setTitle(&NSString::from_str(title));
6035 btn.setImagePosition(position);
6036 }
6037 return;
6038 };
6039 unsafe {
6040 let col = nscolor(S::on_tint(fill));
6041 let font = btn
6042 .font()
6043 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6044 let para = objc2_app_kit::NSMutableParagraphStyle::new();
6047 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6048 let keys: [&NSString; 3] = [
6049 objc2_app_kit::NSFontAttributeName,
6050 objc2_app_kit::NSForegroundColorAttributeName,
6051 objc2_app_kit::NSParagraphStyleAttributeName,
6052 ];
6053 let objs: [&objc2::runtime::AnyObject; 3] = [
6054 font.as_ref() as &objc2::runtime::AnyObject,
6055 col.as_ref() as &objc2::runtime::AnyObject,
6056 para.as_ref() as &objc2::runtime::AnyObject,
6057 ];
6058 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6059 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6060 objc2_foundation::NSAttributedString::alloc(),
6061 &NSString::from_str(title),
6062 Some(&attrs),
6063 );
6064 btn.setAttributedTitle(&s);
6065 btn.setImagePosition(position);
6066 }
6067}
6068
6069define_class!(
6072 #[unsafe(super(objc2_app_kit::NSImageView))]
6073 #[thread_kind = MainThreadOnly]
6074 #[name = "DayFillImageView"]
6075 struct FillImageView;
6076
6077 impl FillImageView {
6078 #[unsafe(method(drawRect:))]
6079 fn draw_rect(&self, dirty: NSRect) {
6080 let bounds = self.bounds();
6081 let image = unsafe { self.image() };
6082 let Some(size) = image.map(|image| image.size()).filter(|size| {
6083 size.width > 0.0 && size.height > 0.0
6084 && bounds.size.width > 0.0 && bounds.size.height > 0.0
6085 }) else {
6086 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6087 return;
6088 };
6089 let x = bounds.size.width / size.width;
6090 let y = bounds.size.height / size.height;
6091 let scale = x.max(y) / x.min(y);
6092 let cx = bounds.origin.x + bounds.size.width / 2.0;
6093 let cy = bounds.origin.y + bounds.size.height / 2.0;
6094 NSGraphicsContext::saveGraphicsState_class();
6095 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6096 let transform = NSAffineTransform::transform();
6097 transform.translateXBy_yBy(cx, cy);
6098 transform.scaleBy(scale);
6099 transform.translateXBy_yBy(-cx, -cy);
6100 transform.concat();
6101 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6102 NSGraphicsContext::restoreGraphicsState_class();
6103 }
6104
6105 #[unsafe(method(setFrameSize:))]
6106 fn set_frame_size(&self, size: NSSize) {
6107 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6108 NSView::setNeedsDisplay(self, true);
6109 }
6110 }
6111);
6112
6113fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6114 use day_spec::Shape;
6115 use objc2_app_kit::NSBezierPath;
6116 unsafe {
6117 Some(match shape {
6118 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6119 Shape::RoundedRect(r, rad) => {
6120 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6121 }
6122 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6123 Shape::Arc {
6124 rect,
6125 start_deg,
6126 sweep_deg,
6127 } => {
6128 let p = NSBezierPath::new();
6129 let center = NSPoint::new(
6130 rect.origin.x + rect.size.width / 2.0,
6131 rect.origin.y + rect.size.height / 2.0,
6132 );
6133 let radius = rect.size.width.min(rect.size.height) / 2.0;
6134 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6136 center,
6137 radius,
6138 *start_deg,
6139 *start_deg + *sweep_deg,
6140 );
6141 p
6142 }
6143 Shape::Line(a, b) => {
6144 let p = NSBezierPath::new();
6145 p.moveToPoint(NSPoint::new(a.x, a.y));
6146 p.lineToPoint(NSPoint::new(b.x, b.y));
6147 p
6148 }
6149 Shape::Polygon(pts) => {
6150 if pts.len() < 2 {
6151 return None;
6152 }
6153 let p = NSBezierPath::new();
6154 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6155 for pt in &pts[1..] {
6156 p.lineToPoint(NSPoint::new(pt.x, pt.y));
6157 }
6158 p.closePath();
6159 p
6160 }
6161 Shape::Path(path) => {
6162 use day_spec::PathSeg;
6163 if path.segs.is_empty() {
6164 return None;
6165 }
6166 let p = NSBezierPath::new();
6167 let mut cur = NSPoint::new(0.0, 0.0);
6171 for seg in &path.segs {
6172 match seg {
6173 PathSeg::Move(a) => {
6174 cur = NSPoint::new(a.x, a.y);
6175 p.moveToPoint(cur);
6176 }
6177 PathSeg::Line(a) => {
6178 cur = NSPoint::new(a.x, a.y);
6179 p.lineToPoint(cur);
6180 }
6181 PathSeg::Quad(c, a) => {
6182 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6183 let c1 = NSPoint::new(
6184 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6185 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6186 );
6187 let c2 = NSPoint::new(
6188 end.x + 2.0 / 3.0 * (ctl.x - end.x),
6189 end.y + 2.0 / 3.0 * (ctl.y - end.y),
6190 );
6191 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6192 cur = end;
6193 }
6194 PathSeg::Cubic(c1, c2, a) => {
6195 cur = NSPoint::new(a.x, a.y);
6196 p.curveToPoint_controlPoint1_controlPoint2(
6197 cur,
6198 NSPoint::new(c1.x, c1.y),
6199 NSPoint::new(c2.x, c2.y),
6200 );
6201 }
6202 PathSeg::Close => p.closePath(),
6203 }
6204 }
6205 p.setWindingRule(match path.rule {
6206 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6207 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6208 });
6209 p
6210 }
6211 })
6212 }
6213}
6214
6215struct UndoIvars {
6223 state: std::cell::RefCell<day_spec::UndoState>,
6224}
6225
6226define_class!(
6227 #[unsafe(super(objc2_foundation::NSUndoManager))]
6228 #[thread_kind = MainThreadOnly]
6229 #[name = "DayUndoManager"]
6230 #[ivars = UndoIvars]
6231 struct DayUndoManager;
6232
6233 impl DayUndoManager {
6237 #[unsafe(method(canUndo))]
6238 fn can_undo(&self) -> bool {
6239 self.ivars().state.borrow().can_undo
6240 }
6241
6242 #[unsafe(method(canRedo))]
6243 fn can_redo(&self) -> bool {
6244 self.ivars().state.borrow().can_redo
6245 }
6246
6247 #[unsafe(method(undo))]
6248 fn do_undo(&self) {
6249 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6250 }
6251
6252 #[unsafe(method(redo))]
6253 fn do_redo(&self) {
6254 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6255 }
6256
6257 #[unsafe(method_id(undoMenuItemTitle))]
6258 fn undo_menu_item_title(&self) -> Retained<NSString> {
6259 let label = self.ivars().state.borrow().undo_label.clone();
6262 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6263 }
6264
6265 #[unsafe(method_id(redoMenuItemTitle))]
6266 fn redo_menu_item_title(&self) -> Retained<NSString> {
6267 let label = self.ivars().state.borrow().redo_label.clone();
6268 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6269 }
6270 }
6271);
6272
6273fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6274 UNDO_FRONT.with(|u| {
6275 u.borrow_mut()
6276 .get_or_insert_with(|| {
6277 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6278 state: std::cell::RefCell::new(day_spec::UndoState::default()),
6279 });
6280 unsafe { msg_send![super(this), init] }
6281 })
6282 .clone()
6283 })
6284}
6285
6286struct WinIvars {
6294 node: Option<NodeId>,
6295 group: Option<String>,
6298 last_state: Cell<i32>,
6301}
6302
6303define_class!(
6304 #[unsafe(super(NSObject))]
6305 #[thread_kind = MainThreadOnly]
6306 #[name = "DayWinDelegate"]
6307 #[ivars = WinIvars]
6308 struct DayWinDelegate;
6309
6310 unsafe impl NSObjectProtocol for DayWinDelegate {}
6311
6312 impl DayWinDelegate {
6316 #[unsafe(method(undo:))]
6320 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6321 ffi_guard::contain((), || {
6322 if let Some(m) = self.acting_undo_manager() {
6323 unsafe { m.undo() };
6324 }
6325 });
6326 }
6327
6328 #[unsafe(method(redo:))]
6330 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6331 ffi_guard::contain((), || {
6332 if let Some(m) = self.acting_undo_manager() {
6333 unsafe { m.redo() };
6334 }
6335 });
6336 }
6337
6338 #[unsafe(method(cut:))]
6339 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6340 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6341 }
6342
6343 #[unsafe(method(copy:))]
6344 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6345 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6346 }
6347
6348 #[unsafe(method(paste:))]
6349 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6350 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6351 }
6352
6353 #[unsafe(method(selectAll:))]
6354 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6355 ffi_guard::contain((), || {
6356 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6357 });
6358 }
6359
6360 #[unsafe(method(validateMenuItem:))]
6364 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6365 ffi_guard::contain(false, || {
6366 let state = EDIT_STATE.with(|s| s.get());
6367 match unsafe { item.action() } {
6368 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6371 Some(m) => {
6372 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6373 unsafe { m.canUndo() }
6374 }
6375 None => false,
6376 },
6377 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6378 Some(m) => {
6379 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6380 unsafe { m.canRedo() }
6381 }
6382 None => false,
6383 },
6384 Some(a) if a == sel!(selectAll:) => state.can_select_all,
6385 Some(a) if a == sel!(cut:) => state.can_cut,
6386 Some(a) if a == sel!(copy:) => state.can_copy,
6387 Some(a) if a == sel!(paste:) => {
6388 state.can_paste && {
6389 let pb = unsafe { NSPasteboard::generalPasteboard() };
6390 pb.types().is_some_and(|types| !types.is_empty())
6391 }
6392 }
6393 _ => true,
6394 }
6395 })
6396 }
6397 }
6398
6399 unsafe impl NSWindowDelegate for DayWinDelegate {
6400 #[unsafe(method(windowDidResize:))]
6401 fn window_did_resize(&self, notification: &NSNotification) {
6402 ffi_guard::contain((), || {
6403 if let Some(obj) = unsafe { notification.object() }
6404 && let Ok(win) = obj.downcast::<NSWindow>()
6405 && let Some(size) = pin_below_title_bar(&win)
6406 {
6407 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6408 emit(target, Event::WindowResized(size));
6409 }
6410 self.report_state_of(notification);
6412 })
6413 }
6414
6415 #[unsafe(method(windowShouldClose:))]
6416 fn window_should_close(&self, _window: &NSWindow) -> bool {
6417 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6418 }
6419
6420 #[unsafe(method(windowWillClose:))]
6421 fn window_will_close(&self, _notification: &NSNotification) {
6422 ffi_guard::contain((), || {
6423 match self.ivars().node {
6424 Some(node) => emit(node, Event::WindowClosed),
6427 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6432 None => {
6433 let app = NSApplication::sharedApplication(self.mtm());
6434 unsafe { app.terminate(None) };
6435 }
6436 }
6437 })
6438 }
6439
6440 #[unsafe(method_id(windowWillReturnUndoManager:))]
6441 fn window_will_return_undo_manager(
6442 &self,
6443 _window: &NSWindow,
6444 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6445 ffi_guard::contain(None, || {
6449 UNDO_FRONT.with(|u| {
6450 u.borrow()
6451 .as_ref()
6452 .map(|m| Retained::into_super(m.clone()))
6453 })
6454 })
6455 }
6456
6457 #[unsafe(method(windowDidBecomeKey:))]
6458 fn window_did_become_key(&self, _notification: &NSNotification) {
6459 ffi_guard::contain((), || {
6460 if let Some(node) = self.ivars().node {
6461 emit(node, Event::WindowFocused(true));
6462 }
6463 })
6464 }
6465
6466 #[unsafe(method(windowDidResignKey:))]
6467 fn window_did_resign_key(&self, _notification: &NSNotification) {
6468 ffi_guard::contain((), || {
6469 if let Some(node) = self.ivars().node {
6470 emit(node, Event::WindowFocused(false));
6471 }
6472 })
6473 }
6474
6475 #[unsafe(method(windowDidMiniaturize:))]
6476 fn window_did_miniaturize(&self, notification: &NSNotification) {
6477 ffi_guard::contain((), || self.report_state_of(notification))
6478 }
6479
6480 #[unsafe(method(windowDidDeminiaturize:))]
6481 fn window_did_deminiaturize(&self, notification: &NSNotification) {
6482 ffi_guard::contain((), || self.report_state_of(notification))
6483 }
6484
6485 #[unsafe(method(windowDidEnterFullScreen:))]
6486 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6487 ffi_guard::contain((), || self.report_state_of(notification))
6488 }
6489
6490 #[unsafe(method(windowDidExitFullScreen:))]
6491 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6492 ffi_guard::contain((), || self.report_state_of(notification))
6493 }
6494 }
6495
6496 impl DayWinDelegate {
6500 #[unsafe(method(newWindowForTab:))]
6501 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6502 ffi_guard::contain((), || {
6503 let _ = match self.ivars().group.as_deref() {
6506 Some(group) => day_core::windows::open_new_window_for_group(group),
6507 None => day_core::windows::open_new_window(),
6508 };
6509 })
6510 }
6511 }
6512);
6513
6514impl DayWinDelegate {
6515 fn report_state_of(&self, notification: &NSNotification) {
6516 if let Some(obj) = unsafe { notification.object() }
6517 && let Ok(win) = obj.downcast::<NSWindow>()
6518 {
6519 self.report_state(&win);
6520 }
6521 }
6522}
6523
6524fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6527 match unsafe { event.keyCode() } {
6528 123 => Some("ArrowLeft"),
6529 124 => Some("ArrowRight"),
6530 125 => Some("ArrowDown"),
6531 126 => Some("ArrowUp"),
6532 _ => {
6540 let held = NSEventModifierFlags::Command
6541 | NSEventModifierFlags::Option
6542 | NSEventModifierFlags::Control;
6543 if event.modifierFlags().intersects(held) {
6544 return None;
6545 }
6546 let typed = event.characters()?.to_string();
6547 let mut chars = typed.chars();
6548 match (chars.next(), chars.next()) {
6549 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6550 _ => None,
6551 }
6552 }
6553 }
6554}
6555
6556fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6558 let mut modifiers = 0u8;
6559 if f.contains(NSEventModifierFlags::Shift) {
6560 modifiers |= day_spec::KeyEvent::SHIFT;
6561 }
6562 if f.contains(NSEventModifierFlags::Command) {
6563 modifiers |= day_spec::KeyEvent::PRIMARY;
6564 }
6565 if f.contains(NSEventModifierFlags::Option) {
6566 modifiers |= day_spec::KeyEvent::ALT;
6567 }
6568 modifiers
6569}
6570
6571impl DayWinDelegate {
6572 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6577 let responder = NSApplication::sharedApplication(self.mtm())
6578 .keyWindow()
6579 .and_then(|w| w.firstResponder());
6580 responder
6581 .and_then(|r| unsafe { r.undoManager() })
6582 .or_else(|| {
6583 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6584 })
6585 }
6586}
6587
6588impl DayWinDelegate {
6589 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6590 let this = Self::alloc(mtm).set_ivars(WinIvars {
6591 node,
6592 group,
6593 last_state: Cell::new(day_spec::WindowState::Normal.code()),
6594 });
6595 unsafe { msg_send![super(this), init] }
6596 }
6597
6598 fn report_state(&self, window: &NSWindow) {
6602 let state = ns_window_state(window);
6603 if self.ivars().last_state.replace(state.code()) != state.code() {
6604 log::debug!("appkit: window state now {state:?}");
6605 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6606 emit(target, Event::WindowStateChanged(state));
6607 }
6608 }
6609}
6610
6611fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6614 if window.isMiniaturized() {
6615 day_spec::WindowState::Minimized
6616 } else if window
6617 .styleMask()
6618 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6619 {
6620 day_spec::WindowState::Fullscreen
6621 } else if window.isZoomed() {
6622 day_spec::WindowState::Maximized
6623 } else {
6624 day_spec::WindowState::Normal
6625 }
6626}
6627
6628fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6631 use day_spec::WindowState as S;
6632 let current = ns_window_state(window);
6633 if current == state {
6634 return;
6635 }
6636 unsafe {
6637 match current {
6638 S::Minimized => window.deminiaturize(None),
6639 S::Fullscreen => {
6643 window.toggleFullScreen(None);
6644 return;
6645 }
6646 S::Maximized if state != S::Minimized => window.zoom(None),
6647 _ => {}
6648 }
6649 match state {
6650 S::Normal => {}
6651 S::Minimized => window.miniaturize(None),
6652 S::Maximized => {
6653 if !window.isZoomed() {
6654 window.zoom(None)
6655 }
6656 }
6657 S::Fullscreen => window.toggleFullScreen(None),
6658 }
6659 }
6660}
6661
6662#[distributed_slice]
6668pub static RENDERERS: [fn() -> Renderer<AppKit>];
6669
6670struct SecondaryWin {
6674 window: Retained<NSWindow>,
6675 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
6677 content: Handle,
6678}
6679
6680struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6683impl Drop for MenuEscapeMonitor {
6684 fn drop(&mut self) {
6685 unsafe { NSEvent::removeMonitor(&self.0) };
6686 }
6687}
6688
6689pub struct AppKit {
6690 menu_escape_monitor: Option<MenuEscapeMonitor>,
6691 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6692
6693 mtm: MainThreadMarker,
6694 registry: Registry<AppKit>,
6695 window: Option<Retained<NSWindow>>,
6696 content: Option<Handle>,
6697 secondary: Vec<SecondaryWin>,
6698 app_name: String,
6699 cascade: Option<NSPoint>,
6704 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
6707}
6708
6709impl AppKit {
6710 fn swap_text_field(
6715 &mut self,
6716 h: &Handle,
6717 old: &NSTextField,
6718 node: NodeId,
6719 secure: bool,
6720 ) -> Retained<NSTextField> {
6721 let new = new_text_field(self.mtm, node, secure);
6722 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
6723 let window = h.window();
6726 let focused = window
6727 .as_deref()
6728 .is_some_and(|w| owns_first_responder(w, h));
6729 let selection = old.currentEditor().map(|e| e.selectedRange());
6730 unsafe {
6731 new.setStringValue(&old.stringValue());
6732 new.setPlaceholderString(old.placeholderString().as_deref());
6733 new.setEnabled(old.isEnabled());
6734 new.setFont(old.font().as_deref());
6735 new.setFrame(h.frame());
6736 new.setHidden(h.isHidden());
6737 new.setMenu(h.menu().as_deref());
6738 new.setToolTip(h.toolTip().as_deref());
6739 if h.wantsLayer() {
6741 new.setWantsLayer(true);
6742 new.setAlphaValue(h.alphaValue());
6743 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
6744 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
6745 if !from.is_null() && !to.is_null() {
6746 let t: CGAffineTransform = msg_send![from, affineTransform];
6747 let _: () = msg_send![to, setAffineTransform: t];
6748 }
6749 }
6750 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
6753 new.setAccessibilityIdentifier(Some(&id));
6754 }
6755 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
6756 new.setAccessibilityLabel(Some(&label));
6757 }
6758 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
6759 new.setAccessibilityHelp(Some(&help));
6760 }
6761 if !h.isAccessibilityElement() {
6762 new.setAccessibilityElement(false);
6763 }
6764 }
6765 for r in unsafe { h.gestureRecognizers() }.iter() {
6767 unsafe {
6768 h.removeGestureRecognizer(&r);
6769 new.addGestureRecognizer(&r);
6770 }
6771 }
6772 GESTURES.with(|m| {
6773 let mut m = m.borrow_mut();
6774 if let Some(targets) = m.remove(&old_key) {
6775 m.insert(new_key, targets);
6776 }
6777 });
6778 if let Some((owner, area)) = self.cursors.remove(&old_key) {
6779 unsafe {
6780 h.removeTrackingArea(&area);
6781 new.addTrackingArea(&area);
6782 }
6783 self.cursors.insert(new_key, (owner, area));
6784 }
6785 PAN_NODES.with(|t| rekey(t, old_key, new_key));
6786 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
6787 KEY_NODES.with(|t| rekey(t, old_key, new_key));
6788 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
6789 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
6790 transfer::moved(h, &new);
6791 unsafe { old.setDelegate(None) };
6794 TARGETS.with(|m| {
6795 m.borrow_mut().remove(&old_key);
6796 });
6797 if let Some(parent) = unsafe { h.superview() } {
6798 unsafe {
6799 parent.addSubview_positioned_relativeTo(
6800 &new,
6801 objc2_app_kit::NSWindowOrderingMode::Above,
6802 Some(h),
6803 );
6804 h.removeFromSuperview();
6805 }
6806 }
6807 if focused && let Some(window) = window {
6808 FIELD_SWAP.with(|s| s.set(true));
6809 let taken = window.makeFirstResponder(Some(&new));
6810 FIELD_SWAP.with(|s| s.set(false));
6811 if taken && let Some(editor) = new.currentEditor() {
6814 let len = unsafe { new.stringValue() }.length();
6815 let range = selection
6816 .filter(|r| r.location.saturating_add(r.length) <= len)
6817 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
6818 editor.setSelectedRange(range);
6819 }
6820 }
6821 day_spec::sidetable::sweep(old_key);
6823 new
6824 }
6825
6826 pub fn new() -> Self {
6827 let mtm =
6828 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
6829 let mut registry = Registry::default();
6830 for f in RENDERERS {
6831 registry.register(f());
6832 }
6833 AppKit {
6834 menu_escape_monitor: None,
6835 mtm,
6836 registry,
6837 window: None,
6838 sharing: None,
6839 content: None,
6840 secondary: Vec::new(),
6841 app_name: "Day".into(),
6842 cascade: None,
6843 cursors: HashMap::new(),
6844 }
6845 }
6846
6847 pub fn mtm(&self) -> MainThreadMarker {
6849 self.mtm
6850 }
6851
6852 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
6854 if let Some(w) = self
6855 .secondary
6856 .iter()
6857 .find(|w| ptr_of(&w.content) == ptr_of(host))
6858 {
6859 return Some(w.window.clone());
6860 }
6861 self.content
6862 .as_ref()
6863 .filter(|c| ptr_of(c) == ptr_of(host))
6864 .and(self.window.clone())
6865 }
6866
6867 fn make_window(
6873 &self,
6874 options: &WindowOptions,
6875 prefs_style: bool,
6876 node: Option<NodeId>,
6877 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
6878 let mtm = self.mtm;
6879 let (title, size, min_size, tabbing) = (
6880 options.title.as_str(),
6881 options.size,
6882 options.min_size,
6883 &options.tabbing,
6884 );
6885 let content_rect =
6886 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
6887 let style = window_chrome::style_mask(options, prefs_style);
6889 let window = window_chrome::alloc_window(
6890 mtm,
6891 content_rect,
6892 style,
6893 options.chrome == day_spec::WindowChrome::Frameless,
6894 );
6895 unsafe { window.setReleasedWhenClosed(false) };
6896 window.setTitle(&NSString::from_str(title));
6897 if let Some(min) = min_size {
6898 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
6899 }
6900 if let Some(max) = options.max_size {
6901 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
6902 }
6903 use day_spec::WindowTabbing as T;
6904 use objc2_app_kit::NSWindowTabbingMode as M;
6905 let group = match tabbing {
6906 T::Group(g) | T::Preferred(g) => Some(g.clone()),
6907 T::Automatic | T::Disallowed => None,
6908 };
6909 match tabbing {
6910 _ if prefs_style => window.setTabbingMode(M::Disallowed),
6911 T::Disallowed => window.setTabbingMode(M::Disallowed),
6912 T::Automatic => unsafe {
6916 window.setTabbingIdentifier(&NSString::from_str("day.normal"))
6917 },
6918 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
6919 T::Preferred(g) => {
6920 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
6921 window.setTabbingMode(M::Preferred);
6922 }
6923 }
6924 if group.is_some() {
6925 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
6928 }
6929 let delegate = DayWinDelegate::new(mtm, node, group);
6930 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
6931 let content = view_of(DayFlipped::new(mtm));
6932 window.setContentView(Some(&content));
6933 window_chrome::apply(&window, &content, options);
6934 window.setAutorecalculatesKeyViewLoop(true);
6943 (window, delegate, content)
6944 }
6945}
6946
6947impl Default for AppKit {
6948 fn default() -> Self {
6949 Self::new()
6950 }
6951}
6952
6953fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
6954 Retained::from(x.as_ref())
6955}
6956
6957fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
6958 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
6959}
6960
6961fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
6964 use objc2_app_kit::*;
6965 unsafe {
6966 Some(match f {
6967 Font::LargeTitle => NSFontTextStyleLargeTitle,
6968 Font::Title => NSFontTextStyleTitle1,
6969 Font::Title2 => NSFontTextStyleTitle2,
6970 Font::Title3 => NSFontTextStyleTitle3,
6971 Font::Headline => NSFontTextStyleHeadline,
6972 Font::Subheadline => NSFontTextStyleSubheadline,
6973 Font::Body => NSFontTextStyleBody,
6974 Font::Callout => NSFontTextStyleCallout,
6975 Font::Footnote => NSFontTextStyleFootnote,
6976 Font::Caption => NSFontTextStyleCaption1,
6977 Font::Caption2 => NSFontTextStyleCaption2,
6978 Font::System(_) | Font::Custom(..) => return None,
6979 })
6980 }
6981}
6982
6983fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
6984 use day_spec::FontWeight as W;
6985 use objc2_app_kit::*;
6986 unsafe {
6987 match w {
6988 W::UltraLight => NSFontWeightUltraLight,
6989 W::Thin => NSFontWeightThin,
6990 W::Light => NSFontWeightLight,
6991 W::Regular => NSFontWeightRegular,
6992 W::Medium => NSFontWeightMedium,
6993 W::Semibold => NSFontWeightSemibold,
6994 W::Bold => NSFontWeightBold,
6995 W::Heavy => NSFontWeightHeavy,
6996 W::Black => NSFontWeightBlack,
6997 }
6998 }
6999}
7000
7001fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7004 use day_spec::FontWeight as W;
7005 match w {
7006 W::UltraLight => 2,
7007 W::Thin => 3,
7008 W::Light => 4,
7009 W::Regular => 5,
7010 W::Medium => 6,
7011 W::Semibold => 8,
7012 W::Bold => 9,
7013 W::Heavy => 10,
7014 W::Black => 12,
7015 }
7016}
7017
7018fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7023 use objc2_app_kit::*;
7024 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7025 let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7026 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7027 let mut traits = NSFontTraitMask::empty();
7028 if weight >= day_spec::FontWeight::Semibold {
7029 traits |= NSFontTraitMask::BoldFontMask;
7030 }
7031 if font.italic {
7032 traits |= NSFontTraitMask::ItalicFontMask;
7033 }
7034 let Some(family) = font.family.as_deref() else {
7035 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7036 return if font.italic {
7037 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7038 } else {
7039 base
7040 };
7041 };
7042 let ns_family = NSString::from_str(family);
7043 if let Some(f) = unsafe {
7044 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7045 } {
7046 return f;
7047 }
7048 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7049 return if traits.is_empty() {
7050 f
7051 } else {
7052 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7053 };
7054 }
7055 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7056 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7057}
7058
7059fn canvas_text_attrs(
7062 font: &NSFont,
7063 color: day_spec::Color,
7064) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7065 let col = nscolor(color);
7066 let keys: [&NSString; 2] = unsafe {
7068 [
7069 objc2_app_kit::NSFontAttributeName,
7070 objc2_app_kit::NSForegroundColorAttributeName,
7071 ]
7072 };
7073 let objs: [&objc2::runtime::AnyObject; 2] = [
7074 font as &objc2::runtime::AnyObject,
7075 col.as_ref() as &objc2::runtime::AnyObject,
7076 ];
7077 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7078}
7079
7080fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7083 use objc2_app_kit::*;
7084 let base: Retained<NSFont> = match spec.style {
7085 Font::System(pt) => {
7086 let w = spec
7087 .weight
7088 .map(ns_weight)
7089 .unwrap_or(unsafe { NSFontWeightRegular });
7090 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7091 }
7092 Font::Custom(name, pt) => {
7096 match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7097 Some(f) => {
7098 if spec
7099 .weight
7100 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7101 {
7102 let mtm = objc2::MainThreadMarker::new()
7103 .expect("labels realize on the main thread");
7104 unsafe {
7105 NSFontManager::sharedFontManager(mtm)
7106 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7107 }
7108 } else {
7109 f
7110 }
7111 }
7112 None => {
7113 log::warn!(
7114 "unknown font family {name:?} — falling back to the system font \
7115 (is the file in the project's fonts/ directory?)"
7116 );
7117 let w = spec
7118 .weight
7119 .map(ns_weight)
7120 .unwrap_or(unsafe { NSFontWeightRegular });
7121 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7122 }
7123 }
7124 }
7125 style => {
7126 let ts = ns_text_style(style).expect("semantic style");
7129 let opts = objc2_foundation::NSDictionary::new();
7130 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7131 match spec.weight {
7132 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7134 None => f,
7135 }
7136 }
7137 };
7138 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7143 let w = spec
7144 .weight
7145 .map(ns_weight)
7146 .unwrap_or(unsafe { NSFontWeightRegular });
7147 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7148 } else {
7149 base
7150 };
7151 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7155 let w = spec
7156 .weight
7157 .map(ns_weight)
7158 .unwrap_or(unsafe { NSFontWeightRegular });
7159 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7160 } else {
7161 base
7162 };
7163 let base = if spec.scale != 1.0 {
7167 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7168 let pts = spec.resolved_points(base.pointSize());
7169 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7170 } else {
7171 base
7172 };
7173 if spec.italic {
7174 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7175 unsafe {
7176 NSFontManager::sharedFontManager(mtm)
7177 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7178 }
7179 } else {
7180 base
7181 }
7182}
7183
7184fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7194 use objc2_foundation::{NSMutableAttributedString, NSRange};
7195 unsafe {
7196 let cur = tf.attributedStringValue();
7197 let m = NSMutableAttributedString::initWithAttributedString(
7198 NSMutableAttributedString::alloc(),
7199 &cur,
7200 );
7201 let style = objc2_app_kit::NSMutableParagraphStyle::new();
7202 style.setAlignment(align);
7203 style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7206 m.addAttribute_value_range(
7207 objc2_app_kit::NSParagraphStyleAttributeName,
7208 &style,
7209 NSRange::new(0, cur.length()),
7210 );
7211 tf.setAttributedStringValue(&m);
7212 }
7213}
7214
7215fn attributed_label(
7216 text: &str,
7217 base_font: &NSFont,
7218 color: Option<day_spec::Color>,
7219 role: day_spec::props::TextRole,
7220 runs: &[day_spec::TextRun],
7221) -> Retained<objc2_foundation::NSAttributedString> {
7222 use objc2_foundation::{NSMutableAttributedString, NSRange};
7223 let ns = NSString::from_str(text);
7224 let s = unsafe {
7225 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7226 };
7227 let whole = NSRange::new(0, ns.length());
7228 unsafe {
7229 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7230 let fg = color.map(nscolor).unwrap_or_else(|| match role {
7238 day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7239 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7240 });
7241 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7242 }
7243 for r in runs {
7244 let Some(range) = utf16_range(text, &r.range) else {
7245 continue;
7246 };
7247 unsafe {
7248 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7249 if let Some(c) = r.color {
7250 s.addAttribute_value_range(
7251 objc2_app_kit::NSForegroundColorAttributeName,
7252 &nscolor(c),
7253 range,
7254 );
7255 }
7256 if let Some(c) = r.background {
7257 s.addAttribute_value_range(
7258 objc2_app_kit::NSBackgroundColorAttributeName,
7259 &nscolor(c),
7260 range,
7261 );
7262 }
7263 if r.underline.is_on() {
7264 let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7265 s.addAttribute_value_range(
7266 objc2_app_kit::NSUnderlineStyleAttributeName,
7267 &style,
7268 range,
7269 );
7270 }
7271 if r.strikethrough {
7272 let one = objc2_foundation::NSNumber::new_i64(1);
7273 s.addAttribute_value_range(
7274 objc2_app_kit::NSStrikethroughStyleAttributeName,
7275 &one,
7276 range,
7277 );
7278 }
7279 if let Some(url) = r.link.as_deref() {
7280 let value = NSString::from_str(url);
7283 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7284 }
7285 }
7286 }
7287 s.into_super()
7288}
7289
7290fn ns_underline(u: day_spec::Underline) -> i64 {
7294 use day_spec::Underline as U;
7295 match u {
7296 U::None => 0,
7297 U::Single => 0x01,
7298 U::Double => 0x09,
7299 U::Dotted => 0x01 | 0x0100,
7300 U::Wavy => 0x01 | 0x0400,
7301 }
7302}
7303
7304fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7306 let start = text.get(..r.start)?.encode_utf16().count();
7307 let len = text.get(r.clone())?.encode_utf16().count();
7308 Some(objc2_foundation::NSRange::new(start, len))
7309}
7310
7311fn register_bundled_fonts() {
7316 #[link(name = "CoreText", kind = "framework")]
7318 unsafe extern "C" {
7319 fn CTFontManagerRegisterFontsForURL(
7320 font_url: *const std::ffi::c_void,
7321 scope: u32, error: *mut *const std::ffi::c_void,
7323 ) -> bool;
7324 }
7325 for path in day_spec::fonts::bundled_fonts() {
7326 let url = unsafe {
7327 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7328 };
7329 let ok = unsafe {
7330 CTFontManagerRegisterFontsForURL(
7331 Retained::as_ptr(&url) as *const std::ffi::c_void,
7332 1,
7333 std::ptr::null_mut(),
7334 )
7335 };
7336 if !ok {
7337 log::warn!("could not register bundled font {}", path.display());
7338 }
7339 }
7340}
7341
7342fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7345 match a {
7346 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7347 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7348 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7349 }
7350}
7351
7352fn configure_label_cell(tf: &NSTextField) {
7353 if let Some(cell) = unsafe { tf.cell() } {
7354 unsafe {
7355 cell.setWraps(true);
7356 cell.setUsesSingleLineMode(false);
7357 cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7358 }
7359 }
7360}
7361
7362fn content_of(parent: &Handle) -> Retained<NSView> {
7364 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7365 && let Some(doc) = unsafe { sv.documentView() }
7366 {
7367 return doc;
7368 }
7369 parent.clone()
7370}
7371
7372fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7378 let Some(a) = anim else {
7379 body();
7380 return;
7381 };
7382 let (dur, timing) = appkit_timing(a);
7383 unsafe {
7384 NSAnimationContext::beginGrouping();
7385 let ctx = NSAnimationContext::currentContext();
7386 ctx.setDuration(dur);
7387 ctx.setTimingFunction(Some(&timing));
7388 ctx.setAllowsImplicitAnimation(true);
7389 body();
7390 NSAnimationContext::endGrouping();
7391 }
7392}
7393
7394fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7397 unsafe {
7398 let named = |n| {
7399 (
7400 a.duration_secs().max(0.01),
7401 CAMediaTimingFunction::functionWithName(n),
7402 )
7403 };
7404 match a.curve {
7405 Curve::Linear => named(kCAMediaTimingFunctionLinear),
7406 Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7407 Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7408 Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7409 Curve::Spring { damping, .. } => {
7410 let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7412 (
7413 a.duration_secs().max(0.05),
7414 CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7415 )
7416 }
7417 }
7418 }
7419}
7420
7421fn warn_missing_renderer(kind: PieceKind) {
7426 day_spec::placeholder::report(kind, "appkit");
7427}
7428
7429pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7433 view_of(unsafe {
7434 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7435 })
7436}
7437
7438impl Toolkit for AppKit {
7439 fn ui_idle(&mut self) -> bool {
7442 toolbar::chrome_settled()
7443 }
7444
7445 type Handle = Handle;
7446
7447 fn dark_mode(&mut self) -> bool {
7448 let app = NSApplication::sharedApplication(self.mtm());
7451 app.effectiveAppearance()
7452 .name()
7453 .to_string()
7454 .contains("Dark")
7455 }
7456
7457 fn reduce_motion(&mut self) -> bool {
7460 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7461 }
7462
7463 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7467 use day_spec::AppBadge;
7468 let label = match badge {
7469 AppBadge::None => None,
7470 AppBadge::Count(0) => None,
7472 AppBadge::Count(n) => Some(n.to_string()),
7473 AppBadge::Text(t) if t.is_empty() => None,
7474 AppBadge::Text(t) => Some(t.clone()),
7475 AppBadge::Dot => Some("\u{2022}".to_string()),
7477 };
7478 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7479 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7480 unsafe { tile.setBadgeLabel(ns.as_deref()) };
7481 tile.display();
7482 }
7483
7484 fn set_appearance(&mut self, dark: Option<bool>) {
7485 let app = NSApplication::sharedApplication(self.mtm());
7486 let appearance = dark.and_then(|d| {
7487 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7488 if d {
7489 objc2_app_kit::NSAppearanceNameDarkAqua
7490 } else {
7491 objc2_app_kit::NSAppearanceNameAqua
7492 }
7493 })
7494 });
7495 unsafe { app.setAppearance(appearance.as_deref()) };
7497 }
7498
7499 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7500 controls::refresh_gesture::attach(handle, host);
7501 }
7502
7503 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7504 unsafe {
7505 handle.setHidden(!visible);
7506 }
7507 }
7508
7509 fn capability(&self, cap: Cap) -> Support {
7510 match cap {
7511 Cap::SearchField => Support::Native,
7512 Cap::ComboBox => Support::Native,
7513 Cap::Stepper => Support::Native,
7514 Cap::DateTimePicker => Support::Native,
7515 Cap::ColorPicker => Support::Native,
7516 Cap::PullRefresh => Support::Emulated,
7517 Cap::Pager => Support::Emulated,
7518 Cap::PullRefreshGesture => Support::Emulated,
7519 Cap::Cursor => Support::Native,
7523 Cap::FontList => Support::Native,
7525 Cap::ListItem => Support::Native,
7527 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7531 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7534 Cap::Announce => Support::Native,
7537 Cap::ReduceMotion => Support::Native,
7540 Cap::Snapshot
7541 | Cap::NativeSymbols
7542 | Cap::NavTabs
7551 | Cap::NavSplit
7552 | Cap::NavRepresent
7556 | Cap::NavContentList
7559 | Cap::Dialogs
7560 | Cap::FileDialogs
7561 | Cap::FolderDialog
7563 | Cap::Animation
7564 | Cap::TextEditable
7566 | Cap::TextSelectable
7567 | Cap::TextSpellCheck
7568 | Cap::NavReorder | Cap::ListReorder
7571 | Cap::ListRecycling
7574 | Cap::ListSwipeActions
7577 | Cap::ListSections
7579 | Cap::Tree
7582 | Cap::TreeSections
7583 | Cap::TreeMove
7584 | Cap::MultiWindow
7586 | Cap::WindowStates
7589 | Cap::WindowFullscreen
7590 | Cap::ContentProtection
7592 | Cap::WindowTabbing
7595 | Cap::DockMenu
7597 | Cap::FramelessWindow
7601 | Cap::OverlayTitleBar
7602 | Cap::TransparentWindow
7603 | Cap::WindowMaterial
7604 | Cap::DragRegion
7606 | Cap::StatusItem
7609 | Cap::AppProgress
7610 | Cap::DockVisibility
7611 | Cap::WindowGeometry
7614 | Cap::WindowPosition
7615 | Cap::WindowLevel
7616 | Cap::WindowAppearance
7617 | Cap::RequestAttention
7618 | Cap::Monitors
7619 | Cap::DynamicShortcuts
7621 | Cap::Toolbar
7623 | Cap::ToolbarSearch
7625 | Cap::AppMenu
7626 | Cap::AppBadgeCount
7629 | Cap::AppBadgeText
7630 | Cap::UndoBridge
7633 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7634 | Cap::AppBadgeDot
7635 | Cap::Appearance
7636 | Cap::BaselineAlignment
7638 | Cap::Inspector
7641 | Cap::Split
7643 | Cap::TextRuns
7644 | Cap::TextLinks => Support::Native,
7645 Cap::Cover => Support::Emulated,
7648 Cap::CoverSheet => Support::Native,
7650 _ => Support::Unsupported,
7651 }
7652 }
7653
7654 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7655 let mtm = self.mtm;
7656 match Builtin::from_key(kind) {
7657 Some(Builtin::Container) => {
7658 let v = DayFlipped::new(mtm);
7659 if let Some(p) = props.downcast_ref::<ContainerProps>() {
7660 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7661 v.set_section_card(p.corner_radius);
7662 } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7663 v.set_surface(p.background, p.corner_radius, p.clips);
7664 }
7665 }
7666 view_of(v)
7667 }
7668 Some(Builtin::Scroll) => {
7669 let horizontal = props
7670 .downcast_ref::<day_spec::props::ScrollProps>()
7671 .map(|p| p.horizontal)
7672 .unwrap_or(false);
7673 let sv = unsafe { NSScrollView::new(mtm) };
7674 unsafe {
7675 sv.setHasVerticalScroller(!horizontal);
7676 sv.setHasHorizontalScroller(horizontal);
7677 sv.setDrawsBackground(false);
7678 sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7684 }
7685 let doc = DayFlipped::new(mtm);
7686 unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7687 view_of(sv)
7688 }
7689 Some(Builtin::Label) => {
7690 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7695 return placeholder_view(mtm, kind);
7696 };
7697 let tf = DayLabel::new(mtm, id, &p.text);
7698 configure_label_cell(&tf);
7699 if !p.wraps || p.max_lines > 0 {
7700 unsafe {
7701 tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
7702 if !p.wraps || p.max_lines == 1 {
7703 tf.setUsesSingleLineMode(true);
7704 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
7705 }
7706 }
7707 }
7708 unsafe { tf.setFont(Some(&nsfont(p.font))) };
7709 match (p.color, p.role) {
7713 (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
7714 (None, day_spec::props::TextRole::Secondary) => unsafe {
7715 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
7716 },
7717 (None, day_spec::props::TextRole::Primary) => {}
7718 }
7719 if !p.runs.is_empty() {
7720 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
7721 unsafe { tf.setAttributedStringValue(&s) };
7722 }
7723 tf.ivars().has_runs.set(!p.runs.is_empty());
7724 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
7725 if p.align != day_spec::props::TextAlign::Leading {
7730 unsafe { tf.setAlignment(nstextalign(p.align)) };
7731 if !p.runs.is_empty() {
7732 set_paragraph_alignment(&tf, nstextalign(p.align));
7733 }
7734 }
7735 view_of(Retained::into_super(tf))
7736 }
7737 Some(Builtin::Button) => {
7738 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
7739 return placeholder_view(mtm, kind);
7740 };
7741 let target = DayTarget::new(mtm, id);
7742 let btn = unsafe {
7743 NSButton::buttonWithTitle_target_action(
7744 &NSString::from_str(&p.title),
7745 Some(&*target),
7746 Some(sel!(action:)),
7747 mtm,
7748 )
7749 };
7750 apply_button_style(&btn, p.style);
7751 if p.icon.is_some() {
7752 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
7753 }
7754 unsafe { btn.setEnabled(p.enabled) };
7755 set_button_selected(&btn, p.selected);
7756 let view = view_of(btn);
7757 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7758 view
7759 }
7760 Some(Builtin::Toggle) => {
7761 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
7762 return placeholder_view(mtm, kind);
7763 };
7764 let target = DayTarget::new(mtm, id);
7765 let sw = unsafe { NSSwitch::new(mtm) };
7766 unsafe {
7767 sw.setState(if p.on { 1 } else { 0 });
7768 sw.setEnabled(p.enabled);
7769 sw.setTarget(Some(&*target));
7770 sw.setAction(Some(sel!(action:)));
7771 }
7772 let view = view_of(sw);
7773 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7774 view
7775 }
7776 Some(Builtin::Slider) => {
7777 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
7778 return placeholder_view(mtm, kind);
7779 };
7780 let target = DayTarget::new(mtm, id);
7781 let sl = unsafe {
7782 NSSlider::sliderWithValue_minValue_maxValue_target_action(
7783 p.value,
7784 p.min,
7785 p.max,
7786 Some(&*target),
7787 Some(sel!(action:)),
7788 mtm,
7789 )
7790 };
7791 unsafe { sl.setContinuous(true) };
7792 let view = view_of(sl);
7793 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7794 view
7795 }
7796 Some(Builtin::Picker) => picker::realize_any(self, props, id),
7797 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
7798 Some(Builtin::TextField) => {
7799 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
7800 return placeholder_view(mtm, kind);
7801 };
7802 let tf = new_text_field(mtm, id, false);
7803 unsafe {
7804 tf.setStringValue(&NSString::from_str(&p.text));
7805 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
7806 }
7807 view_of(tf)
7808 }
7809 Some(Builtin::Divider) => {
7810 let b = unsafe { NSBox::new(mtm) };
7811 unsafe { b.setBoxType(NSBoxType::Separator) };
7812 view_of(b)
7813 }
7814 Some(Builtin::Progress) => {
7815 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
7816 return placeholder_view(mtm, kind);
7817 };
7818 if p.value.is_none() {
7819 return crate::controls::spinner::make(self, p, id);
7820 }
7821 let pi = unsafe { NSProgressIndicator::new(mtm) };
7822 unsafe {
7823 match p.value {
7824 Some(v) => {
7825 pi.setStyle(NSProgressIndicatorStyle::Bar);
7826 pi.setIndeterminate(false);
7827 pi.setMinValue(0.0);
7828 pi.setMaxValue(1.0);
7829 pi.setDoubleValue(v);
7830 }
7831 None => {
7832 pi.setStyle(NSProgressIndicatorStyle::Spinning);
7833 pi.setIndeterminate(true);
7834 pi.startAnimation(None);
7835 }
7836 }
7837 }
7838 view_of(pi)
7839 }
7840 Some(Builtin::Canvas) => {
7841 let canvas = DayCanvas::new(mtm);
7842 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
7843 view_of(canvas)
7844 }
7845 Some(Builtin::Inspector) => {
7846 let (visible, width, leading) = props
7847 .downcast_ref::<InspectorProps>()
7848 .map(|p| {
7849 (
7850 p.visible,
7851 p.width,
7852 p.edge == day_spec::props::PaneEdge::Leading,
7853 )
7854 })
7855 .unwrap_or((false, 280.0, false));
7856 let content_wrap = view_of(DayFlipped::new(mtm));
7857 let panel_flipped = DayFlipped::new(mtm);
7858 panel_flipped.set_pane_backdrop();
7862 let panel_wrap = view_of(panel_flipped);
7863 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
7864 let _ = unsafe { split_vc.view() };
7867 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7868 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7869 unsafe {
7870 content_vc.setView(&content_wrap);
7871 panel_vc.setView(&panel_wrap);
7872 }
7873 let content_item = unsafe {
7874 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
7875 };
7876 let panel_item = unsafe {
7881 if leading {
7882 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
7883 } else {
7884 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
7885 }
7886 };
7887 unsafe {
7888 panel_item.setCanCollapse(false);
7892 panel_item.setCollapsed(!visible);
7893 panel_item.setMinimumThickness(width);
7894 panel_item.setMaximumThickness(width);
7895 panel_item.setAllowsFullHeightLayout(true);
7896 if leading {
7897 split_vc.addSplitViewItem(&panel_item);
7898 split_vc.addSplitViewItem(&content_item);
7899 } else {
7900 split_vc.addSplitViewItem(&content_item);
7901 split_vc.addSplitViewItem(&panel_item);
7902 }
7903 }
7904 let split = unsafe { split_vc.splitView() };
7905 unsafe {
7906 split.setVertical(true);
7907 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7908 split.setTranslatesAutoresizingMaskIntoConstraints(true);
7912 }
7913 let view = view_of(split);
7914 INSPECTOR_STATE.with(|m| {
7915 m.borrow_mut().insert(
7916 ptr_of(&view),
7917 InspectorState {
7918 content_wrap,
7919 panel_wrap,
7920 _split_vc: split_vc,
7921 panel_item,
7922 },
7923 )
7924 });
7925 view
7926 }
7927 Some(Builtin::InspectorPane) => {
7928 let pane = view_of(DayNavPage::new(mtm, id));
7932 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7933 let panel = props
7934 .downcast_ref::<InspectorPaneProps>()
7935 .map(|p| p.panel)
7936 .unwrap_or(false);
7937 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
7938 pane
7939 }
7940 Some(Builtin::Split) => {
7941 let (axis, fraction, min_pane) = props
7942 .downcast_ref::<SplitProps>()
7943 .map(|p| (p.axis, p.fraction, p.min_pane))
7944 .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
7945 let wrap = view_of(DayFlipped::new(mtm));
7946 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
7947 let first_wrap = view_of(DayFlipped::new(mtm));
7948 let second_wrap = view_of(DayFlipped::new(mtm));
7949 unsafe {
7950 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
7952 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7953 split.addArrangedSubview(&first_wrap);
7954 split.addArrangedSubview(&second_wrap);
7955 split.setFrame(wrap.bounds());
7956 split.setAutoresizingMask(
7957 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
7958 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
7959 );
7960 wrap.addSubview(&split);
7961 }
7962 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
7963 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7964 SPLIT_STATE.with(|m| {
7965 m.borrow_mut().insert(
7966 ptr_of(&wrap),
7967 SplitState {
7968 split,
7969 first_wrap,
7970 second_wrap,
7971 delegate,
7972 },
7973 )
7974 });
7975 wrap
7976 }
7977 Some(Builtin::SplitPane) => {
7978 let pane = view_of(DayNavPage::new(mtm, id));
7981 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7982 let second = props
7983 .downcast_ref::<SplitPaneProps>()
7984 .map(|p| p.second)
7985 .unwrap_or(false);
7986 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
7987 pane
7988 }
7989 Some(Builtin::Nav) => {
7990 let presentation = props
7991 .downcast_ref::<NavProps>()
7992 .map(|p| p.presentation)
7993 .unwrap_or(NavPresentation::Split);
7994 let is_split = presentation.is_split();
7995 let sidebar_wrap = view_of(DayFlipped::new(mtm));
8004 let detail_wrap = view_of(DayFlipped::new(mtm));
8005 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8006 let _ = unsafe { split_vc.view() };
8012 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8015 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8016 unsafe {
8017 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8018 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8019 }
8020 let sidebar_item = unsafe {
8021 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8022 };
8023 let detail_item = unsafe {
8024 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8025 };
8026 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8032 let list_visible = props
8038 .downcast_ref::<NavProps>()
8039 .is_none_or(|p| p.list_visible);
8040 let (list_wrap, list_item) = match list_width {
8041 Some(w) => {
8042 let wrap = view_of(DayFlipped::new(mtm));
8043 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8044 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8045 let item = unsafe {
8046 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8047 };
8048 unsafe {
8049 item.setCanCollapse(true);
8050 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8051 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8052 item.setCollapsed(!list_visible);
8053 }
8054 (Some(wrap), Some(item))
8055 }
8056 None => (None, None),
8057 };
8058 unsafe {
8059 sidebar_item.setCanCollapse(is_split);
8062 sidebar_item.setCollapsed(!is_split);
8063 if is_split {
8064 sidebar_item.setAllowsFullHeightLayout(true);
8068 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8069 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8070 } else {
8071 sidebar_item.setMinimumThickness(0.0);
8072 sidebar_item.setMaximumThickness(0.0);
8073 }
8074 split_vc.addSplitViewItem(&sidebar_item);
8075 if let Some(item) = list_item.as_ref() {
8076 split_vc.addSplitViewItem(item);
8077 }
8078 split_vc.addSplitViewItem(&detail_item);
8079 }
8080 let split = unsafe { split_vc.splitView() };
8081 unsafe {
8088 let after = split.nextResponder();
8089 split.setNextResponder(Some(&split_vc));
8090 let own_view = split_vc.view();
8100 let vc_resp: *const objc2_app_kit::NSResponder = {
8101 let r: &objc2_app_kit::NSResponder = &split_vc;
8102 r
8103 };
8104 let view_resp: *const objc2_app_kit::NSResponder = {
8105 let r: &objc2_app_kit::NSResponder = &own_view;
8106 r
8107 };
8108 let upstream = after.filter(|a| {
8109 let p: *const objc2_app_kit::NSResponder = &**a;
8110 p != vc_resp && p != view_resp
8111 });
8112 split_vc.setNextResponder(upstream.as_deref());
8113 }
8114 unsafe {
8115 split.setVertical(true);
8116 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8117 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8125 }
8126 let root_title = props
8127 .downcast_ref::<NavProps>()
8128 .map(|p| p.title.clone())
8129 .unwrap_or_default();
8130 let header = if presentation == NavPresentation::Stack {
8133 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8134 } else {
8135 None
8136 };
8137 let tabs = (presentation == NavPresentation::Tabs).then(|| {
8140 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8141 let b = detail_wrap.bounds();
8146 let frame = NSRect::new(
8147 NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8148 NSSize::new(
8149 (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8150 (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8151 ),
8152 );
8153 unsafe {
8154 tv.setTabViewType(
8155 if props
8156 .downcast_ref::<NavProps>()
8157 .is_some_and(|p| p.documents.is_some())
8158 {
8159 objc2_app_kit::NSTabViewType::NoTabsNoBorder
8160 } else {
8161 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8162 },
8163 );
8164 tv.setFrame(frame);
8165 tv.setAutoresizingMask(
8166 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8167 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8168 );
8169 detail_wrap.addSubview(&tv);
8170 }
8171 TabHost {
8172 view: tv,
8173 target: None,
8174 }
8175 });
8176 let view = view_of(split);
8177 NAV_STATE.with(|m| {
8178 m.borrow_mut().insert(
8179 ptr_of(&view),
8180 NavState {
8181 sidebar_wrap,
8182 detail_wrap,
8183 _split_vc: split_vc,
8184 sidebar_item,
8185 list_wrap,
8186 list_item,
8187 pages: Vec::new(),
8188 list_page: None,
8189 sidebar_page: None,
8190 list_width,
8191 list_visible,
8192 list_positioned: false,
8193 positioned: false,
8194 presentation,
8195 selected: 0,
8196 tabs,
8197 header,
8198 root_title,
8199 node: id,
8200 title_strip: 0.0,
8201 },
8202 )
8203 });
8204 view
8205 }
8206 Some(Builtin::NavPage) => {
8207 let page = view_of(DayNavPage::new(mtm, id));
8208 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8209 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8210 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8211 }
8212 page
8213 }
8214 Some(Builtin::Cover) => {
8218 let page = DayNavPage::new(mtm, id);
8219 let cover_props = props.downcast_ref::<CoverProps>();
8220 page.ivars()
8223 .sheet
8224 .set(cover_props.is_some_and(|p| p.sheet || p.half));
8225 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8226 unsafe { page.setHidden(true) };
8227 view_of(page)
8228 }
8229 Some(Builtin::NavMenu) => {
8230 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8231 return placeholder_view(mtm, kind);
8232 };
8233 let data = DayNavMenuData::new(
8234 mtm,
8235 id,
8236 &p.items,
8237 &p.icons,
8238 &p.badges,
8239 &p.badge_icons,
8240 &p.badge_tints,
8241 &p.sections,
8242 &p.tints,
8243 &p.menus,
8244 );
8245 *data.ivars().movable.borrow_mut() = p.movable.clone();
8246 data.ivars().regroup.set(p.regroup);
8247 *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8248 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8250 let o: Retained<DayNavOutlineView> =
8251 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8252 NAV_OUTLINE_MENUS
8253 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8254 unsafe { msg_send![&*o, self] }
8255 };
8256 let col = unsafe {
8257 objc2_app_kit::NSTableColumn::initWithIdentifier(
8258 objc2_app_kit::NSTableColumn::alloc(mtm),
8259 &NSString::from_str("item"),
8260 )
8261 };
8262 unsafe {
8263 outline.addTableColumn(&col);
8264 outline.setOutlineTableColumn(Some(&col));
8265 outline.setHeaderView(None);
8266 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8279 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8284 outline.setFloatsGroupRows(true);
8287 outline.setIndentationPerLevel(0.0);
8288 outline.registerForDraggedTypes(
8291 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8292 DAY_NAV_PASTEBOARD_TYPE,
8293 )]),
8294 );
8295 outline.setDraggingSourceOperationMask_forLocal(
8296 objc2_app_kit::NSDragOperation::Move,
8297 true,
8298 );
8299 outline.setDraggingSourceOperationMask_forLocal(
8300 objc2_app_kit::NSDragOperation::None,
8301 false,
8302 );
8303 outline.setDraggingDestinationFeedbackStyle(
8304 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8305 );
8306 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8307 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8308 outline.reloadData();
8309 }
8310 let scroll = unsafe { NSScrollView::new(mtm) };
8311 unsafe {
8312 scroll.setDrawsBackground(false);
8313 scroll.setHasVerticalScroller(true);
8314 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8318 scroll.setHasHorizontalScroller(false);
8320 outline.setAutoresizingMask(
8321 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8322 );
8323 outline.setColumnAutoresizingStyle(
8324 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8325 );
8326 scroll.setDocumentView(Some(&outline));
8327 }
8328 let view = view_of(scroll);
8329 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8332 data.ivars().suppress.set(true);
8333 unsafe {
8334 outline.selectRowIndexes_byExtendingSelection(
8335 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8336 false,
8337 )
8338 };
8339 data.ivars().suppress.set(false);
8340 }
8341 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8342 view
8343 }
8344 Some(Builtin::List) => {
8345 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8346 return placeholder_view(mtm, kind);
8347 };
8348 let table: Retained<DayListView> =
8350 unsafe { msg_send![DayListView::alloc(mtm), init] };
8351 let table = Retained::into_super(table);
8352 let col = unsafe {
8353 NSTableColumn::initWithIdentifier(
8354 NSTableColumn::alloc(mtm),
8355 &NSString::from_str("day.list.col"),
8356 )
8357 };
8358 let data = DayListData::new(
8359 mtm,
8360 id,
8361 p.selectable,
8362 p.multi_select,
8363 p.row_height == RowHeight::Automatic,
8364 p.sections,
8365 );
8366 unsafe {
8367 if p.multi_select {
8368 table.setAllowsMultipleSelection(true);
8369 }
8370 table.addTableColumn(&col);
8371 table.setHeaderView(None);
8372 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8381 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8385 if p.separators == Some(true) {
8389 table.setGridStyleMask(
8390 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8391 );
8392 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8393 }
8394 table.setColumnAutoresizingStyle(
8395 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8396 );
8397 table.setFloatsGroupRows(p.sections);
8400 match p.row_height {
8401 RowHeight::Uniform(h) => table.setRowHeight(h),
8402 RowHeight::Automatic => table.setRowHeight(44.0),
8403 }
8404 if !p.selectable {
8405 table.setSelectionHighlightStyle(
8406 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8407 );
8408 }
8409 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8413 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8414 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8415 table.setTarget(Some(&*data));
8416 if p.activatable {
8417 table.setDoubleAction(Some(sel!(doubleClickRow:)));
8418 }
8419 if p.reorderable {
8420 table.registerForDraggedTypes(
8424 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8425 DAY_ROW_PASTEBOARD_TYPE,
8426 )]),
8427 );
8428 table.setDraggingSourceOperationMask_forLocal(
8429 objc2_app_kit::NSDragOperation::Move,
8430 true,
8431 );
8432 table.setDraggingSourceOperationMask_forLocal(
8433 objc2_app_kit::NSDragOperation::None,
8434 false,
8435 );
8436 table.setDraggingDestinationFeedbackStyle(
8437 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8438 );
8439 }
8440 }
8441 let scroll = unsafe { NSScrollView::new(mtm) };
8442 unsafe {
8443 scroll.setDrawsBackground(false);
8444 scroll.setHasVerticalScroller(true);
8445 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8449 scroll.setDocumentView(Some(&table));
8450 let clip = scroll.contentView();
8451 clip.setPostsBoundsChangedNotifications(true);
8452 objc2_foundation::NSNotificationCenter::defaultCenter()
8453 .addObserver_selector_name_object(
8454 &data,
8455 sel!(listViewportChanged:),
8456 Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8457 Some(&clip),
8458 );
8459 }
8460 let view = view_of(scroll);
8461 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8462 view
8463 }
8464 Some(Builtin::Tree) => {
8465 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8466 return placeholder_view(mtm, kind);
8467 };
8468 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8470 let o: Retained<DayOutlineView> =
8471 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8472 unsafe { msg_send![&*o, self] }
8473 };
8474 let col = unsafe {
8475 NSTableColumn::initWithIdentifier(
8476 NSTableColumn::alloc(mtm),
8477 &NSString::from_str("day.tree.col"),
8478 )
8479 };
8480 let data = DayTreeData::new(mtm, id, p.selectable);
8481 unsafe {
8482 if p.multi_select {
8483 outline.setAllowsMultipleSelection(true);
8484 }
8485 outline.addTableColumn(&col);
8486 outline.setOutlineTableColumn(Some(&col));
8487 outline.setHeaderView(None);
8488 if p.section_headers {
8489 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8492 outline.setFloatsGroupRows(true);
8493 } else {
8494 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8497 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8498 }
8499 outline.setColumnAutoresizingStyle(
8500 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8501 );
8502 outline.setAutoresizesOutlineColumn(true);
8503 if let Some(indent) = p.indent {
8504 outline.setIndentationPerLevel(indent);
8505 }
8506 match p.row_height {
8507 RowHeight::Uniform(h) => outline.setRowHeight(h),
8508 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8509 RowHeight::Automatic => {}
8510 }
8511 if !p.selectable {
8512 outline.setSelectionHighlightStyle(
8513 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8514 );
8515 }
8516 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8517 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8518 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8519 if p.movable {
8520 outline.registerForDraggedTypes(
8525 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8526 DAY_TREE_PASTEBOARD_TYPE,
8527 )]),
8528 );
8529 outline.setDraggingSourceOperationMask_forLocal(
8530 objc2_app_kit::NSDragOperation::Move,
8531 true,
8532 );
8533 outline.setDraggingSourceOperationMask_forLocal(
8534 objc2_app_kit::NSDragOperation::None,
8535 false,
8536 );
8537 }
8538 }
8539 let scroll = unsafe { NSScrollView::new(mtm) };
8540 unsafe {
8541 scroll.setDrawsBackground(false);
8542 scroll.setHasVerticalScroller(true);
8543 scroll.setHasHorizontalScroller(false);
8544 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8545 outline.setAutoresizingMask(
8546 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8547 );
8548 scroll.setDocumentView(Some(&outline));
8549 }
8550 let view = view_of(scroll);
8551 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8552 view
8553 }
8554 Some(Builtin::Image) => {
8555 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8556 return placeholder_view(mtm, kind);
8557 };
8558 let iv: Retained<objc2_app_kit::NSImageView> =
8559 if p.content_mode == ContentMode::Fill {
8560 let view: Retained<FillImageView> =
8561 unsafe { msg_send![FillImageView::alloc(mtm), init] };
8562 Retained::from(
8563 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8564 )
8565 } else {
8566 unsafe { objc2_app_kit::NSImageView::new(mtm) }
8567 };
8568 let scaling = match p.content_mode {
8571 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8572 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8573 };
8574 unsafe { iv.setImageScaling(scaling) };
8575 if let Some(img) = appkit_image_for(&p.source) {
8576 if p.tint.is_some() || p.template {
8581 unsafe { img.setTemplate(true) };
8582 }
8583 unsafe { iv.setImage(Some(&img)) };
8584 }
8585 if let Some(t) = p.tint {
8586 unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8587 }
8588 IMAGE_MODES.with(|t| {
8589 t.insert(
8590 ptr_of(&iv),
8591 ImageMode {
8592 template: p.template,
8593 tinted: p.tint.is_some(),
8594 },
8595 )
8596 });
8597 view_of(iv)
8598 }
8599 Some(Builtin::ListItem) => {
8600 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8601 else {
8602 return placeholder_view(mtm, kind);
8603 };
8604 make_list_item(p, mtm)
8605 }
8606 Some(Builtin::ListCell) | None => {
8609 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8610 return make(self, props, id);
8611 }
8612 warn_missing_renderer(kind);
8616 placeholder_view(mtm, kind)
8617 }
8618 }
8619 }
8620
8621 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8622 match kind {
8623 kinds::LIST_ITEM => {
8624 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8625 return;
8626 };
8627 let props = LIST_ITEMS.with(|m| {
8628 let mut m = m.borrow_mut();
8629 let props = m.get_mut(&ptr_of(h))?;
8630 use day_spec::props::ListItemPatch as P;
8631 match p {
8632 P::Title(t) => props.title = t.clone(),
8633 P::Subtitle(t) => props.subtitle = t.clone(),
8634 P::Detail(t) => props.detail = t.clone(),
8635 P::Icon(i) => props.icon = i.clone(),
8636 P::IconTint(c) => props.icon_tint = *c,
8637 P::Checked(on) => props.checked = *on,
8638 }
8639 Some(props.clone())
8640 });
8641 if let Some(props) = props {
8642 dress_list_item(h, &props, self.mtm());
8643 }
8644 }
8645 kinds::IMAGE => {
8646 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8647 match p {
8648 day_spec::props::ImagePatch::Tint(c) => {
8649 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8653 let key = ptr_of(&iv);
8654 let template = IMAGE_MODES
8655 .with(|t| {
8656 t.with(key, |m| {
8657 m.tinted = c.is_some();
8658 m.renders_template()
8659 })
8660 })
8661 .unwrap_or(c.is_some());
8662 if let Some(img) = unsafe { iv.image() } {
8663 unsafe { img.setTemplate(template) };
8664 }
8665 unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8666 }
8667 }
8668 day_spec::props::ImagePatch::Source(source) => {
8672 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8673 if let Some(img) = appkit_image_for(source) {
8679 let template = IMAGE_MODES
8680 .with(|t| t.get(ptr_of(&iv)))
8681 .is_some_and(|m| m.renders_template());
8682 unsafe {
8683 img.setTemplate(template);
8684 iv.setImage(Some(&img));
8685 }
8686 }
8687 }
8688 }
8689 }
8690 }
8691 }
8692 kinds::CONTAINER => {
8693 if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8694 patch.downcast_ref::<ContainerPatch>(),
8695 h.clone().downcast::<DayFlipped>(),
8696 ) {
8697 v.set_surface(*c, 0.0, false);
8705 }
8706 }
8707 kinds::LABEL => {
8708 if let (Some(p), Ok(tf)) = (
8709 patch.downcast_ref::<LabelPatch>(),
8710 h.clone().downcast::<NSTextField>(),
8711 ) {
8712 match p {
8713 LabelPatch::Text(t) => {
8714 unsafe { tf.setStringValue(&NSString::from_str(t)) };
8715 if let Some(label) = h.downcast_ref::<DayLabel>() {
8716 label.ivars().has_runs.set(false);
8717 label.set_links(false);
8718 }
8719 }
8720 LabelPatch::Color(c) => unsafe {
8721 tf.setTextColor(c.map(nscolor).as_deref())
8722 },
8723 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
8724 LabelPatch::Runs(text, runs) => {
8725 let base = unsafe { tf.font() };
8729 let s = match base.as_deref() {
8730 Some(f) => {
8731 attributed_label(text, f, None, Default::default(), runs)
8732 }
8733 None => attributed_label(
8734 text,
8735 &nsfont(day_spec::FontSpec::default()),
8736 None,
8737 Default::default(),
8738 runs,
8739 ),
8740 };
8741 unsafe { tf.setAttributedStringValue(&s) };
8742 set_paragraph_alignment(&tf, unsafe { tf.alignment() });
8745 if let Some(label) = h.downcast_ref::<DayLabel>() {
8746 label.ivars().has_runs.set(!runs.is_empty());
8747 label.set_links(runs.iter().any(|r| r.link.is_some()));
8748 }
8749 }
8750 }
8751 }
8752 }
8753 kinds::BUTTON => {
8754 if let (Some(p), Ok(btn)) = (
8755 patch.downcast_ref::<ButtonPatch>(),
8756 h.clone().downcast::<NSButton>(),
8757 ) {
8758 match p {
8759 ButtonPatch::Content(c) => {
8760 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
8761 }
8762 ButtonPatch::Title(t) => {
8763 let style = BUTTON_STYLES
8764 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
8765 .unwrap_or_default();
8766 set_button_title(&btn, t, style);
8767 }
8768 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
8769 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
8770 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
8771 }
8772 }
8773 }
8774 kinds::TOGGLE => {
8775 if let (Some(p), Ok(sw)) = (
8776 patch.downcast_ref::<TogglePatch>(),
8777 h.clone().downcast::<NSSwitch>(),
8778 ) {
8779 match p {
8780 TogglePatch::On(on) => {
8781 let want = if *on { 1 } else { 0 };
8782 if unsafe { sw.state() } != want {
8783 unsafe { sw.setState(want) };
8784 }
8785 }
8786 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
8787 }
8788 }
8789 }
8790 kinds::SLIDER => {
8791 if let (Some(p), Ok(sl)) = (
8792 patch.downcast_ref::<SliderPatch>(),
8793 h.clone().downcast::<NSSlider>(),
8794 ) {
8795 match p {
8796 SliderPatch::Value(v) => {
8797 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
8798 unsafe { sl.setDoubleValue(*v) };
8799 }
8800 }
8801 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
8802 }
8803 }
8804 }
8805 kinds::PROGRESS => {
8806 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
8807 {
8808 crate::controls::spinner::update(self, h, p);
8809 return;
8810 }
8811
8812 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
8813 patch.downcast_ref::<ProgressPatch>(),
8814 h.clone().downcast::<NSProgressIndicator>(),
8815 ) {
8816 unsafe {
8817 match v {
8818 Some(val) => {
8819 if pi.isIndeterminate() {
8820 pi.stopAnimation(None);
8821 pi.setIndeterminate(false);
8822 pi.setStyle(NSProgressIndicatorStyle::Bar);
8823 pi.setMinValue(0.0);
8824 pi.setMaxValue(1.0);
8825 }
8826 if (pi.doubleValue() - val).abs() > 0.0001 {
8827 pi.setDoubleValue(*val);
8828 }
8829 }
8830 None => {
8831 pi.setIndeterminate(true);
8832 pi.setStyle(NSProgressIndicatorStyle::Spinning);
8833 pi.startAnimation(None);
8834 }
8835 }
8836 }
8837 }
8838 }
8839 kinds::NAV_MENU => {
8840 if let Some(NavMenuPatch::Items {
8841 items,
8842 icons,
8843 badges,
8844 badge_icons,
8845 badge_tints,
8846 sections,
8847 tints,
8848 menus,
8849 movable,
8850 sorted,
8851 selected,
8852 rows_changed,
8853 ..
8854 }) = patch.downcast_ref::<NavMenuPatch>()
8855 {
8856 NAV_MENUS.with(|m| {
8857 let m = m.borrow();
8858 let Some((outline, data)) = m.get(&ptr_of(h)) else {
8859 return;
8860 };
8861 *data.ivars().movable.borrow_mut() = movable.clone();
8862 *data.ivars().sorted.borrow_mut() = sorted.clone();
8863 data.set_items(
8864 items,
8865 icons,
8866 badges,
8867 badge_icons,
8868 badge_tints,
8869 sections,
8870 tints,
8871 menus,
8872 );
8873 data.ivars().suppress.set(true);
8874 if let Some(rows) = rows_changed {
8877 let set = objc2_foundation::NSMutableIndexSet::new();
8878 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
8879 unsafe { set.addIndex(row) };
8880 }
8881 unsafe {
8882 outline.reloadDataForRowIndexes_columnIndexes(
8883 &set,
8884 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
8885 )
8886 };
8887 data.ivars().suppress.set(false);
8888 return;
8889 }
8890 unsafe {
8891 outline.reloadData();
8892 match selected.and_then(|i| data.row_of_item(i)) {
8893 Some(row) => outline.selectRowIndexes_byExtendingSelection(
8894 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8895 false,
8896 ),
8897 None => outline.deselectAll(None),
8898 }
8899 }
8900 data.ivars().suppress.set(false);
8901 });
8902 adopt_menu_for_tabs(self.mtm(), h);
8904 } else if let Some(NavMenuPatch::IconProgress(progress)) =
8905 patch.downcast_ref::<NavMenuPatch>()
8906 {
8907 NAV_MENUS.with(|menus| {
8908 let menus = menus.borrow();
8909 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
8910 return;
8911 };
8912 let previous = data.ivars().icon_progress.replace(progress.clone());
8913 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
8914 let Some(index) = item else {
8915 continue;
8916 };
8917 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
8918 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
8919 continue;
8920 }
8921 if let Some(view) = unsafe {
8922 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
8923 } && let Some(cell) =
8924 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
8925 && let Some(icon) = unsafe { cell.imageView() }
8926 {
8927 nav_progress::update(&icon, value);
8928 }
8929 }
8930 });
8931 } else if let Some(NavMenuPatch::Selected(sel)) =
8932 patch.downcast_ref::<NavMenuPatch>()
8933 {
8934 NAV_MENUS.with(|m| {
8935 let m = m.borrow();
8936 let Some((outline, data)) = m.get(&ptr_of(h)) else {
8937 return;
8938 };
8939 data.ivars().suppress.set(true);
8940 unsafe {
8941 match sel.and_then(|i| data.row_of_item(i)) {
8942 Some(row) => outline.selectRowIndexes_byExtendingSelection(
8943 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8944 false,
8945 ),
8946 None => outline.deselectAll(None),
8947 }
8948 }
8949 data.ivars().suppress.set(false);
8950 });
8951 }
8952 }
8953 kinds::INSPECTOR => {
8954 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
8955 INSPECTOR_STATE.with(|m| {
8956 if let Some(state) = m.borrow().get(&ptr_of(h)) {
8957 state.panel_item.setCollapsed(!*v);
8960 }
8961 });
8962 }
8963 }
8964 kinds::SPLIT => {
8965 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
8966 SPLIT_STATE.with(|m| {
8967 let m = m.borrow();
8968 let Some(state) = m.get(&ptr_of(h)) else {
8969 return;
8970 };
8971 let iv = state.delegate.ivars();
8972 match p {
8973 SplitPatch::Fraction(f) => {
8974 iv.share.set(f.clamp(0.0, 1.0));
8975 if iv.positioned.get() {
8976 split_place(&state.split, iv);
8977 }
8978 }
8979 SplitPatch::Axis(axis) => unsafe {
8980 state
8981 .split
8982 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
8983 state.split.adjustSubviews();
8984 if iv.positioned.get() {
8985 split_place(&state.split, iv);
8986 }
8987 },
8988 }
8989 });
8990 }
8991 }
8992 kinds::NAV => {
8993 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
8994 nav_present(self.mtm(), h, *next);
8995 return;
8996 }
8997 if let Some(p) = patch.downcast_ref::<NavPatch>() {
8998 NAV_STATE.with(|m| {
8999 let mut m = m.borrow_mut();
9000 let Some(state) = m.get_mut(&ptr_of(h)) else {
9001 return;
9002 };
9003 match p {
9004 NavPatch::Pushed { title, .. } => {
9005 let last = state.pages.len().saturating_sub(1);
9007 state.selected = last;
9008 for (i, page) in state.pages.iter().enumerate() {
9009 page.setHidden(i != last);
9010 }
9011 if let Some(hdr) = state.header.as_mut() {
9012 hdr.titles.push(title.clone());
9013 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9014 }
9015 }
9016 NavPatch::Popped => {
9017 let n = state.pages.len();
9020 if let Some(top) = state.pages.last() {
9021 top.setHidden(true);
9022 }
9023 if n >= 2 {
9024 state.pages[n - 2].setHidden(false);
9025 }
9026 state.selected = n.saturating_sub(2);
9027 if let Some(hdr) = state.header.as_mut() {
9028 if hdr.titles.len() > 1 {
9029 hdr.titles.pop();
9030 }
9031 let after: Vec<Retained<NSView>> = state
9034 .pages
9035 .iter()
9036 .take(n.saturating_sub(1))
9037 .cloned()
9038 .collect();
9039 sync_nav_header(hdr, &state.detail_wrap, &after);
9040 }
9041 }
9042 NavPatch::Title(t) => {
9043 if let Some(hdr) = state.header.as_mut() {
9044 if let Some(last) = hdr.titles.last_mut() {
9045 *last = t.clone();
9046 }
9047 unsafe {
9048 hdr.title.setStringValue(&NSString::from_str(t));
9049 }
9050 }
9051 }
9052 NavPatch::GuardTop(_) => {}
9056 NavPatch::Reorder(order) => {
9057 let old = state.pages.clone();
9058 state.pages =
9059 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9060 if let Some(tabs) = &state.tabs {
9061 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9062 unsafe {
9063 let items = tabs.view.tabViewItems();
9064 for item in items.iter() {
9065 tabs.view.removeTabViewItem(&item);
9066 }
9067 for i in order {
9068 if let Some(item) = items.iter().nth(*i) {
9069 tabs.view.addTabViewItem(&item);
9070 }
9071 }
9072 }
9073 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9074 }
9075 }
9076 NavPatch::Presentation(_) => {}
9078 NavPatch::Select(i) => {
9082 state.selected = *i;
9083 match state.tabs.as_ref() {
9084 Some(tabs) => {
9086 let n = unsafe { tabs.view.numberOfTabViewItems() };
9087 if (*i as isize) < n {
9088 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9089 unsafe {
9090 tabs.view.selectTabViewItemAtIndex(*i as isize)
9091 };
9092 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9093 }
9094 }
9095 None => {
9096 for (n, page) in state.pages.iter().enumerate() {
9097 page.setHidden(n != *i);
9098 }
9099 }
9100 }
9101 }
9102 NavPatch::ListVisible(v) => {
9108 state.list_visible = *v;
9109 if let Some(item) = state.list_item.as_ref() {
9110 item.setCollapsed(!*v);
9111 let split = unsafe { state._split_vc.splitView() };
9112 unsafe { split.layoutSubtreeIfNeeded() };
9113 if let Some(w) = take_list_placement(state) {
9118 unsafe {
9119 split.setPosition_ofDividerAtIndex(
9120 day_spec::NAV_SIDEBAR_WIDTH + w,
9121 1,
9122 );
9123 }
9124 }
9125 if *v
9132 && let Some(wrap) = state.list_wrap.as_ref()
9133 && let Some(page) = state.list_page.as_ref()
9134 {
9135 unsafe {
9136 wrap.layoutSubtreeIfNeeded();
9137 page.setFrame(wrap.bounds());
9138 }
9139 }
9140 }
9141 }
9142 NavPatch::ListInStack(_) => {}
9146 }
9147 });
9148 }
9149 }
9150 kinds::COVER => {
9156 if let (Some(p), Ok(page)) = (
9157 patch.downcast_ref::<CoverPatch>(),
9158 h.clone().downcast::<DayNavPage>(),
9159 ) {
9160 let node = page.ivars().node;
9161 match p {
9162 CoverPatch::Present { background, .. } => {
9163 if page.ivars().sheet.get() {
9164 if let Some(parent) =
9165 primary_content().and_then(|v| unsafe { v.window() })
9166 {
9167 let bounds = parent.frame().size;
9168 let height = if page.ivars().half.get() {
9169 (bounds.height * 0.5).clamp(160.0, 620.0)
9170 } else {
9171 (bounds.height - 80.0).clamp(300.0, 620.0)
9172 };
9173 let size = NSSize::new(
9174 (bounds.width - 40.0).clamp(320.0, 640.0),
9175 height,
9176 );
9177 let window = unsafe {
9178 NSWindow::initWithContentRect_styleMask_backing_defer(
9179 NSWindow::alloc(MainThreadMarker::new().unwrap()),
9180 NSRect::new(NSPoint::new(0.0, 0.0), size),
9181 NSWindowStyleMask::Titled,
9182 NSBackingStoreType::Buffered,
9183 false,
9184 )
9185 };
9186 unsafe {
9187 window.setReleasedWhenClosed(false);
9188 page.removeFromSuperview();
9189 page.setHidden(false);
9190 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9191 window.setContentView(Some(&page));
9192 }
9193 let key = ptr_of(h);
9194 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9195 dispatch2::DispatchQueue::main().exec_async(move || {
9196 ffi_guard::contain((), || {
9197 let window =
9198 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9199 if let (Some(window), Some(parent)) = (
9200 window,
9201 primary_content()
9202 .and_then(|v| unsafe { v.window() }),
9203 ) {
9204 unsafe {
9205 parent.beginSheet_completionHandler(
9206 &window, None,
9207 );
9208 }
9209 }
9210 });
9211 });
9212 emit(
9213 node,
9214 Event::FrameChanged(Size::new(size.width, size.height)),
9215 );
9216 }
9217 return;
9218 }
9219 unsafe {
9223 page.setWantsLayer(true);
9224 if let Some(layer) = page.layer() {
9225 let color = match background {
9226 Some(bg) => nscolor(*bg),
9227 None => NSColor::windowBackgroundColor(),
9228 };
9229 layer.setBackgroundColor(Some(&color.CGColor()));
9230 }
9231 }
9232 if let Some(content) = primary_content() {
9235 if let Some(window) = unsafe { content.window() } {
9236 toolbar::cover_presented(ptr_of(h), &window);
9237 }
9238 let top = title_bar_inset(&content);
9243 let full = content.frame().size;
9244 page.ivars().top_inset.set(top);
9245 unsafe {
9246 page.removeFromSuperview();
9247 content.addSubview(&page);
9248 page.setFrame(NSRect::new(
9249 NSPoint::new(0.0, -top),
9250 NSSize::new(full.width, full.height),
9251 ));
9252 page.setBoundsOrigin(NSPoint::new(0.0, -top));
9253 page.setAutoresizingMask(
9254 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9255 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9256 );
9257 page.setHidden(false);
9258 }
9259 emit(
9260 node,
9261 Event::FrameChanged(Size::new(
9262 full.width,
9263 (full.height - top).max(0.0),
9264 )),
9265 );
9266 }
9267 }
9268 CoverPatch::DismissDisabled(_) => {}
9269 CoverPatch::Dismiss => {
9270 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9271 toolbar::cover_dismissed(ptr_of(h));
9272 unsafe {
9273 page.setHidden(true);
9274 page.removeFromSuperview();
9275 }
9276 emit(node, Event::CoverHidden);
9277 }
9278 }
9279 }
9280 }
9281 kinds::PICKER => picker::update_any(self, h, patch),
9282 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9283 kinds::TEXT_FIELD => {
9284 if let (Some(p), Ok(tf)) = (
9285 patch.downcast_ref::<TextFieldPatch>(),
9286 h.clone().downcast::<NSTextField>(),
9287 ) {
9288 match p {
9289 TextFieldPatch::Text { text, from_native } => {
9290 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9292 unsafe { tf.setStringValue(&NSString::from_str(text)) };
9293 }
9294 }
9295 TextFieldPatch::Placeholder(t) => unsafe {
9296 tf.setPlaceholderString(Some(&NSString::from_str(t)))
9297 },
9298 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9299 }
9300 }
9301 }
9302 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9303 Some(ListPatch::Splice(deltas)) => {
9304 if let Some((table, data)) = list_entry(ptr_of(h)) {
9310 use objc2_app_kit::NSTableViewAnimationOptions;
9311 for d in deltas {
9312 unsafe {
9313 table.beginUpdates();
9314 match d {
9315 day_spec::props::RowDelta::Insert(i) => table
9316 .insertRowsAtIndexes_withAnimation(
9317 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9318 NSTableViewAnimationOptions::SlideDown,
9319 ),
9320 day_spec::props::RowDelta::Remove(i) => table
9321 .removeRowsAtIndexes_withAnimation(
9322 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9323 NSTableViewAnimationOptions::SlideUp,
9324 ),
9325 day_spec::props::RowDelta::Move(from, to) => {
9326 table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9327 }
9328 }
9329 table.endUpdates();
9330 }
9331 }
9332 if let Some(source) = data.ivars().source.borrow().as_ref() {
9336 let n = (source.len)();
9337 *data.ivars().tokens.borrow_mut() =
9338 (0..n).map(|i| (source.token_at)(i)).collect();
9339 }
9340 }
9341 post_realize_visible_rows(ptr_of(h));
9342 }
9343 Some(ListPatch::Reload) => {
9344 if let Some((table, data)) = list_entry(ptr_of(h)) {
9345 let selected = unsafe { table.selectedRowIndexes() };
9349 let tokens: Vec<u64> = data
9350 .ivars()
9351 .tokens
9352 .borrow()
9353 .iter()
9354 .enumerate()
9355 .filter(|(row, _)| selected.containsIndex(*row))
9356 .map(|(_, token)| *token)
9357 .collect();
9358 data.ivars().suppress.set(true);
9359 if let Some(moves) = data.permutation_moves(&table) {
9366 unsafe {
9367 table.beginUpdates();
9368 for (from, to) in moves {
9369 table.moveRowAtIndex_toIndex(from as isize, to as isize);
9370 }
9371 table.endUpdates();
9372 }
9373 } else {
9374 unsafe { table.reloadData() };
9375 }
9376 let restored = objc2_foundation::NSMutableIndexSet::new();
9377 for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9378 if tokens.contains(token) {
9379 restored.addIndex(row);
9380 }
9381 }
9382 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9383 data.ivars().suppress.set(false);
9384 }
9385 post_realize_visible_rows(ptr_of(h));
9391 }
9392 Some(ListPatch::ScrollToRow(row)) => {
9393 let (key, row) = (ptr_of(h), *row);
9396 <AppKit as Platform>::post(Box::new(move || {
9397 if let Some((table, _)) = list_entry(key) {
9398 let rows = unsafe { table.numberOfRows() };
9399 if rows > 0 {
9400 unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9401 }
9402 }
9403 }));
9404 post_realize_visible_rows(ptr_of(h));
9405 }
9406 Some(ListPatch::ScrollToEnd) => {
9407 let key = ptr_of(h);
9412 <AppKit as Platform>::post(Box::new(move || {
9413 if let Some((table, _)) = list_entry(key) {
9414 let rows = unsafe { table.numberOfRows() };
9415 if rows > 0 {
9416 unsafe { table.scrollRowToVisible(rows - 1) };
9417 }
9418 }
9419 }));
9420 post_realize_visible_rows(ptr_of(h));
9422 }
9423 Some(ListPatch::Selected(rows)) => {
9424 if let Some((table, data)) = list_entry(ptr_of(h)) {
9427 data.ivars().suppress.set(true);
9428 unsafe {
9429 if rows.is_empty() {
9430 table.deselectAll(None);
9431 } else {
9432 let set = objc2_foundation::NSMutableIndexSet::new();
9433 let count = table.numberOfRows().max(0) as usize;
9434 for r in rows.iter().copied().filter(|r| *r < count) {
9435 set.addIndex(r);
9436 }
9437 table.selectRowIndexes_byExtendingSelection(&set, false);
9438 }
9439 }
9440 data.ivars().suppress.set(false);
9441 }
9442 }
9443 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9444 if let Some((table, data)) = list_entry(ptr_of(h)) {
9445 data.row_resized(&table, *cell, *height);
9446 }
9447 }
9448 Some(ListPatch::Editing(_)) | None => {}
9451 },
9452 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9453 Some(TreePatch::Reload) => {
9454 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9459 unsafe { outline.reloadData() };
9460 }
9461 post_realize_visible_tree_rows(ptr_of(h));
9462 }
9463 Some(TreePatch::Expand(token, on)) => {
9464 let (key, token, on) = (ptr_of(h), *token, *on);
9469 <AppKit as Platform>::post(Box::new(move || {
9470 if let Some((outline, data)) = tree_entry(key) {
9471 let item = data.intern(token);
9472 data.ivars().suppress.set(true);
9475 unsafe {
9476 if on {
9477 outline.expandItem(Some(&item));
9478 } else {
9479 outline.collapseItem(Some(&item));
9480 }
9481 }
9482 data.ivars().suppress.set(false);
9483 }
9484 day_core::pump_events();
9485 }));
9486 post_realize_visible_tree_rows(ptr_of(h));
9487 }
9488 Some(TreePatch::Selected(tokens)) => {
9489 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9490 data.ivars().suppress.set(true);
9491 unsafe {
9492 if tokens.is_empty() {
9493 outline.deselectAll(None);
9494 } else {
9495 let set = objc2_foundation::NSMutableIndexSet::new();
9496 for t in tokens {
9497 let row = outline.rowForItem(Some(&data.intern(*t)));
9500 if row >= 0 {
9501 set.addIndex(row as usize);
9502 }
9503 }
9504 outline.selectRowIndexes_byExtendingSelection(&set, false);
9505 }
9506 }
9507 data.ivars().suppress.set(false);
9508 }
9509 }
9510 Some(TreePatch::Reveal(token)) => {
9511 let (key, token) = (ptr_of(h), *token);
9514 <AppKit as Platform>::post(Box::new(move || {
9515 if let Some((outline, data)) = tree_entry(key) {
9516 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9517 if row >= 0 {
9518 unsafe { outline.scrollRowToVisible(row) };
9519 }
9520 }
9521 }));
9522 post_realize_visible_tree_rows(ptr_of(h));
9523 }
9524 None => {}
9525 },
9526 _ => {
9527 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9528 update(self, h, patch);
9529 }
9530 }
9531 }
9532 }
9533
9534 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9536 let f = self.registry.get(kind).and_then(|r| r.release);
9539 if let Some(f) = f {
9540 f(self, h);
9541 }
9542 }
9543 fn release(&mut self, h: Handle) {
9544 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9545 self.secondary.retain(|w| {
9549 if ptr_of(&w.content) == ptr_of(&h) {
9550 w.window.close();
9551 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9555 false
9556 } else {
9557 true
9558 }
9559 });
9560 TARGETS.with(|m| {
9561 m.borrow_mut().remove(&ptr_of(&h));
9562 });
9563 LIST_STATE.with(|m| {
9564 m.borrow_mut().remove(&ptr_of(&h));
9565 });
9566 TREE_STATE.with(|m| {
9567 m.borrow_mut().remove(&ptr_of(&h));
9568 });
9569 GESTURES.with(|m| {
9570 m.borrow_mut().remove(&ptr_of(&h));
9571 });
9572 NAV_STATE.with(|m| {
9573 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9574 unsafe {
9582 nav._split_vc.setNextResponder(None);
9583 let split = nav._split_vc.splitView();
9584 if split.nextResponder().is_some_and(|r| {
9585 core::ptr::eq::<objc2::runtime::AnyObject>(
9586 r.as_ref(),
9587 nav._split_vc.as_ref(),
9588 )
9589 }) {
9590 split.setNextResponder(None);
9591 }
9592 }
9593 }
9594 });
9595 NAV_PAGES.with(|set| {
9596 set.borrow_mut().remove(&ptr_of(&h));
9597 });
9598 SPLIT_STATE.with(|m| {
9599 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9600 state.split.setDelegate(None);
9601 }
9602 });
9603 INSPECTOR_STATE.with(|m| {
9604 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9605 unsafe {
9608 insp._split_vc.setNextResponder(None);
9609 let split = insp._split_vc.splitView();
9610 if split.nextResponder().is_some_and(|r| {
9611 core::ptr::eq::<objc2::runtime::AnyObject>(
9612 r.as_ref(),
9613 insp._split_vc.as_ref(),
9614 )
9615 }) {
9616 split.setNextResponder(None);
9617 }
9618 }
9619 }
9620 });
9621 NAV_MENUS.with(|m| {
9622 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9623 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9628 }
9629 });
9630 day_spec::sidetable::sweep(ptr_of(&h));
9636 unsafe { h.removeFromSuperview() };
9637 }
9638
9639 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9640 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9644 unsafe { content_of(parent).addSubview(child) };
9645 adopt_menu_for_tabs(self.mtm(), child);
9646 return;
9647 }
9648 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9651 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9652 let handled = NAV_STATE.with(|m| {
9653 let mut m = m.borrow_mut();
9654 let Some(state) = m.get_mut(&ptr_of(parent)) else {
9655 return false;
9656 };
9657 if page_pane == Some(day_spec::props::Pane::List)
9660 && let Some(wrap) = state.list_wrap.as_ref()
9661 {
9662 state.list_page = Some(child.clone());
9663 unsafe {
9664 child.setFrame(wrap.bounds());
9665 child.setAutoresizingMask(
9666 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9667 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9668 );
9669 wrap.addSubview(child);
9670 }
9671 return true;
9672 }
9673 if is_sidebar_page {
9674 state.sidebar_page = Some(child.clone());
9675 }
9676 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9682 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9687 state.pages.push(child.clone());
9688 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9689 unsafe {
9690 child.setAutoresizingMask(
9691 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9692 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9693 );
9694 item.setView(Some(child));
9695 tabs.view.addTabViewItem(&item);
9696 }
9697 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
9698 sync_tab_labels(tabs, &titles, state.selected);
9699 }
9700 return true;
9701 }
9702 let (wrap, frame) = if to_pane {
9703 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
9704 } else {
9705 state.pages.push(child.clone());
9706 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
9707 (
9708 &state.detail_wrap,
9709 nav_page_frame(&state.detail_wrap, visible),
9710 )
9711 };
9712 unsafe {
9713 child.setFrame(frame);
9714 child.setAutoresizingMask(
9715 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9716 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9717 );
9718 wrap.addSubview(child);
9719 }
9720 true
9721 });
9722 if handled {
9723 return;
9724 }
9725 let split_pane = SPLIT_STATE.with(|m| {
9728 let m = m.borrow();
9729 let Some(state) = m.get(&ptr_of(parent)) else {
9730 return false;
9731 };
9732 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
9733 let wrap = if second {
9734 &state.second_wrap
9735 } else {
9736 &state.first_wrap
9737 };
9738 unsafe {
9739 child.setFrame(wrap.bounds());
9740 child.setAutoresizingMask(
9741 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9742 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9743 );
9744 wrap.addSubview(child);
9745 }
9746 true
9747 });
9748 if split_pane {
9749 return;
9750 }
9751 let inspected = INSPECTOR_STATE.with(|m| {
9754 let m = m.borrow();
9755 let Some(state) = m.get(&ptr_of(parent)) else {
9756 return false;
9757 };
9758 let panel = INSPECTOR_PANES
9759 .with(|t| t.get(ptr_of(child)))
9760 .unwrap_or(false);
9761 let wrap = if panel {
9762 &state.panel_wrap
9763 } else {
9764 &state.content_wrap
9765 };
9766 unsafe {
9767 child.setFrame(wrap.bounds());
9768 child.setAutoresizingMask(
9769 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9770 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9771 );
9772 wrap.addSubview(child);
9773 }
9774 true
9775 });
9776 if !inspected {
9777 unsafe { content_of(parent).addSubview(child) };
9780 }
9781 }
9782
9783 fn remove(&mut self, parent: &Handle, child: &Handle) {
9784 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
9785 let mtm = self.mtm();
9786 NAV_STATE.with(|m| {
9787 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
9788 if let Some(tabs) = state.tabs.as_ref() {
9790 unsafe {
9791 let n = tabs.view.numberOfTabViewItems();
9792 for i in 0..n {
9793 let item = tabs.view.tabViewItemAtIndex(i);
9794 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
9795 tabs.view.removeTabViewItem(&item);
9796 break;
9797 }
9798 }
9799 }
9800 }
9801 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
9802 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
9803 state.sidebar_page = None;
9804 }
9805 }
9806 });
9807 unsafe { child.removeFromSuperview() };
9808 }
9809
9810 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
9811 unsafe { content_of(parent).addSubview(child) };
9812 }
9813
9814 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
9815 match kind {
9816 kinds::LABEL => {
9817 if let Some(tf) = h.downcast_ref::<NSTextField>() {
9818 let w = p.width.unwrap_or(1.0e6);
9819 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
9821 let mut height = s.height.ceil();
9822 if tf.maximumNumberOfLines() == 1 {
9825 thread_local! {
9826 static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
9827 }
9828 if let Some(font) = unsafe { tf.font() } {
9829 height = height.min(
9830 METRICS
9831 .with(|metrics| metrics.defaultLineHeightForFont(&font))
9832 .ceil(),
9833 );
9834 }
9835 }
9836 return Size::new(s.width.ceil().min(w), height);
9837 }
9838 Size::ZERO
9839 }
9840 kinds::BUTTON | kinds::TOGGLE => {
9841 let s = unsafe { h.fittingSize() };
9842 Size::new(s.width.ceil(), s.height.ceil())
9843 }
9844 kinds::SLIDER => {
9845 let s = unsafe { h.fittingSize() };
9846 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
9847 }
9848 kinds::PICKER => picker::measure_any(self, h, p),
9849 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
9850 kinds::TEXT_FIELD => {
9851 let s = unsafe { h.fittingSize() };
9852 Size::new(
9853 p.width.unwrap_or(s.width.max(160.0)),
9854 s.height.max(22.0).ceil(),
9855 )
9856 }
9857 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
9858 kinds::LIST_ITEM => {
9861 let s = h.fittingSize();
9862 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
9863 }
9864 kinds::PROGRESS => {
9865 let indeterminate = h
9867 .clone()
9868 .downcast::<NSProgressIndicator>()
9869 .map(|pi| unsafe { pi.isIndeterminate() })
9870 .unwrap_or(false);
9871 if indeterminate {
9872 let large = h
9873 .downcast_ref::<NSProgressIndicator>()
9874 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
9875 let side = if large { 32.0 } else { 20.0 };
9876 Size::new(side, side)
9877 } else {
9878 Size::new(p.width.unwrap_or(180.0), 20.0)
9879 }
9880 }
9881 kinds::NAV_MENU => {
9882 let rows = NAV_MENUS.with(|m| {
9883 m.borrow()
9884 .get(&ptr_of(h))
9885 .map(|(_, d)| d.ivars().items.borrow().len())
9886 .unwrap_or(0)
9887 });
9888 Size::new(
9889 p.width.unwrap_or(220.0),
9890 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
9891 )
9892 }
9893 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
9895 _ => {
9896 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
9897 measure(self, h, p)
9898 } else {
9899 let s = unsafe { h.fittingSize() };
9900 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
9901 }
9902 }
9903 }
9904 }
9905
9906 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
9907 unsafe {
9908 h.setWantsLayer(true);
9909 }
9910 let v = h.clone();
9911 with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
9912 }
9913
9914 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
9915 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
9918 let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
9919 let v = h.clone();
9920 with_appkit_anim(anim, move || {
9921 if let Some(base) = base {
9922 apply_geometry(&v, base, t);
9923 }
9924 });
9925 }
9926
9927 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
9928 if let Some(label) = h.downcast_ref::<DayLabel>() {
9929 label.ivars().selectable.set(selectable);
9930 label.set_links(label.ivars().has_links.get());
9931 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
9932 unsafe { tf.setSelectable(selectable) };
9933 }
9934 None
9935 }
9936
9937 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
9938 let node = text_field_node(h)?;
9939 let old = h.downcast_ref::<NSTextField>()?;
9940 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
9943 .then(|| self.swap_text_field(h, old, node, traits.secure));
9944 let tf = swapped.as_deref().unwrap_or(old);
9945 unsafe {
9946 tf.setEditable(!traits.read_only);
9949 tf.setSelectable(true);
9950 }
9951 let content_type = match traits.purpose {
9955 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
9956 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
9957 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
9958 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
9959 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
9960 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
9961 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
9962 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
9963 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
9964 };
9965 unsafe {
9966 tf.setContentType(content_type);
9967 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
9970 }
9971 swapped.map(view_of)
9974 }
9975
9976 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
9977 let key = Retained::as_ptr(h) as usize;
9978 if cursor == Cursor::Default {
9979 if let Some((owner, area)) = self.cursors.remove(&key) {
9981 unsafe { h.removeTrackingArea(&area) };
9982 if owner.ivars().hiding.replace(false) {
9983 NSCursor::unhide();
9984 }
9985 }
9986 return;
9987 }
9988 let hidden = cursor == Cursor::None;
9989 let shape = if hidden { None } else { ns_cursor(&cursor) };
9990 let mtm = self.mtm;
9991 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
9992 let owner = DayCursorOwner::new(mtm);
9993 let opts = NSTrackingAreaOptions::CursorUpdate
9996 | NSTrackingAreaOptions::MouseEnteredAndExited
9997 | NSTrackingAreaOptions::ActiveInKeyWindow
9998 | NSTrackingAreaOptions::InVisibleRect;
9999 let any: &objc2::runtime::AnyObject = &owner;
10000 let area = unsafe {
10001 NSTrackingArea::initWithRect_options_owner_userInfo(
10002 NSTrackingArea::alloc(),
10003 NSRect::ZERO,
10004 opts,
10005 Some(any),
10006 None,
10007 )
10008 };
10009 unsafe { h.addTrackingArea(&area) };
10010 (owner, area)
10011 });
10012 let changed = {
10013 let iv = owner.ivars();
10014 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10015 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10016 (None, None) => true,
10017 _ => false,
10018 };
10019 *iv.cursor.borrow_mut() = shape;
10020 let was_hidden = iv.hidden.replace(hidden);
10021 !same || was_hidden != hidden
10022 };
10023 if changed && let Some(w) = h.window() {
10026 unsafe { w.invalidateCursorRectsForView(h) };
10027 }
10028 }
10029
10030 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10044 if !day_spec::kind_has_baseline(kind) {
10045 return None;
10046 }
10047 let current = unsafe { h.frame() };
10050 if (current.size.height - size.height).abs() > 0.5 {
10051 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10052 }
10053 let insets = unsafe { h.alignmentRectInsets() };
10054 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10055 let font = h
10056 .downcast_ref::<NSControl>()
10057 .and_then(|c| unsafe { c.font() });
10058 let offset = match font {
10059 Some(_) if kind == kinds::TEXT_AREA => reported,
10062 Some(f) => {
10063 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10064 let line = ascender - descender;
10065 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10066 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10067 }
10068 None => reported,
10069 };
10070 (offset > 0.0 && offset < size.height).then_some(offset)
10072 }
10073
10074 fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10075 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10077 return;
10078 }
10079 let r = NSRect::new(
10082 NSPoint::new(frame.origin.x, frame.origin.y),
10083 NSSize::new(frame.size.width, frame.size.height),
10084 );
10085 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10090 let strip = unsafe { split.superview() }
10094 .and_then(|sup| {
10095 let content = unsafe { sup.window() }?.contentView()?;
10096 let mut ancestor = Some(sup.clone());
10100 while let Some(view) = ancestor {
10101 if std::ptr::eq(&*view, &*content) {
10102 break;
10103 }
10104 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10105 return None; }
10107 ancestor = unsafe { view.superview() };
10108 }
10109 let point = unsafe {
10110 sup.convertPoint_toView(
10111 NSPoint::new(frame.origin.x, frame.origin.y),
10112 Some(&content),
10113 )
10114 };
10115 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10116 })
10117 .unwrap_or(0.0);
10118 let r = NSRect::new(
10119 NSPoint::new(r.origin.x, r.origin.y - strip),
10120 NSSize::new(r.size.width, r.size.height + strip),
10121 );
10122 let wraps = NAV_STATE.with(|m| {
10123 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10124 (s.title_strip != strip).then(|| {
10125 s.title_strip = strip;
10126 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10127 w.extend(s.list_wrap.clone());
10128 w
10129 })
10130 })
10131 });
10132 let first = NAV_STATE.with(|m| {
10133 m.borrow_mut()
10134 .get_mut(&ptr_of(h))
10135 .map(|s| {
10136 if !s.presentation.is_split() {
10137 return (false, None);
10138 }
10139 let sidebar = !std::mem::replace(&mut s.positioned, true);
10140 (sidebar, take_list_placement(s))
10145 })
10146 .unwrap_or((false, None))
10147 });
10148 unsafe {
10149 split.setFrame(r);
10150 split.layoutSubtreeIfNeeded();
10151 }
10152 for wrap in wraps.iter().flatten() {
10155 place_below_strip(wrap, strip);
10156 }
10157 unsafe {
10158 if first.0 {
10159 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10160 }
10161 if let Some(w) = first.1 {
10166 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10167 }
10168 }
10169 } else {
10170 BASE_FRAMES.with(|m| {
10171 m.insert(
10172 ptr_of(h),
10173 [
10174 frame.origin.x,
10175 frame.origin.y,
10176 frame.size.width,
10177 frame.size.height,
10178 ],
10179 )
10180 });
10181 match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10183 Some(t) => apply_geometry(
10184 h,
10185 [
10186 frame.origin.x,
10187 frame.origin.y,
10188 frame.size.width,
10189 frame.size.height,
10190 ],
10191 t,
10192 ),
10193 None => unsafe { h.setFrame(r) },
10194 }
10195 }
10196 }
10197
10198 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10199 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10200 && let Some(doc) = unsafe { sv.documentView() }
10201 {
10202 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10203 }
10204 }
10205
10206 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10208 day_spec::RowMetrics {
10209 insets: day_spec::Insets {
10210 top: 4.0,
10211 leading: 8.0,
10212 bottom: 4.0,
10213 trailing: 8.0,
10214 },
10215 min_height: 28.0,
10216 }
10217 }
10218
10219 fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10220 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10221 && let Some(doc) = unsafe { sv.documentView() }
10222 {
10223 unsafe {
10224 doc.scrollRectToVisible(NSRect::new(
10225 NSPoint::new(target.origin.x, target.origin.y),
10226 NSSize::new(target.size.width, target.size.height),
10227 ))
10228 };
10229 }
10230 }
10231
10232 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10233 let Some(window) = h.window() else { return };
10234 let list = list_entry(ptr_of(h));
10236 let responder: &NSResponder = match &list {
10237 Some((table, _)) => table,
10238 None => h,
10239 };
10240 let responder_ptr = responder as *const NSResponder as usize;
10241 if focused {
10242 window.makeFirstResponder(Some(responder));
10243 return;
10244 }
10245 let owns = window
10248 .firstResponder()
10249 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10250 || owns_first_responder(&window, h);
10251 if owns {
10252 window.makeFirstResponder(None);
10253 }
10254 }
10255
10256 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10257 if focusable {
10260 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10261 } else {
10262 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10263 }
10264 }
10265
10266 fn set_event_sink(&mut self, sink: EventSink) {
10267 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10268 }
10269
10270 fn set_edit_state(&mut self, state: &day_spec::EditState) {
10271 EDIT_STATE.with(|s| s.set(*state));
10272 }
10273
10274 fn modifiers(&mut self) -> day_spec::Modifiers {
10275 let f = NSEvent::modifierFlags_class();
10276 day_spec::Modifiers {
10277 shift: f.contains(NSEventModifierFlags::Shift),
10278 primary: f.contains(NSEventModifierFlags::Command),
10279 alt: f.contains(NSEventModifierFlags::Option),
10280 }
10281 }
10282
10283 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10284 let front = undo_front(self.mtm);
10285 *front.ivars().state.borrow_mut() = state.clone();
10286 }
10287
10288 fn attach_list(&mut self, host: &Handle, source: ListSource) {
10289 let key = ptr_of(host);
10290 if let Some((table, data)) = list_entry(key) {
10291 data.ivars().source.replace(Some(source));
10292 unsafe { table.reloadData() };
10294 }
10295 post_realize_visible_rows(key);
10300 }
10301
10302 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10303 let key = ptr_of(host);
10304 if let Some((outline, data)) = tree_entry(key) {
10305 data.ivars().source.replace(Some(source));
10306 unsafe { outline.reloadData() };
10308 }
10309 <AppKit as Platform>::post(Box::new(move || {
10312 if let Some((outline, _)) = tree_entry(key) {
10313 unsafe { outline.layoutSubtreeIfNeeded() };
10314 }
10315 }));
10316 }
10317
10318 fn adopt(&mut self, raw: RawHandle) -> Handle {
10319 let ptr = raw as *mut NSView;
10323 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10324 }
10325
10326 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10327 self.edit_toolbar(h, ops)
10328 }
10329
10330 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10331 self.patch_toolbar(h, patch);
10332 }
10333
10334 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10335 let mtm = self.mtm;
10336 if self.menu_escape_monitor.is_none() {
10337 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10338 ffi_guard::contain(event.as_ptr(), || {
10339 let event_ref = unsafe { event.as_ref() };
10340 let app = NSApplication::sharedApplication(mtm);
10341 if app.modalWindow().is_none()
10344 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10345 && unsafe { event_ref.charactersIgnoringModifiers() }
10346 .is_some_and(|s| s.to_string() == "\u{1b}")
10347 && app
10348 .mainMenu()
10349 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10350 {
10351 std::ptr::null_mut()
10352 } else {
10353 event.as_ptr()
10354 }
10355 })
10356 });
10357 self.menu_escape_monitor = unsafe {
10358 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10359 objc2_app_kit::NSEventMask::KeyDown,
10360 &block,
10361 )
10362 }
10363 .map(MenuEscapeMonitor);
10364 }
10365 let app = NSApplication::sharedApplication(mtm);
10366 let menubar = NSMenu::new(mtm);
10367 let mut items = items.to_vec();
10370 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10371 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10372 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10373 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10374 let services =
10375 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10376 let items =
10381 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10382 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10383 for item in &items {
10385 match item {
10386 day_spec::MenuItem::Submenu { label, items, role } => {
10387 let sub = build_ns_menu(mtm, label, items);
10388 let it = NSMenuItem::new(mtm);
10389 if *role == Some(day_spec::MenuBarRole::Help)
10393 || *label == day_localization::t(day_localization::key::day_help)
10394 {
10395 help_menu = Some((label.clone(), sub));
10396 continue;
10397 }
10398 it.setTitle(&NSString::from_str(label));
10399 it.setSubmenu(Some(&sub));
10400 menubar.addItem(&it);
10401 }
10402 other => {
10403 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10405 let it = NSMenuItem::new(mtm);
10406 it.setSubmenu(Some(&sub));
10407 menubar.addItem(&it);
10408 }
10409 }
10410 }
10411 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10414 install_windows_menu(mtm, &app, &menubar);
10415 }
10416 if let Some((label, help)) = help_menu {
10417 let it = NSMenuItem::new(mtm);
10418 it.setTitle(&NSString::from_str(&label));
10419 it.setSubmenu(Some(&help));
10420 menubar.addItem(&it);
10421 unsafe { app.setHelpMenu(Some(&help)) };
10424 }
10425 app.setMainMenu(Some(&menubar));
10426 unsafe { app.setServicesMenu(Some(&services)) };
10427 }
10428
10429 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10430 let Some(view) = h.downcast_ref::<NSView>() else {
10431 return;
10432 };
10433 if items.is_empty() {
10434 unsafe { view.setMenu(None) };
10435 return;
10436 }
10437 let menu = build_ns_menu(self.mtm, "", items);
10438 unsafe { view.setMenu(Some(&menu)) };
10444 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10445 for sub in v.subviews() {
10446 unsafe { sub.setMenu(Some(menu)) };
10447 apply_to_subviews(&sub, menu);
10448 }
10449 }
10450 apply_to_subviews(view, &menu);
10451 }
10452
10453 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10454 transfer::source(h, source);
10455 }
10456 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10457 transfer::target(h, target);
10458 }
10459 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10460 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10463 }
10464
10465 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10466 let key = ptr_of(h);
10467 if kind == day_spec::GestureKind::Pan {
10471 PAN_NODES.with(|t| t.insert(key, node));
10472 install_container_pan_monitor();
10473 return;
10474 }
10475 if kind == day_spec::GestureKind::Hover {
10479 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10483 HOVER_NODES.with(|t| t.insert(key, node));
10484 if first {
10485 install_tracking_area(h);
10486 }
10487 return;
10488 }
10489 let already = GESTURES.with(|m| {
10491 m.borrow()
10492 .get(&key)
10493 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10494 });
10495 if already {
10496 return;
10497 }
10498 let mtm = self.mtm;
10499 let target = DayGesture::new(mtm, node, kind);
10500 let recognizer: Retained<NSGestureRecognizer> = unsafe {
10501 match kind {
10502 day_spec::GestureKind::Drag => {
10503 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10504 NSPanGestureRecognizer::alloc(mtm),
10505 Some(&target),
10506 Some(sel!(fire:)),
10507 ))
10508 }
10509 day_spec::GestureKind::Pinch => Retained::into_super(
10510 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10511 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10512 Some(&target),
10513 Some(sel!(fire:)),
10514 ),
10515 ),
10516 _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10517 NSClickGestureRecognizer::alloc(mtm),
10518 Some(&target),
10519 Some(sel!(fire:)),
10520 )),
10521 }
10522 };
10523 unsafe { h.addGestureRecognizer(&recognizer) };
10524 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10525 }
10526
10527 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10528 unsafe {
10529 if let Some(id) = &a11y.identifier {
10530 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10531 }
10532 if let Some(label) = &a11y.label {
10533 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10534 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10535 } else {
10536 APP_LABELED.with(|t| t.remove(ptr_of(h)));
10537 }
10538 if let Some(hint) = &a11y.hint {
10539 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10540 }
10541 if let Some(value) = &a11y.value {
10542 let ns = NSString::from_str(value);
10543 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10544 }
10545 if let Some(role) = ns_role(a11y.role) {
10548 h.setAccessibilityRole(Some(role));
10549 }
10550 if a11y.role == day_spec::Role::Tab {
10551 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10552 }
10553 if let Some(on) = a11y.selected {
10554 h.setAccessibilitySelected(on);
10555 }
10556 if a11y.hidden {
10562 h.setAccessibilityElement(false);
10563 h.setAccessibilityChildren(Some(&NSArray::new()));
10564 }
10565 }
10566 }
10567
10568 fn announce(&mut self, text: &str, urgent: bool) {
10572 use objc2_app_kit::{
10573 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10574 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10575 NSAccessibilityPriorityLevel,
10576 };
10577 let app = NSApplication::sharedApplication(self.mtm());
10578 let window = primary_content().and_then(|content| content.window());
10579 let element: &objc2::runtime::AnyObject = match &window {
10580 Some(window) => window,
10581 None => &app,
10582 };
10583 let priority = if urgent {
10585 NSAccessibilityPriorityLevel::High
10586 } else {
10587 NSAccessibilityPriorityLevel::Medium
10588 };
10589 let announcement = NSString::from_str(text);
10590 let priority = NSNumber::new_isize(priority.0);
10591 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10592 unsafe {
10595 let user_info = NSDictionary::from_slices::<NSString>(
10596 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10597 &values,
10598 );
10599 NSAccessibilityPostNotificationWithUserInfo(
10600 element,
10601 NSAccessibilityAnnouncementRequestedNotification,
10602 Some(&user_info),
10603 );
10604 }
10605 }
10606
10607 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10608 unsafe {
10609 let role = h
10610 .accessibilityRole()
10611 .map(|r| day_role_from_ns(&r.to_string()))
10612 .unwrap_or(day_spec::Role::None);
10613 let picker = picker::read_native(h);
10616 day_spec::NativeSnapshot {
10617 found: true,
10618 role,
10619 label: h.accessibilityLabel().map(|s| s.to_string()),
10620 value: h
10621 .accessibilityValue()
10622 .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10623 identifier: h
10624 .accessibilityIdentifier()
10625 .map(|s| s.to_string())
10626 .filter(|s| !s.is_empty()),
10627 text: match &picker {
10628 Some((text, _)) => text.clone(),
10629 None => native_text(h),
10630 },
10631 number: native_number(h),
10632 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10633 match sw.state() {
10634 s if s == NSControlStateValueOn => Some(true),
10635 s if s == NSControlStateValueOff => Some(false),
10636 _ => None,
10638 }
10639 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10640 BUTTON_SELECTED
10643 .with(|m| m.borrow().contains_key(&ptr_of(h)))
10644 .then(|| btn.state() == NSControlStateValueOn)
10645 } else {
10646 None
10647 },
10648 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10651 (Some((_, on)), _) => *on,
10652 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10653 (None, Some(c)) => Some(c.isEnabled()),
10654 (None, None) => None,
10655 },
10656 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10658 frame: native_frame(h),
10659 }
10660 }
10661 }
10662
10663 fn request_frame(
10664 &mut self,
10665 host: &Handle,
10666 cb: day_spec::FrameCallback,
10667 ) -> day_spec::CancelFrame {
10668 frame::request(host, cb)
10669 }
10670
10671 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10672 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10673 unsafe { h.setNeedsDisplay(true) };
10674 }
10675 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10676 NAV_STATE.with(|m| {
10677 let m = m.borrow();
10678 let Some(st) = m.get(&ptr_of(host)) else {
10679 return false;
10680 };
10681 if !matches!(
10684 st.presentation,
10685 NavPresentation::Split | NavPresentation::Rail
10686 ) {
10687 return false;
10688 }
10689 let item = &st.sidebar_item;
10690 let collapsed = unsafe { item.isCollapsed() };
10696 unsafe { item.setCollapsed(!collapsed) };
10697 true
10698 })
10699 }
10700
10701 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
10702 let content = self.content.as_ref().ok_or("no window content")?;
10703 snapshot_view(content)
10704 }
10705
10706 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
10712 use objc2::AllocAnyThread as _;
10713 let data = NSData::with_bytes(bytes);
10714 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
10715 else {
10716 emit(
10717 WINDOW_NODE,
10718 Event::ImageDecoded {
10719 req,
10720 result: Err(day_spec::ImageError::Decode),
10721 },
10722 );
10723 return;
10724 };
10725 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
10726 let info = day_spec::BitmapInfo {
10727 pixels: Size::new(w, h),
10728 scale: 1.0,
10731 format: day_spec::ImageFormat::sniff(bytes),
10732 has_alpha: unsafe { rep.hasAlpha() },
10733 };
10734 let image = unsafe {
10738 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
10739 };
10740 unsafe { image.addRepresentation(&rep) };
10741 BITMAPS.with(|m| {
10742 m.borrow_mut().insert(
10743 id.0,
10744 AppKitBitmap {
10745 image,
10746 rep: Some(rep),
10747 info,
10748 },
10749 )
10750 });
10751 emit(
10752 WINDOW_NODE,
10753 Event::ImageDecoded {
10754 req,
10755 result: Ok(info),
10756 },
10757 );
10758 }
10759
10760 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
10761 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
10762 }
10763
10764 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
10771 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
10772 let mut out = day_spec::ImageProperties::default();
10773 let size = unsafe { rep.size() };
10774 if size.width > 0.0 {
10775 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
10776 if (dpi - 72.0).abs() > 0.5 {
10779 out.dpi = Some(dpi);
10780 }
10781 }
10782 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
10786 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
10787 for key in keys.iter() {
10788 let value: Option<Retained<objc2::runtime::AnyObject>> =
10789 unsafe { msg_send![&*exif, objectForKey: &*key] };
10790 let Some(value) = value else { continue };
10791 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
10792 let (k, v) = (key.to_string(), text.to_string());
10793 match k.as_str() {
10794 "Orientation" => out.orientation = v.parse().ok(),
10795 "DateTimeOriginal" => out.created = Some(v.clone()),
10796 _ => {}
10797 }
10798 out.extra.push((k, v));
10801 }
10802 }
10803 Some(out)
10804 }
10805
10806 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
10810 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
10811 vec![Png, Jpeg, Tiff, Bmp, Gif]
10812 }
10813
10814 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
10815 let result = encode_bitmap(id, spec);
10816 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
10817 }
10818
10819 fn release_image(&mut self, id: day_spec::BitmapId) {
10820 release_bitmap(id);
10821 }
10822
10823 fn render_bitmap(
10827 &mut self,
10828 req: u64,
10829 id: day_spec::BitmapId,
10830 ops: &[DrawOp],
10831 size: Size,
10832 scale: f64,
10833 ) {
10834 let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
10835 let info = bitmap.info;
10836 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
10837 info
10838 });
10839 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
10840 }
10841
10842 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
10843 let result = render_pdf_bytes(pages, info);
10844 emit(WINDOW_NODE, Event::PdfRendered { req, result });
10845 }
10846
10847 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
10851 use day_spec::FontWeight as W;
10852 let mtm =
10853 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
10854 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
10855 let mut out = Vec::new();
10856 for family in unsafe { manager.availableFontFamilies() }.iter() {
10857 let name = family.to_string();
10858 if name.starts_with('.') {
10859 continue;
10860 }
10861 let mut faces = Vec::new();
10862 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
10863 for member in members.iter() {
10864 if member.count() < 4 {
10865 continue;
10866 }
10867 let style = member
10868 .objectAtIndex(1)
10869 .downcast_ref::<NSString>()
10870 .map(|s| s.to_string())
10871 .unwrap_or_default();
10872 let weight = member
10873 .objectAtIndex(2)
10874 .downcast_ref::<objc2_foundation::NSNumber>()
10875 .map(|n| n.integerValue())
10876 .unwrap_or(5);
10877 let traits = member
10878 .objectAtIndex(3)
10879 .downcast_ref::<objc2_foundation::NSNumber>()
10880 .map(|n| n.integerValue())
10881 .unwrap_or(0);
10882 let weight = match weight {
10883 ..=2 => W::UltraLight,
10884 3 => W::Thin,
10885 4 => W::Light,
10886 5 => W::Regular,
10887 6 => W::Medium,
10888 7 | 8 => W::Semibold,
10889 9 => W::Bold,
10890 10 | 11 => W::Heavy,
10891 _ => W::Black,
10892 };
10893 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
10895 name: if style.is_empty() {
10896 day_spec::FontFace::synthesized_name(weight, italic)
10897 } else {
10898 style
10899 },
10900 weight,
10901 italic,
10902 });
10903 }
10904 }
10905 out.push(day_spec::FontFamilyInfo {
10906 family: name,
10907 faces,
10908 });
10909 }
10910 out
10911 }
10912
10913 fn measure_text(
10916 &mut self,
10917 text: &str,
10918 size: f64,
10919 font: &day_spec::CanvasFont,
10920 ) -> Option<day_spec::TextMetrics> {
10921 let nsfont = canvas_nsfont(size, font);
10922 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
10923 let ns = NSString::from_str(text);
10924 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
10925 let unbounded = NSSize::new(f64::MAX, f64::MAX);
10929 let ink: NSRect = unsafe {
10930 msg_send![
10931 &ns,
10932 boundingRectWithSize: unbounded,
10933 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
10934 attributes: &*attrs,
10935 ]
10936 };
10937 Some(day_spec::TextMetrics::from_baseline(
10938 sz.width,
10939 nsfont.ascender(),
10940 sz.height - nsfont.ascender(),
10941 nsfont.capHeight(),
10942 day_spec::Rect::new(
10943 ink.origin.x,
10944 -(ink.origin.y + ink.size.height),
10945 ink.size.width,
10946 ink.size.height,
10947 ),
10948 ))
10949 }
10950
10951 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
10952 let content = self.content.as_ref().ok_or("no window content")?;
10953 snapshot_view_chrome(content)
10954 }
10955
10956 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
10957 snapshot_view(host)
10958 }
10959
10960 fn open_window(
10961 &mut self,
10962 id: NodeId,
10963 options: &WindowOptions,
10964 kind: day_spec::WindowKind,
10965 ) -> day_spec::WindowOpenReply<Handle> {
10966 let prefs = kind.is_panel();
10967 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
10968 if prefs {
10969 window.center();
10972 unsafe { window.setExcludedFromWindowsMenu(true) };
10973 } else {
10974 let from = match self.cascade {
10982 Some(p) => p,
10983 None => self
10984 .window
10985 .as_ref()
10986 .map(|w| {
10987 let f = w.frame();
10988 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
10989 unsafe { w.cascadeTopLeftFromPoint(top_left) }
10992 })
10993 .unwrap_or(NSPoint::new(0.0, 0.0)),
10994 };
10995 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
10996 }
10997 window_chrome::place(&window, options.placement);
10998 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11003 center_on_screen_of(&window, self.window.as_deref());
11004 }
11005 let _ = pin_below_title_bar(&window);
11008 if !options.start_hidden {
11009 window.makeKeyAndOrderFront(None);
11010 }
11011 mark_tree_needs_display(&content);
11014 self.secondary.push(SecondaryWin {
11015 window,
11016 delegate,
11017 content: content.clone(),
11018 });
11019 day_spec::WindowOpenReply::Open(content)
11020 }
11021
11022 fn native_window_tabs(&self) -> bool {
11023 true
11024 }
11025 fn group_windows(&mut self, hosts: &[Handle]) {
11026 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11027 let Some(first) = windows.first() else {
11028 return;
11029 };
11030 unsafe {
11031 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11032 }
11033 for window in windows.iter().skip(1) {
11035 unsafe {
11036 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11037 }
11038 }
11039 if let Some(group) = first.tabGroup() {
11040 if !group.isTabBarVisible() {
11041 unsafe {
11042 first.toggleTabBar(None);
11043 }
11044 }
11045 for (i, window) in windows.iter().enumerate() {
11046 group.insertWindow_atIndex(window, i as isize);
11047 }
11048 }
11049 for window in &windows {
11052 if let Some(size) = pin_below_title_bar(window) {
11053 let node = window
11054 .delegate()
11055 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11056 .and_then(|d| d.ivars().node)
11057 .unwrap_or(WINDOW_NODE);
11058 emit(node, Event::WindowResized(size));
11059 }
11060 }
11061 }
11062 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11063 let Some(window) = self.ns_window_for(host) else {
11064 return Vec::new();
11065 };
11066 let windows = window.tabGroup().map(|g| g.windows());
11067 let Some(windows) = windows else {
11068 return Vec::new();
11069 };
11070 windows
11071 .iter()
11072 .filter_map(|window| {
11073 self.secondary
11074 .iter()
11075 .find(|w| std::ptr::eq(&*w.window, &*window))
11076 .and_then(|w| w.delegate.ivars().node)
11077 })
11078 .collect()
11079 }
11080
11081 fn close_window(&mut self, host: &Handle) {
11082 if let Some(w) = self
11085 .secondary
11086 .iter()
11087 .find(|w| ptr_of(&w.content) == ptr_of(host))
11088 {
11089 w.window.close();
11090 }
11091 }
11092
11093 fn focus_window(&mut self, host: &Handle) {
11094 if let Some(w) = self
11095 .secondary
11096 .iter()
11097 .find(|w| ptr_of(&w.content) == ptr_of(host))
11098 {
11099 w.window.makeKeyAndOrderFront(None);
11100 }
11101 }
11102
11103 fn fit_window(&mut self, host: &Handle, size: Size) {
11104 let Some(w) = self
11105 .secondary
11106 .iter()
11107 .find(|w| ptr_of(&w.content) == ptr_of(host))
11108 else {
11109 return;
11110 };
11111 unsafe {
11112 w.window
11116 .setContentSize(NSSize::new(size.width, size.height));
11117 let mask = w.window.styleMask();
11121 w.window
11122 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11123 w.window.center();
11124 }
11125 center_on_screen_of(&w.window, self.window.as_deref());
11126 }
11127
11128 fn set_window_title(&mut self, host: &Handle, title: &str) {
11129 if let Some(w) = self
11130 .secondary
11131 .iter()
11132 .find(|w| ptr_of(&w.content) == ptr_of(host))
11133 {
11134 w.window.setTitle(&NSString::from_str(title));
11135 return;
11136 }
11137 if self
11141 .content
11142 .as_ref()
11143 .is_some_and(|c| ptr_of(c) == ptr_of(host))
11144 && let Some(w) = self.window.as_ref()
11145 {
11146 w.setTitle(&NSString::from_str(title));
11147 }
11148 }
11149
11150 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11151 use day_spec::WindowChange as C;
11152 let Some(window) = self.ns_window_for(host) else {
11153 return;
11154 };
11155 match change {
11156 C::State(state) => set_ns_window_state(&window, *state),
11157 C::ContentProtected(on) => window.setSharingType(if *on {
11159 objc2_app_kit::NSWindowSharingType::None
11160 } else {
11161 objc2_app_kit::NSWindowSharingType::ReadOnly
11162 }),
11163 other => window_chrome::apply_property(&window, other),
11164 }
11165 }
11166
11167 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11168 self.ns_window_for(host)
11169 .map(|w| window_chrome::frame_of(&w))
11170 }
11171
11172 fn monitors(&self) -> Vec<day_spec::Monitor> {
11173 window_chrome::monitors(self.mtm)
11174 }
11175
11176 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11179
11180 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11181 dock::set_app_items(self.mtm, items);
11182 }
11183
11184 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11185 window_chrome::set_drag_region(h, drag);
11186 }
11187
11188 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11189 status_item::set_items(self.mtm, items);
11190 }
11191
11192 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11193 status_item::set_progress(self.mtm, progress);
11194 }
11195
11196 fn set_dock_visible(&mut self, visible: bool) {
11197 status_item::set_dock_visible(self.mtm, visible);
11198 }
11199
11200 fn set_keep_running(&mut self, keep: bool) {
11201 status_item::set_keep_running(keep);
11202 }
11203
11204 fn quit_app(&mut self) {
11205 let app = NSApplication::sharedApplication(self.mtm);
11206 unsafe { app.terminate(None) };
11207 }
11208
11209 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11210 use present::PresentSpec;
11211 let mtm = self.mtm;
11212 let app = NSApplication::sharedApplication(mtm);
11216 let key = app.keyWindow().filter(|k| {
11217 let mut owner = k.clone();
11218 while let Some(parent) = owner.sheetParent() {
11219 owner = parent;
11220 }
11221 self.window
11222 .as_deref()
11223 .is_some_and(|w| std::ptr::eq(w, &*owner))
11224 || self
11225 .secondary
11226 .iter()
11227 .any(|s| std::ptr::eq(&*s.window, &*owner))
11228 });
11229 let Some(mut window) = key.or_else(|| self.window.clone()) else {
11230 emit(
11231 WINDOW_NODE,
11232 Event::PresentResult {
11233 req,
11234 result: present::PresentResult::Dismissed,
11235 },
11236 );
11237 return;
11238 };
11239 while let Some(sheet) = window.attachedSheet() {
11241 window = sheet;
11242 }
11243 match spec {
11245 PresentSpec::OpenFile {
11246 filters, multiple, ..
11247 } => {
11248 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11249 unsafe {
11250 panel.setCanChooseFiles(true);
11251 panel.setCanChooseDirectories(false);
11252 panel.setAllowsMultipleSelection(*multiple);
11253 panel.setMessage(Some(&NSString::from_str(spec.title())));
11254 }
11255 apply_allowed_file_types(&panel, filters);
11256 let p = panel.clone();
11257 let handler: block2::RcBlock<dyn Fn(isize)> =
11260 block2::RcBlock::new(move |resp: isize| {
11261 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11262 });
11263 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11264 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11265 return;
11266 }
11267 PresentSpec::OpenFolder { .. } => {
11269 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11270 unsafe {
11271 panel.setCanChooseFiles(false);
11272 panel.setCanChooseDirectories(true);
11273 panel.setCanCreateDirectories(true);
11274 panel.setAllowsMultipleSelection(false);
11275 panel.setMessage(Some(&NSString::from_str(spec.title())));
11276 }
11277 let p = panel.clone();
11278 let handler: block2::RcBlock<dyn Fn(isize)> =
11279 block2::RcBlock::new(move |resp: isize| {
11280 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11281 });
11282 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11283 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11284 return;
11285 }
11286 PresentSpec::SaveFile { suggested_name, .. } => {
11287 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11288 unsafe {
11289 panel.setMessage(Some(&NSString::from_str(spec.title())));
11290 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11291 }
11292 apply_allowed_file_types(&panel, spec.filters());
11293 let p = panel.clone();
11294 let handler: block2::RcBlock<dyn Fn(isize)> =
11295 block2::RcBlock::new(move |resp: isize| {
11296 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11298 });
11299 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11300 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11301 return;
11302 }
11303 _ => {}
11304 }
11305 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11306 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11307 if let Some(msg) = spec.message() {
11308 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11309 }
11310 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11312 PresentSpec::Dialog { buttons, .. } => {
11313 if buttons
11314 .iter()
11315 .any(|b| b.role == present::ButtonRole::Destructive)
11316 {
11317 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11318 }
11319 for b in buttons {
11320 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11321 }
11322 block2::RcBlock::new(move |resp: isize| {
11323 ffi_guard::contain((), || {
11324 let idx = resp - 1000;
11326 emit(
11327 WINDOW_NODE,
11328 Event::PresentResult {
11329 req,
11330 result: present::PresentResult::Button(idx as i64),
11331 },
11332 );
11333 PRESENT_ALERTS.with(|m| {
11334 m.borrow_mut().remove(&req);
11335 });
11336 })
11337 })
11338 }
11339 PresentSpec::Prompt {
11340 placeholder,
11341 initial,
11342 ok,
11343 cancel,
11344 ..
11345 } => {
11346 let tf = unsafe { NSTextField::new(mtm) };
11347 unsafe {
11348 tf.setFrame(NSRect::new(
11349 NSPoint::new(0.0, 0.0),
11350 NSSize::new(260.0, 24.0),
11351 ));
11352 tf.setEditable(true);
11353 tf.setBezeled(true);
11354 tf.setStringValue(&NSString::from_str(initial));
11355 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11356 alert.setAccessoryView(Some(&tf));
11357 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
11360 block2::RcBlock::new(move |resp: isize| {
11361 ffi_guard::contain((), || {
11362 let result = if resp == 1000 {
11363 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11364 } else {
11365 present::PresentResult::Dismissed
11366 };
11367 emit(WINDOW_NODE, Event::PresentResult { req, result });
11368 PRESENT_ALERTS.with(|m| {
11369 m.borrow_mut().remove(&req);
11370 });
11371 })
11372 })
11373 }
11374 PresentSpec::OpenFile { .. }
11376 | PresentSpec::OpenFolder { .. }
11377 | PresentSpec::SaveFile { .. } => unreachable!(),
11378 };
11379 unsafe {
11380 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11381 }
11382 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11383 }
11384
11385 fn dismiss(&mut self, req: u64) {
11386 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11389 if let Some(alert) = alert {
11390 let sheet = alert.window();
11391 if let Some(parent) = sheet.sheetParent() {
11392 unsafe { parent.endSheet(&sheet) };
11393 }
11394 }
11395 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11397 if let Some(panel) = panel
11398 && let Some(parent) = panel.sheetParent()
11399 {
11400 unsafe { parent.endSheet(&panel) };
11401 }
11402 }
11403
11404 fn application_handlers(
11405 &mut self,
11406 query: &day_spec::applications::HandlerQuery,
11407 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11408 {
11409 applications::handlers(query)
11410 }
11411
11412 fn open_url_with_application(
11413 &mut self,
11414 url: &str,
11415 application: &str,
11416 completion: day_spec::applications::OpenApplicationCompletion,
11417 ) {
11418 applications::open(url, application, completion);
11419 }
11420
11421 fn share_support(&self) -> day_spec::Support {
11422 day_spec::Support::Native
11423 }
11424 fn share_url(&mut self, url: &str, _title: &str) -> bool {
11425 use objc2::{msg_send, runtime::AnyObject};
11426 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11427 let Some(mtm) = objc2::MainThreadMarker::new() else {
11428 return false;
11429 };
11430 let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11431 return false;
11432 };
11433 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11434 let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11435 return false;
11436 };
11437 unsafe {
11438 let items = NSArray::from_retained_slice(&[url]);
11439 let picker: objc2::rc::Allocated<AnyObject> =
11440 msg_send![objc2::class!(NSSharingServicePicker), alloc];
11441 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11442 let bounds = view.bounds();
11443 let y = if view.isFlipped() {
11444 30.0
11445 } else {
11446 bounds.size.height - 30.0
11447 };
11448 let rect = NSRect::new(
11449 NSPoint::new(bounds.size.width - 30.0, y),
11450 NSSize::new(1.0, 1.0),
11451 );
11452 let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11453 self.sharing = Some(picker);
11454 }
11455 true
11456 }
11457 fn open_url(&mut self, url: &str) {
11458 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11461 if let Some(nsurl) = nsurl {
11462 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11463 }
11464 }
11465}
11466
11467#[allow(deprecated)]
11470fn apply_allowed_file_types(
11471 panel: &objc2_app_kit::NSSavePanel,
11472 filters: &[day_spec::present::FileFilter],
11473) {
11474 let exts: Vec<Retained<NSString>> = filters
11475 .iter()
11476 .flat_map(|f| f.extensions.iter())
11477 .map(|e| NSString::from_str(e))
11478 .collect();
11479 if !exts.is_empty() {
11480 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11481 let arr = objc2_foundation::NSArray::from_slice(&refs);
11482 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11483 }
11484}
11485
11486fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11490 let mut paths = Vec::new();
11491 if resp == 1 {
11492 for url in unsafe { panel.URLs() }.iter() {
11493 if let Some(p) = unsafe { url.path() } {
11494 paths.push(p.to_string());
11495 }
11496 }
11497 }
11498 let result = if paths.is_empty() {
11499 present::PresentResult::Dismissed
11500 } else {
11501 present::PresentResult::Files(paths)
11502 };
11503 emit(WINDOW_NODE, Event::PresentResult { req, result });
11504 PRESENT_PANELS.with(|m| {
11505 m.borrow_mut().remove(&req);
11506 });
11507}
11508
11509fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11511 let result = if resp == 1 {
11512 unsafe { panel.URL() }
11513 .and_then(|url| unsafe { url.path() })
11514 .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11515 .unwrap_or(present::PresentResult::Dismissed)
11516 } else {
11517 present::PresentResult::Dismissed
11518 };
11519 emit(WINDOW_NODE, Event::PresentResult { req, result });
11520 PRESENT_PANELS.with(|m| {
11521 m.borrow_mut().remove(&req);
11522 });
11523}
11524
11525impl Platform for AppKit {
11526 const TARGET: &'static str = "macos-appkit";
11527 const TOOLKIT: &'static str = "appkit";
11528
11529 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11530 let mtm = self.mtm;
11531 self.app_name = options
11535 .app_name
11536 .clone()
11537 .unwrap_or_else(|| options.title.clone());
11538 unsafe {
11547 objc2_foundation::NSProcessInfo::processInfo()
11548 .setProcessName(&NSString::from_str(&self.app_name));
11549 let bundle = objc2_foundation::NSBundle::mainBundle();
11550 let info: Option<Retained<objc2_foundation::NSDictionary>> =
11551 msg_send![&bundle, infoDictionary];
11552 if let Some(info) = info {
11553 let key = NSString::from_str("CFBundleName");
11554 let value = NSString::from_str(&self.app_name);
11555 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11559 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11560 }
11561 }
11562 }
11563 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11568 unsafe {
11569 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11570 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11571 .into_super()
11572 .into_super()
11573 .into_super();
11574 let dict = NSDictionary::from_retained_objects(
11575 &[
11576 &*NSString::from_str("AppleTextDirection"),
11577 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11578 ],
11579 &[yes.clone(), yes],
11580 );
11581 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11582 }
11583 }
11584 let app = NSApplication::sharedApplication(mtm);
11585 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11588 || unsafe {
11589 let bundle = objc2_foundation::NSBundle::mainBundle();
11590 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11591 &bundle,
11592 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11593 ];
11594 value.is_some_and(|v| {
11595 let on: bool = msg_send![&v, boolValue];
11596 on
11597 })
11598 };
11599 app.setActivationPolicy(if menu_bar_app {
11600 NSApplicationActivationPolicy::Accessory
11601 } else {
11602 NSApplicationActivationPolicy::Regular
11603 });
11604 let document_delegate = documents::delegate(mtm);
11605 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11606 if let Ok(theme) = std::env::var("DAY_THEME") {
11609 let name = match theme.as_str() {
11610 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11611 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11612 _ => None,
11613 };
11614 if let Some(name) = name {
11615 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11616 unsafe { app.setAppearance(appearance.as_deref()) };
11617 }
11618 }
11619 register_bundled_fonts();
11621
11622 let app_name = self.app_name.clone();
11626 install_main_menu(mtm, &app, &app_name);
11627 install_lifecycle_observers();
11629 install_appearance_observer();
11630 install_reduce_motion_observer();
11631
11632 let (window, delegate, content) = self.make_window(&options, false, None);
11633 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11637 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11638 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11639 _ => None,
11640 };
11641 if let Some(name) = appearance_name
11642 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11643 {
11644 window.setAppearance(Some(&appearance));
11645 }
11646 std::mem::forget(delegate);
11649
11650 self.window = Some(window.clone());
11651 self.content = Some(content.clone());
11652 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11653
11654 let layout = pin_below_title_bar(&window)
11656 .unwrap_or(Size::new(options.size.width, options.size.height));
11657 ready(self, content, layout);
11658
11659 if day_core::windows::new_window_action_id() == 0
11663 && options.tabbing == day_spec::WindowTabbing::Automatic
11664 {
11665 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11666 }
11667 if !day_core::has_app_menu() {
11672 install_main_menu(mtm, &app, &app_name);
11673 }
11674
11675 let deterministic =
11683 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11684 let autosave = NSString::from_str("day.main");
11685 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11686 window.center();
11687 window_chrome::place(&window, options.placement);
11689 }
11690 if let Some(screen) = capture_screen(mtm) {
11694 let (visible, frame) = (screen.visibleFrame(), window.frame());
11695 window.setFrameOrigin(NSPoint::new(
11696 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11697 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
11698 ));
11699 }
11700 if !deterministic {
11701 unsafe { window.setFrameAutosaveName(&autosave) };
11702 }
11703 if !options.start_hidden {
11704 window.makeKeyAndOrderFront(None);
11705 app.activate();
11706 }
11707 if let Some(content) = window.contentView() {
11712 mark_tree_needs_display(&content);
11713 }
11714 if std::env::var_os("DAY_DUMP").is_some() {
11715 std::thread::spawn(|| {
11716 std::thread::sleep(std::time::Duration::from_millis(2000));
11717 Self::post(Box::new(|| {
11718 if let Some(content) = primary_content() {
11720 let desc: Retained<NSString> =
11721 unsafe { msg_send![&*content, _subtreeDescription] };
11722 log::warn!("{desc}");
11723 }
11724 }));
11725 });
11726 }
11727 app.run();
11728 }
11729
11730 fn post(f: Box<dyn FnOnce() + Send>) {
11731 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
11734 }
11735
11736 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
11737 let when =
11741 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
11742 .unwrap_or(dispatch2::DispatchTime::FOREVER);
11743 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
11744 ffi_guard::contain((), f);
11745 }) {
11746 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
11747 }
11748 }
11749
11750 fn locale_hints(&self) -> Vec<String> {
11751 objc2_foundation::NSLocale::preferredLanguages()
11754 .iter()
11755 .map(|s| s.to_string())
11756 .collect()
11757 }
11758}
11759
11760unsafe extern "C" {
11765 fn CGWindowListCreateImage(
11766 bounds: objc2_core_foundation::CGRect,
11767 list_option: u32,
11768 window_id: u32,
11769 image_option: u32,
11770 ) -> *mut objc2_core_graphics::CGImage;
11771}
11772
11773const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
11776const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
11779
11780fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
11787 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
11788 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
11789 objc2_app_kit::NSColorRenderingIntent::Default,
11790 );
11791 let rep = srgb.as_deref().unwrap_or(rep);
11792 let data = unsafe {
11793 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
11794 }
11795 .ok_or("png encode failed")?;
11796 Ok(data.to_vec())
11797}
11798
11799fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
11812 let window = content.window().ok_or("view is not in a window")?;
11813 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
11816 return snapshot_via_window_server(&sheet, chrome);
11817 }
11818 let number = window.windowNumber();
11819 if number <= 0 {
11820 return Err(format!("window {number} is not on screen"));
11821 }
11822 unsafe { content.layoutSubtreeIfNeeded() };
11829 window.displayIfNeeded();
11830 CATransaction::flush();
11831 let null_rect = objc2_core_foundation::CGRect::new(
11833 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
11834 objc2_core_foundation::CGSize::new(0.0, 0.0),
11835 );
11836 let shot = unsafe {
11837 CGWindowListCreateImage(
11838 null_rect,
11839 CG_WINDOW_LIST_INCLUDING_WINDOW,
11840 number as u32,
11841 CG_WINDOW_IMAGE_IGNORE_FRAMING,
11842 )
11843 };
11844 if shot.is_null() {
11845 return Err("the window server has no image for this window".into());
11846 }
11847 let shot = unsafe {
11850 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
11851 };
11852
11853 if chrome {
11856 let rep = unsafe {
11857 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11858 objc2_app_kit::NSBitmapImageRep::alloc(),
11859 &shot,
11860 )
11861 };
11862 return png_of_rep(&rep);
11863 }
11864
11865 let frame = window.frame();
11869 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
11870 return Err("zero-size window".into());
11871 }
11872 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
11873 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
11876 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
11877 let crop = objc2_core_foundation::CGRect::new(
11878 objc2_core_foundation::CGPoint::new(
11879 (in_window.origin.x * scale).round(),
11880 (from_top * scale).round(),
11881 ),
11882 objc2_core_foundation::CGSize::new(
11883 (in_window.size.width * scale).round(),
11884 (in_window.size.height * scale).round(),
11885 ),
11886 );
11887 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
11888 .ok_or("crop to the content view failed")?;
11889 let rep = unsafe {
11890 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11891 objc2_app_kit::NSBitmapImageRep::alloc(),
11892 &cropped,
11893 )
11894 };
11895 png_of_rep(&rep)
11896}
11897
11898fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
11908 let [x, y, w, h] = base;
11909 let (sw, sh) = (w * t.sx, h * t.sy);
11910 let frame = NSRect::new(
11911 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
11912 NSSize::new(sw, sh),
11913 );
11914 unsafe {
11915 v.setFrameCenterRotation(0.0);
11918 v.setFrame(frame);
11919 v.setBoundsSize(NSSize::new(w, h));
11920 if t.rotate_deg != 0.0 {
11921 v.setFrameCenterRotation(t.rotate_deg);
11922 }
11923 }
11924}
11925
11926fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
11927 let modal = content
11928 .window()
11929 .and_then(|w| w.attachedSheet())
11930 .and_then(|s| s.contentView());
11931 let content = modal.as_deref().unwrap_or(content);
11932 match snapshot_via_window_server(content, false) {
11933 Ok(bytes) => Ok(bytes),
11934 Err(_) => snapshot_view_cache(content),
11935 }
11936}
11937
11938fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
11946 let modal = content
11947 .window()
11948 .and_then(|w| w.attachedSheet())
11949 .and_then(|s| s.contentView());
11950 let content = modal.as_deref().unwrap_or(content);
11951 match snapshot_via_window_server(content, true) {
11952 Ok(bytes) => Ok(bytes),
11953 Err(_) => snapshot_view_cache(content),
11954 }
11955}
11956
11957fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
11961 let bounds = content.bounds();
11962 let rep =
11963 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
11964 let ctx =
11968 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
11969 NSGraphicsContext::saveGraphicsState_class();
11970 NSGraphicsContext::setCurrentContext(Some(&ctx));
11971 content
11972 .effectiveAppearance()
11973 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
11974 NSColor::windowBackgroundColor().setFill();
11975 objc2_app_kit::NSRectFill(bounds);
11976 }));
11977 NSGraphicsContext::restoreGraphicsState_class();
11978 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
11979 png_of_rep(&rep)
11980}
11981
11982fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
11988 let Some(screen) = primary.and_then(|w| w.screen()) else {
11989 return;
11990 };
11991 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
11992 return;
11993 }
11994 let (visible, frame) = (screen.visibleFrame(), window.frame());
11995 window.setFrameOrigin(NSPoint::new(
11996 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11997 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
11998 ));
11999}
12000
12001fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12002 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12003 .ok()?
12004 .trim()
12005 .parse()
12006 .ok()?;
12007 let key = NSString::from_str("NSScreenNumber");
12008 objc2_app_kit::NSScreen::screens(mtm)
12009 .into_iter()
12010 .find(|screen| {
12011 let number: Option<Retained<objc2_foundation::NSNumber>> =
12012 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12013 number.is_some_and(|n| n.unsignedIntValue() == wanted)
12014 })
12015}
12016
12017fn mark_tree_needs_display(view: &NSView) {
12019 view.setNeedsDisplay(true);
12020 for sub in view.subviews() {
12021 mark_tree_needs_display(&sub);
12022 }
12023}
12024
12025pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12030 phase.is_universal()
12031}
12032
12033fn install_appearance_observer() {
12039 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12040 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12041 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12042 dispatch2::DispatchQueue::main()
12043 .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12044 });
12045 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12046 let token = unsafe {
12047 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12048 };
12049 std::mem::forget(token);
12050}
12051
12052fn install_reduce_motion_observer() {
12060 use objc2_foundation::NSNotification;
12061 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12062 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12063 dispatch2::DispatchQueue::main()
12064 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12065 });
12066 let token = unsafe {
12067 center.addObserverForName_object_queue_usingBlock(
12068 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12069 None,
12070 None,
12071 &block,
12072 )
12073 };
12074 std::mem::forget(token);
12075}
12076
12077fn install_lifecycle_observers() {
12080 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12081 let center = unsafe { NSNotificationCenter::defaultCenter() };
12082 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12083 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12084 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12085 });
12086 let token = unsafe {
12087 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12088 };
12089 std::mem::forget(token); };
12091 unsafe {
12092 observe(
12093 NSApplicationDidBecomeActiveNotification,
12094 day_spec::Lifecycle::DidBecomeActive,
12095 );
12096 observe(
12097 NSApplicationWillResignActiveNotification,
12098 day_spec::Lifecycle::WillResignActive,
12099 );
12100 observe(
12101 NSApplicationWillTerminateNotification,
12102 day_spec::Lifecycle::WillTerminate,
12103 );
12104 observe(
12108 NSApplicationWillTerminateNotification,
12109 day_spec::Lifecycle::DidExit,
12110 );
12111 }
12112}
12113
12114day_localization_ui::locales!();
12115
12116fn install_application_menu(
12119 mtm: MainThreadMarker,
12120 menubar: &NSMenu,
12121 title: &str,
12122 about: Option<day_spec::MenuItem>,
12123 updates: Option<day_spec::MenuItem>,
12124 prefs: Option<day_spec::MenuItem>,
12125 quit: Option<day_spec::MenuItem>,
12126) -> Retained<NSMenu> {
12127 let app = NSApplication::sharedApplication(mtm);
12128 use day_spec::{MenuItem as M, MenuRole as R};
12129 let standard = |role, label| M::Action {
12130 id: None,
12131 action: 0,
12132 label,
12133 shortcut: None,
12134 enabled: true,
12135 checked: None,
12136 role: Some(role),
12137 icon: None,
12138 };
12139 let mut about =
12140 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12141 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12142 for (item, title) in [
12143 (&mut about, res::str::about_app(title).format()),
12144 (&mut quit, res::str::quit_app(title).format()),
12145 ] {
12146 if let M::Action { label, .. } = item {
12147 *label = title;
12148 }
12149 }
12150 if let M::Action { action, .. } = &mut about
12153 && *action == 0
12154 {
12155 *action = day_core::windows::about_action_id();
12156 }
12157 let updates_id = day_core::windows::check_for_updates_action_id();
12160 let updates = updates.or_else(|| {
12161 (updates_id != 0).then(|| {
12162 standard(
12163 R::CheckForUpdates,
12164 day_localization::t(day_localization::key::day_check_for_updates),
12165 )
12166 })
12167 });
12168 let mut head = vec![about];
12169 if let Some(mut updates) = updates {
12170 if let M::Action { action, .. } = &mut updates
12171 && *action == 0
12172 {
12173 *action = updates_id;
12174 }
12175 head.push(updates);
12176 }
12177 head.push(M::Separator);
12178 let menu = build_ns_menu(mtm, title, &head);
12179 if let Some(mut prefs) = prefs {
12180 if let M::Action { label, .. } = &mut prefs {
12181 *label = res::str::settings().format();
12182 }
12183 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12184 for item in section.itemArray() {
12185 section.removeItem(&item);
12186 menu.addItem(&item);
12187 }
12188 }
12189 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12192 if let Some(parent) = unsafe { services.supermenu() } {
12193 let index = parent.indexOfItemWithSubmenu(Some(&services));
12194 if index >= 0 {
12195 parent.itemAtIndex(index).unwrap().setSubmenu(None);
12196 }
12197 }
12198 let services_item = NSMenuItem::new(mtm);
12199 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12200 services_item.setSubmenu(Some(&services));
12201 menu.addItem(&services_item);
12202 menu.addItem(&NSMenuItem::separatorItem(mtm));
12203 for (label, selector, shortcut) in [
12204 (
12205 res::str::hide_app(title).format(),
12206 sel!(hide:),
12207 Some(day_spec::Shortcut::primary("h")),
12208 ),
12209 (
12210 res::str::hide_others().format(),
12211 sel!(hideOtherApplications:),
12212 Some(day_spec::Shortcut::primary("h").alt()),
12213 ),
12214 (
12215 res::str::show_all().format(),
12216 sel!(unhideAllApplications:),
12217 None,
12218 ),
12219 ] {
12220 let item = unsafe {
12221 NSMenuItem::initWithTitle_action_keyEquivalent(
12222 NSMenuItem::alloc(mtm),
12223 &NSString::from_str(&label),
12224 Some(selector),
12225 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12226 )
12227 };
12228 if let Some(shortcut) = shortcut {
12229 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12230 }
12231 unsafe { item.setTarget(Some(&app)) };
12233 menu.addItem(&item);
12234 }
12235 menu.addItem(&NSMenuItem::separatorItem(mtm));
12236 let section = build_ns_menu(mtm, title, &[quit]);
12237 let quit = section.itemAtIndex(0).unwrap();
12238 section.removeItem(&quit);
12239 menu.addItem(&quit);
12240 let item = NSMenuItem::new(mtm);
12241 item.setSubmenu(Some(&menu));
12242 menubar.addItem(&item);
12243 services
12244}
12245
12246fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12249 let menubar = NSMenu::new(mtm);
12250
12251 let prefs_id = day_core::windows::preferences_action_id();
12252 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12253 id: None,
12254 action: prefs_id,
12255 label: res::str::settings().format(),
12256 shortcut: None,
12257 enabled: true,
12258 checked: None,
12259 role: Some(day_spec::MenuRole::Preferences),
12260 icon: None,
12261 });
12262 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12263
12264 let new_window_id = day_core::windows::new_window_action_id();
12269 if new_window_id != 0 {
12270 let file_item = NSMenuItem::new(mtm);
12271 let file_menu = unsafe {
12272 NSMenu::initWithTitle(
12273 NSMenu::alloc(mtm),
12274 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12275 )
12276 };
12277 let new_window = unsafe {
12278 NSMenuItem::initWithTitle_action_keyEquivalent(
12279 NSMenuItem::alloc(mtm),
12280 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12281 Some(sel!(fire:)),
12282 &NSString::from_str("n"),
12283 )
12284 };
12285 let target = menu_target(mtm);
12286 let tobj: &objc2::runtime::AnyObject = target.as_ref();
12287 unsafe { new_window.setTarget(Some(tobj)) };
12288 new_window.setTag(new_window_id as isize);
12289 file_menu.addItem(&new_window);
12290 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12291 let close = unsafe {
12293 NSMenuItem::initWithTitle_action_keyEquivalent(
12294 NSMenuItem::alloc(mtm),
12295 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12296 Some(sel!(performClose:)),
12297 &NSString::from_str("w"),
12298 )
12299 };
12300 file_menu.addItem(&close);
12301 file_item.setSubmenu(Some(&file_menu));
12302 menubar.addItem(&file_item);
12303 }
12304
12305 let edit_item = NSMenuItem::new(mtm);
12306 let edit_menu = unsafe {
12307 NSMenu::initWithTitle(
12308 NSMenu::alloc(mtm),
12309 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12310 )
12311 };
12312 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12313 let item = unsafe {
12314 NSMenuItem::initWithTitle_action_keyEquivalent(
12315 NSMenuItem::alloc(mtm),
12316 &NSString::from_str(&day_localization::t(key)),
12317 Some(action),
12318 &NSString::from_str(accel),
12319 )
12320 };
12321 edit_menu.addItem(&item);
12322 };
12323 add("day_undo", sel!(undo:), "z");
12324 add("day_redo", sel!(redo:), "Z");
12325 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12326 add("day_cut", sel!(cut:), "x");
12327 add("day_copy", sel!(copy:), "c");
12328 add("day_paste", sel!(paste:), "v");
12329 add("day_select_all", sel!(selectAll:), "a");
12330 edit_item.setSubmenu(Some(&edit_menu));
12331 menubar.addItem(&edit_item);
12332
12333 install_windows_menu(mtm, app, &menubar);
12334
12335 app.setMainMenu(Some(&menubar));
12336 unsafe { app.setServicesMenu(Some(&services)) };
12337}
12338
12339fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12344 let menu = unsafe {
12345 NSMenu::initWithTitle(
12346 NSMenu::alloc(mtm),
12347 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12348 )
12349 };
12350 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12351 let item = unsafe {
12352 NSMenuItem::initWithTitle_action_keyEquivalent(
12353 NSMenuItem::alloc(mtm),
12354 &NSString::from_str(&day_localization::t(key)),
12355 Some(action),
12356 &NSString::from_str(accel),
12357 )
12358 };
12359 menu.addItem(&item);
12360 };
12361 add("day_minimize", sel!(performMiniaturize:), "m");
12362 add("day_zoom", sel!(performZoom:), "");
12363 menu.addItem(&NSMenuItem::separatorItem(mtm));
12364 add("day_bring_all_front", sel!(arrangeInFront:), "");
12365 let item = NSMenuItem::new(mtm);
12366 item.setTitle(&NSString::from_str(&day_localization::t(
12367 day_localization::key::day_window,
12368 )));
12369 item.setSubmenu(Some(&menu));
12370 menubar.addItem(&item);
12371 unsafe { app.setWindowsMenu(Some(&menu)) };
12372}
12373
12374fn extract_app_role(
12377 items: &mut Vec<day_spec::MenuItem>,
12378 role: day_spec::MenuRole,
12379) -> Option<day_spec::MenuItem> {
12380 use day_spec::MenuItem as M;
12381 let mut found = None;
12382 let mut remaining = Vec::new();
12383 for mut item in items.drain(..) {
12384 match &mut item {
12385 M::Action { role: Some(r), .. } if *r == role => {
12386 found.get_or_insert(item);
12387 continue;
12388 }
12389 M::Submenu { items, .. } => {
12390 let nested = extract_app_role(items, role);
12391 if found.is_none() {
12392 found = nested;
12393 }
12394 if items.is_empty() {
12395 continue;
12396 }
12397 }
12398 M::Separator
12399 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12400 {
12401 continue;
12402 }
12403 _ => {}
12404 }
12405 remaining.push(item);
12406 }
12407 while matches!(remaining.last(), Some(M::Separator)) {
12408 remaining.pop();
12409 }
12410 *items = remaining;
12411 found
12412}
12413
12414fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12416 items.iter().any(|it| match it {
12417 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12418 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12419 day_spec::MenuItem::Separator => false,
12420 })
12421}
12422
12423define_class!(
12429 #[unsafe(super(NSObject))]
12430 #[thread_kind = MainThreadOnly]
12431 #[name = "DayMenuTarget"]
12432 #[ivars = ()]
12433 struct DayMenuTarget;
12434
12435 unsafe impl NSObjectProtocol for DayMenuTarget {}
12436
12437 impl DayMenuTarget {
12438 #[unsafe(method(fire:))]
12439 fn fire(&self, sender: &NSMenuItem) {
12440 ffi_guard::contain((), || {
12441 let id = sender.tag() as u64;
12442 if id != 0 {
12443 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12444 }
12445 })
12446 }
12447 }
12448);
12449
12450pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12459 let content = window.contentView()?;
12460 let full = content.frame().size;
12461 let layout = unsafe { window.contentLayoutRect() }.size;
12462 let top = (full.height - layout.height).max(0.0);
12463 if window_chrome::is_overlay(window) {
12467 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12468 window_chrome::report_title_bar_inset(window, top);
12469 return Some(Size::new(full.width, full.height));
12470 }
12471 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12472 Some(Size::new(full.width, (full.height - top).max(0.0)))
12473}
12474
12475fn native_text(h: &NSView) -> Option<String> {
12479 if h.downcast_ref::<NSSecureTextField>().is_some() {
12480 return None;
12481 }
12482 if let Some(tf) = h.downcast_ref::<NSTextField>() {
12483 return Some(tf.stringValue().to_string());
12485 }
12486 if let Some(btn) = h.downcast_ref::<NSButton>() {
12487 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12488 return None;
12489 }
12490 return Some(btn.title().to_string());
12491 }
12492 let sv = h.downcast_ref::<NSScrollView>()?;
12494 let doc = sv.documentView()?;
12495 let tv = doc.downcast_ref::<NSTextView>()?;
12496 Some(tv.string().to_string())
12497}
12498
12499fn native_number(h: &NSView) -> Option<f64> {
12502 if let Some(sl) = h.downcast_ref::<NSSlider>() {
12503 return Some(sl.doubleValue());
12504 }
12505 let pi = h.downcast_ref::<NSProgressIndicator>()?;
12506 (!pi.isIndeterminate()).then(|| pi.doubleValue())
12507}
12508
12509fn native_frame(h: &NSView) -> Option<Rect> {
12513 let content = h.window()?.contentView()?;
12514 let r = h.convertRect_toView(h.bounds(), Some(&content));
12515 let y = if content.isFlipped() {
12516 r.origin.y
12517 } else {
12518 let b = content.bounds();
12519 b.origin.y + b.size.height - (r.origin.y + r.size.height)
12520 };
12521 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12522}
12523
12524fn title_bar_inset(content: &NSView) -> f64 {
12526 (-content.bounds().origin.y).max(0.0)
12527}
12528
12529fn primary_content() -> Option<Retained<NSView>> {
12530 PRIMARY_CONTENT.with(|c| c.borrow().clone())
12531}
12532
12533fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12534 MENU_TARGET.with(|t| {
12535 t.borrow_mut()
12536 .get_or_insert_with(|| {
12537 let this = DayMenuTarget::alloc(mtm).set_ivars(());
12538 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12539 obj
12540 })
12541 .clone()
12542 })
12543}
12544
12545fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12546 use objc2_app_kit::NSEventModifierFlags as F;
12547 let mut m = F::empty();
12548 if s.primary {
12549 m |= F::Command;
12550 }
12551 if s.shift {
12552 m |= F::Shift;
12553 }
12554 if s.alt {
12555 m |= F::Option;
12556 }
12557 if s.control {
12558 m |= F::Control;
12559 }
12560 m
12561}
12562
12563fn ns_key_equivalent(key: &str) -> String {
12566 match key {
12567 "Return" | "Enter" => "\r".into(),
12568 "Tab" => "\t".into(),
12569 "Delete" | "Backspace" => "\u{8}".into(),
12570 "Escape" => "\u{1b}".into(),
12571 "Space" => " ".into(),
12572 k if k.chars().count() == 1 => k.to_lowercase(),
12573 _ => String::new(), }
12575}
12576
12577fn role_spec(
12580 role: day_spec::MenuRole,
12581) -> (
12582 &'static str,
12583 Option<objc2::runtime::Sel>,
12584 Option<day_spec::Shortcut>,
12585) {
12586 use day_spec::MenuRole as R;
12587 use day_spec::Shortcut as S;
12588 match role {
12589 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12590 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12591 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12592 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12593 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12594 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12595 R::Delete => ("Delete", Some(sel!(delete:)), None),
12596 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12597 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12598 R::Preferences => ("Settings…", None, Some(S::primary(","))),
12599 R::Minimize => (
12600 "Minimize",
12601 Some(sel!(performMiniaturize:)),
12602 Some(S::primary("m")),
12603 ),
12604 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12605 R::Fullscreen => (
12606 "Enter Full Screen",
12607 Some(sel!(toggleFullScreen:)),
12608 Some(S::primary("f").control()),
12609 ),
12610 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12613 R::CheckForUpdates => ("Check for Updates…", None, None),
12615 }
12616}
12617
12618pub(crate) fn build_ns_menu(
12619 mtm: MainThreadMarker,
12620 title: &str,
12621 items: &[day_spec::MenuItem],
12622) -> Retained<NSMenu> {
12623 use day_spec::MenuItem as MI;
12624 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12625 let target = menu_target(mtm);
12626 for item in items {
12627 match item {
12628 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12629 MI::Submenu { label, items, .. } => {
12630 let sub = build_ns_menu(mtm, label, items);
12631 let it = NSMenuItem::new(mtm);
12632 it.setTitle(&NSString::from_str(label));
12633 it.setSubmenu(Some(&sub));
12634 menu.addItem(&it);
12635 }
12636 MI::Action {
12637 action,
12638 label,
12639 shortcut,
12640 enabled,
12641 checked,
12642 role,
12643 icon,
12644 ..
12645 } => {
12646 let (mut lbl, sel, mut sc) = match role {
12648 Some(r) => {
12649 let (dl, ds, dsc) = role_spec(*r);
12650 (dl.to_string(), ds, dsc)
12651 }
12652 None => (String::new(), None, None),
12653 };
12654 if !label.is_empty() {
12655 lbl = label.clone();
12656 }
12657 if shortcut.is_some() {
12658 sc = shortcut.clone();
12659 }
12660 let responder_role = matches!(
12666 role,
12667 Some(
12668 day_spec::MenuRole::Undo
12669 | day_spec::MenuRole::Redo
12670 | day_spec::MenuRole::Cut
12671 | day_spec::MenuRole::Copy
12672 | day_spec::MenuRole::Paste
12673 | day_spec::MenuRole::SelectAll
12674 )
12675 );
12676 let custom = *action != 0 && !responder_role;
12677 let key = sc
12678 .as_ref()
12679 .map(|s| ns_key_equivalent(&s.key))
12680 .unwrap_or_default();
12681 let it = unsafe {
12682 NSMenuItem::initWithTitle_action_keyEquivalent(
12683 NSMenuItem::alloc(mtm),
12684 &NSString::from_str(&lbl),
12685 if custom { Some(sel!(fire:)) } else { sel },
12686 &NSString::from_str(&key),
12687 )
12688 };
12689 if let Some(s) = &sc {
12690 it.setKeyEquivalentModifierMask(ns_modifiers(s));
12691 it.setAllowsAutomaticKeyEquivalentLocalization(true);
12697 it.setAllowsAutomaticKeyEquivalentMirroring(true);
12698 }
12699 if custom {
12700 let tobj: &objc2::runtime::AnyObject = target.as_ref();
12701 unsafe { it.setTarget(Some(tobj)) };
12702 it.setTag(*action as isize);
12703 }
12704 it.setEnabled(*enabled);
12705 if let Some(on) = checked {
12708 it.setState(if *on {
12709 NSControlStateValueOn
12710 } else {
12711 NSControlStateValueOff
12712 });
12713 }
12714 if let Some(icon) = icon
12717 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
12718 {
12719 img.setSize(NSSize::new(16.0, 16.0));
12720 it.setImage(Some(&img));
12721 }
12722 menu.addItem(&it);
12723 }
12724 }
12725 }
12726 menu
12727}
12728
12729fn release_bitmap(id: day_spec::BitmapId) {
12732 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
12733}
12734
12735#[cfg(test)]
12736mod bitmap_teardown_tests {
12737 use super::*;
12738
12739 #[test]
12740 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
12741 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
12743 if std::env::var_os(CHILD).is_some() {
12744 struct LateRelease;
12745 impl Drop for LateRelease {
12746 fn drop(&mut self) {
12747 assert!(BITMAPS.try_with(|_| ()).is_err());
12748 release_bitmap(day_spec::BitmapId(1));
12750 }
12751 }
12752 std::thread_local! {
12753 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
12754 }
12755 std::thread::spawn(|| {
12756 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
12757 BITMAPS.with(|_| ()); })
12759 .join()
12760 .unwrap();
12761 return;
12762 }
12763 let output = std::process::Command::new(std::env::current_exe().unwrap())
12764 .args([
12765 "--exact",
12766 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
12767 "--nocapture",
12768 ])
12769 .env(CHILD, "1")
12770 .output()
12771 .unwrap();
12772 assert!(
12773 output.status.success(),
12774 "{}",
12775 String::from_utf8_lossy(&output.stderr)
12776 );
12777 }
12778}