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::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
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::NSTextInputClient;
36use objc2_app_kit::NSUserInterfaceItemIdentification as _;
37use objc2_app_kit::{
38 NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
39 NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
40};
41use objc2_app_kit::{
42 NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
43 NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
44 NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
45 NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
46 NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
47 NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
48 NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
49 NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
50 NSWindowDelegate, NSWindowStyleMask,
51};
52use objc2_app_kit::{
53 NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
54 NSApplicationWillTerminateNotification,
55};
56use objc2_app_kit::{
57 NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
58};
59use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
60use objc2_core_foundation::CGAffineTransform;
61use objc2_foundation::{
62 NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
63 NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
64};
65use objc2_quartz_core::{
66 CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
67 kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
68 kCAMediaTimingFunctionLinear,
69};
70
71use day_spec::ffi_guard;
72use day_spec::present;
73use day_spec::props::*;
74use day_spec::sidetable::SideTable;
75use day_spec::{
76 A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
77 InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
78 Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
79 WindowOptions, kinds, props_of,
80};
81
82pub type Handle = Retained<NSView>;
83
84pub use toolbar::image_for as toolbar_image;
86
87mod dock;
89mod documents;
90mod frame;
91mod picker;
92mod status_item;
93mod textarea;
94mod toolbar;
95mod transfer;
96mod window_chrome;
97use objc2_app_kit::NSDraggingSource;
98
99pub mod ext;
100pub use ext::*;
101
102type Sink = Rc<dyn Fn(NodeId, Event)>;
108
109day_core::tls_group! {
110 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
111 static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
113 static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
118 RefCell::new(HashMap::new());
119 static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
121 static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
125
126 static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
129 static APP_LABELED: SideTable<()> = SideTable::new();
132 static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
138 static TRANSFORMS: SideTable<Transform> = SideTable::new();
142 static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
145 static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
146 static SHEET_NODES: SideTable<NodeId> = SideTable::new();
148 static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149 static PAN_NODES: SideTable<NodeId> = SideTable::new();
152 static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
153 static HOVER_NODES: SideTable<NodeId> = SideTable::new();
157 static KEY_NODES: SideTable<NodeId> = SideTable::new();
161 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
166 static MARKED: SideTable<String> = SideTable::new();
170 static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
173
174 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
176 RefCell::new(HashMap::new());
177
178 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
179 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
181 RefCell::new(std::collections::HashSet::new());
182 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
188
189 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
190 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
193
194 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
196 static SPLIT_PANES: SideTable<bool> = SideTable::new();
198
199 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
203
204 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
205 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
207
208 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
213 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
216
217 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
219
220 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
222 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
223 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
224 const { std::cell::RefCell::new(None) };
225
226 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
228 RefCell::new(HashMap::new());
229 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
231 RefCell::new(HashMap::new());
232
233 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
236 const { std::cell::RefCell::new(None) };
237 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
241 const { std::cell::RefCell::new(None) };
242
243}
244
245pub fn emit(id: NodeId, ev: Event) {
247 let sink = SINK.with(|s| s.borrow().clone());
248 if let Some(sink) = sink {
249 sink(id, ev);
250 }
251}
252
253fn ptr_of(v: &NSView) -> usize {
254 (v as *const NSView).cast::<()>() as usize
255}
256
257#[derive(Clone, Copy)]
259struct ImageMode {
260 template: bool,
261 tinted: bool,
262}
263
264impl ImageMode {
265 fn renders_template(self) -> bool {
268 self.template || self.tinted
269 }
270}
271
272struct AppKitBitmap {
279 image: Retained<objc2_app_kit::NSImage>,
280 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
281 info: day_spec::BitmapInfo,
282}
283
284fn scaled_rep(
290 image: &objc2_app_kit::NSImage,
291 pixels: Size,
292 scale: f64,
293) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
294 use objc2::AllocAnyThread as _;
295 let w = (pixels.width * scale).round().max(1.0);
296 let h = (pixels.height * scale).round().max(1.0);
297 let rep = unsafe {
298 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
299 objc2_app_kit::NSBitmapImageRep::alloc(),
300 std::ptr::null_mut(),
301 w as isize,
302 h as isize,
303 8,
304 4,
305 true,
306 false,
307 objc2_app_kit::NSDeviceRGBColorSpace,
308 0,
309 0,
310 )
311 }?;
312 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
313 NSGraphicsContext::saveGraphicsState_class();
314 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
315 unsafe {
316 image.drawInRect_fromRect_operation_fraction(
317 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
318 NSRect::ZERO,
319 objc2_app_kit::NSCompositingOperation::SourceOver,
320 1.0,
321 );
322 }
323 NSGraphicsContext::restoreGraphicsState_class();
324 Some(rep)
325}
326
327fn encode_bitmap(
332 id: day_spec::BitmapId,
333 spec: &day_spec::EncodeSpec,
334) -> Result<Vec<u8>, day_spec::ImageError> {
335 use day_spec::ImageFormat as F;
336 use objc2_app_kit::NSBitmapImageFileType as T;
337 let file_type = match spec.format {
338 F::Png => T::PNG,
339 F::Jpeg => T::JPEG,
340 F::Tiff => T::TIFF,
341 F::Bmp => T::BMP,
342 F::Gif => T::GIF,
343 _ => return Err(day_spec::ImageError::Encode),
347 };
348 let held = BITMAPS.with(|m| {
349 m.borrow()
350 .get(&id.0)
351 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
352 });
353 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
354 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
355
356 let rep = match spec.fit {
359 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
360 let scale = (fit.width / info.pixels.width)
361 .min(fit.height / info.pixels.height)
362 .min(1.0);
363 if scale < 1.0 {
364 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
365 } else {
366 rep
367 }
368 }
369 _ => rep,
370 };
371
372 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
373 Some(q) => {
375 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
376 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
377 let value: &objc2::runtime::AnyObject = &number;
378 NSDictionary::from_slices::<NSString>(&[key], &[value])
379 }
380 None => NSDictionary::new(),
381 };
382 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
383 .ok_or(day_spec::ImageError::Encode)?;
384 Ok(data.to_vec())
385}
386
387fn paint_ops(ops: &[DrawOp]) {
391 for op in ops {
392 draw_op(op);
393 }
394}
395
396fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
404 use objc2_core_graphics::CGContext;
405 CGContext::save_g_state(Some(cg));
406 CGContext::translate_ctm(Some(cg), 0.0, height);
407 CGContext::scale_ctm(Some(cg), scale, -scale);
408 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
409 NSGraphicsContext::saveGraphicsState_class();
410 NSGraphicsContext::setCurrentContext(Some(&ns));
411 paint_ops(ops);
412 NSGraphicsContext::restoreGraphicsState_class();
413 CGContext::restore_g_state(Some(cg));
414}
415
416fn render_bitmap_image(
424 ops: &[DrawOp],
425 size: Size,
426 scale: f64,
427) -> Result<AppKitBitmap, day_spec::ExportError> {
428 use objc2::AllocAnyThread as _;
429 use objc2_core_graphics::{
430 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
431 };
432 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
433 let (pw, ph) = day_spec::export_pixels(size, scale);
434 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
436 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
437 let cg = unsafe {
440 CGBitmapContextCreate(
441 std::ptr::null_mut(),
442 pw as usize,
443 ph as usize,
444 8,
445 0,
446 Some(&space),
447 CGImageAlphaInfo::PremultipliedLast.0,
448 )
449 }
450 .ok_or_else(|| {
451 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
452 })?;
453 paint_flipped(&cg, ph as f64, scale, ops);
455 let cg_image = CGBitmapContextCreateImage(Some(&cg))
456 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
457 let rep = unsafe {
458 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
459 objc2_app_kit::NSBitmapImageRep::alloc(),
460 &cg_image,
461 )
462 };
463 let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
466 unsafe { rep.setSize(points) };
467 let image =
468 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
469 unsafe { image.addRepresentation(&rep) };
470 Ok(AppKitBitmap {
471 image,
472 rep: Some(rep),
473 info: day_spec::BitmapInfo {
474 pixels: Size::new(pw as f64, ph as f64),
475 scale,
476 format: None,
477 has_alpha: true,
478 },
479 })
480}
481
482fn render_pdf_bytes(
487 pages: &[day_spec::PdfPage],
488 info: &day_spec::PdfInfo,
489) -> Result<Vec<u8>, day_spec::ExportError> {
490 use objc2_core_foundation::{
491 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
492 };
493 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
494 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
495 let media =
496 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
497 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
498 let data = CFMutableData::new(None, 0)
499 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
500 let consumer = CGDataConsumer::with_cf_data(Some(&data))
501 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
502
503 let mut keys: Vec<&CFString> = Vec::new();
504 let mut values: Vec<CFRetained<CFString>> = Vec::new();
505 let (title_key, author_key) = unsafe {
507 (
508 objc2_core_graphics::kCGPDFContextTitle,
509 objc2_core_graphics::kCGPDFContextAuthor,
510 )
511 };
512 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
513 if let Some(value) = value {
514 keys.push(key);
515 values.push(CFString::from_str(value));
516 }
517 }
518 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
519 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
520
521 let first_box = media(first.size);
522 let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
525 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
526 for page in pages {
527 let page_box = media(page.size);
528 unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
530 paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
531 CGContext::end_page(Some(&pdf));
532 }
533 CGPDFContextClose(Some(&pdf));
535 drop(pdf);
536 drop(consumer);
537 Ok(data.to_vec())
538}
539
540thread_local! {
541 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
544 std::cell::RefCell::new(std::collections::HashMap::new());
545}
546
547fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
560 use objc2_app_kit::{
561 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
562 };
563 let label = |text: &str, size: f64, secondary: bool| {
564 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
565 unsafe {
566 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
567 if secondary {
568 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
569 }
570 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
571 }
572 tf
573 };
574 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
575 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
576 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
577 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
578 const STRETCH: f32 = 1.0;
581 const HOLD: f32 = 750.0;
582 let stack = NSStackView::new(mtm);
583 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
584 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
585 stack.setAlignment(NSLayoutAttribute::CenterY);
586 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
587 stack.setSpacing(6.0);
588 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
590 top: 4.0,
591 left: 0.0,
592 bottom: 4.0,
593 right: 0.0,
594 });
595 let icon = unsafe { NSImageView::new(mtm) };
596 unsafe {
597 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
598 icon.widthAnchor()
599 .constraintEqualToConstant(16.0)
600 .setActive(true);
601 icon.heightAnchor()
602 .constraintEqualToConstant(16.0)
603 .setActive(true);
604 }
605 stack.addArrangedSubview(&icon);
606 let texts = NSStackView::new(mtm);
609 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
610 texts.setAlignment(NSLayoutAttribute::Width);
611 texts.setSpacing(1.0);
612 texts.setHuggingPriority_forOrientation(
615 HOLD,
616 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
617 );
618 let title = label("", size, false);
619 let subtitle = label("", small, true);
620 for line in [&title, &subtitle] {
622 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
623 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
624 }
625 texts.addArrangedSubview(&title);
626 texts.addArrangedSubview(&subtitle);
627 stack.addArrangedSubview(&texts);
628 let detail = label("", size, true);
629 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
630 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
631 stack.addArrangedSubview(&detail);
632 let check = unsafe { NSImageView::new(mtm) };
633 unsafe {
634 check.setImage(
635 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
636 &NSString::from_str("checkmark"),
637 None,
638 )
639 .as_deref(),
640 );
641 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
642 }
643 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
644 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
645 stack.addArrangedSubview(&check);
646 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
647 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
648 dress_list_item(&view, p, mtm);
649 view
650}
651
652fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
654 use objc2_app_kit::{NSImageView, NSStackView};
655 let Some(stack) = view.downcast_ref::<NSStackView>() else {
656 return;
657 };
658 let parts = stack.arrangedSubviews();
659 if parts.len() < 4 {
660 return;
661 }
662 let icon = parts.objectAtIndex(0);
663 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
664 let image = p
665 .icon
666 .as_ref()
667 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
668 unsafe {
669 iv.setImage(image.as_deref());
670 iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
671 }
672 }
673 icon.setHidden(p.icon.is_none());
674 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
675 let lines = texts.arrangedSubviews();
676 if lines.len() == 2 {
677 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
678 tf.setStringValue(&NSString::from_str(&p.title));
679 }
680 let sub = lines.objectAtIndex(1);
681 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
682 tf.setStringValue(&NSString::from_str(&p.subtitle));
683 }
684 sub.setHidden(p.subtitle.is_empty());
685 }
686 }
687 let detail = parts.objectAtIndex(2);
688 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
689 tf.setStringValue(&NSString::from_str(&p.detail));
690 }
691 detail.setHidden(p.detail.is_empty());
692 parts.objectAtIndex(3).setHidden(!p.checked);
693 let words = [&p.title, &p.subtitle, &p.detail]
694 .into_iter()
695 .filter(|w| !w.is_empty())
696 .map(String::as_str)
697 .collect::<Vec<_>>()
698 .join(", ");
699 unsafe {
700 view.setAccessibilityElement(true);
701 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
702 view.setAccessibilitySelected(p.checked);
703 }
704}
705
706fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
712 use objc2::AllocAnyThread as _;
713 match source {
714 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
719 .or_else(|| day_spec::resource::resolve_image_file(name))
720 .and_then(|path| unsafe {
721 objc2_app_kit::NSImage::initWithContentsOfFile(
722 objc2_app_kit::NSImage::alloc(),
723 &NSString::from_str(&path.to_string_lossy()),
724 )
725 }),
726 day_spec::ImageSource::Bytes(bytes) => unsafe {
729 objc2_app_kit::NSImage::initWithData(
730 objc2_app_kit::NSImage::alloc(),
731 &NSData::with_bytes(bytes),
732 )
733 },
734 day_spec::ImageSource::Decoded(id) => {
736 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
737 }
738 }
739}
740
741fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
744 use day_spec::Role;
745 use objc2_app_kit::{
746 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
747 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
748 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
749 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
750 };
751 unsafe {
752 Some(match role {
753 Role::Button => NSAccessibilityButtonRole,
754 Role::Toggle => NSAccessibilityCheckBoxRole,
755 Role::Tab => NSAccessibilityRadioButtonRole,
758 Role::TabList => NSAccessibilityTabGroupRole,
759 Role::Slider => NSAccessibilitySliderRole,
760 Role::TextInput => NSAccessibilityTextFieldRole,
761 Role::Heading(_) => NSAccessibilityHeadingRole,
766 Role::Image => NSAccessibilityImageRole,
767 Role::Meter => NSAccessibilityLevelIndicatorRole,
768 Role::Group => NSAccessibilityGroupRole,
769 Role::Tree => NSAccessibilityOutlineRole,
772 Role::TreeItem => NSAccessibilityRowRole,
773 Role::None => return None,
774 })
775 }
776}
777
778fn day_role_from_ns(ax: &str) -> day_spec::Role {
780 use day_spec::Role;
781 match ax {
782 "AXButton" => Role::Button,
783 "AXCheckBox" => Role::Toggle,
784 "AXSlider" => Role::Slider,
785 "AXTextField" => Role::TextInput,
786 "AXStaticText" | "AXHeading" => Role::Heading(0),
789 "AXOutline" => Role::Tree,
790 "AXImage" => Role::Image,
791 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
792 "AXGroup" => Role::Group,
793 "AXRadioButton" => Role::Tab,
794 "AXTabGroup" => Role::TabList,
795 _ => Role::None,
796 }
797}
798
799struct TargetIvars {
804 node: NodeId,
805}
806
807define_class!(
808 #[unsafe(super(NSObject))]
809 #[thread_kind = MainThreadOnly]
810 #[name = "DayTarget"]
811 #[ivars = TargetIvars]
812 struct DayTarget;
813
814 unsafe impl NSObjectProtocol for DayTarget {}
815 unsafe impl NSTextFieldDelegate for DayTarget {}
816
817 unsafe impl NSTabViewDelegate for DayTarget {
822 #[unsafe(method(tabView:didSelectTabViewItem:))]
823 fn tab_view_did_select(
824 &self,
825 tab_view: &objc2_app_kit::NSTabView,
826 item: Option<&objc2_app_kit::NSTabViewItem>,
827 ) {
828 ffi_guard::contain((), || {
829 if TAB_PICK_SUPPRESS.with(|s| s.get()) {
830 return;
831 }
832 if let Some(item) = item {
833 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
834 if idx >= 0 {
835 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
836 }
837 }
838 })
839 }
840 }
841
842 impl DayTarget {
843 #[unsafe(method(action:))]
848 fn action(&self, sender: &NSControl) {
849 ffi_guard::contain((), || {
850 let node = self.ivars().node;
851 if sender.downcast_ref::<NSSwitch>().is_some() {
852 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
853 } else if sender.downcast_ref::<NSSlider>().is_some() {
854 let value = unsafe { sender.doubleValue() };
855 emit(node, Event::ValueChanged(value));
857 if slider_value_settled() {
863 emit(node, Event::ValueCommitted(value));
864 }
865 } else {
866 emit(node, Event::Pressed);
867 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
870 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
871 unsafe {
872 btn.setState(if on {
873 NSControlStateValueOn
874 } else {
875 NSControlStateValueOff
876 })
877 };
878 }
879 }
880 })
881 }
882
883 #[unsafe(method(navBack:))]
886 fn nav_back(&self, _sender: &NSControl) {
887 ffi_guard::contain((), || {
888 emit(
889 self.ivars().node,
890 Event::NavBack {
891 already_popped: false,
892 },
893 );
894 })
895 }
896 }
897
898 unsafe impl NSControlTextEditingDelegate for DayTarget {
899 #[unsafe(method(controlTextDidChange:))]
900 fn control_text_did_change(&self, notification: &NSNotification) {
901 ffi_guard::contain((), || {
902 let node = self.ivars().node;
903 if let Some(obj) = unsafe { notification.object() }
904 && let Ok(tf) = obj.downcast::<NSTextField>() {
905 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
906 }
907 })
908 }
909
910 #[unsafe(method(controlTextDidEndEditing:))]
914 fn control_text_did_end_editing(&self, notification: &NSNotification) {
915 ffi_guard::contain((), || {
916 let node = self.ivars().node;
917 let movement = unsafe { notification.userInfo() }
918 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
919 .and_then(|n| n.downcast::<NSNumber>().ok())
920 .map(|n| NSTextMovement(n.integerValue()))
921 .unwrap_or(NSTextMovement::Other);
922 if movement == NSTextMovement::Return {
923 emit(node, Event::Submitted);
924 } else {
925 emit(node, Event::FocusChanged(false));
926 }
927 })
928 }
929 }
930);
931
932impl DayTarget {
933 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
934 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
935 unsafe { msg_send![super(this), init] }
936 }
937}
938
939struct CursorIvars {
944 cursor: RefCell<Option<Retained<NSCursor>>>,
946 hidden: Cell<bool>,
948 hiding: Cell<bool>,
950}
951
952define_class!(
958 #[unsafe(super(NSObject))]
959 #[thread_kind = MainThreadOnly]
960 #[name = "DayCursorOwner"]
961 #[ivars = CursorIvars]
962 struct DayCursorOwner;
963
964 unsafe impl NSObjectProtocol for DayCursorOwner {}
965
966 impl DayCursorOwner {
967 #[unsafe(method(cursorUpdate:))]
968 fn cursor_update(&self, _event: &NSEvent) {
969 let iv = self.ivars();
970 if iv.hidden.get() {
971 if !iv.hiding.replace(true) {
972 NSCursor::hide();
973 }
974 return;
975 }
976 if let Some(c) = iv.cursor.borrow().as_ref() {
977 c.set();
978 }
979 }
980
981 #[unsafe(method(mouseExited:))]
982 fn mouse_exited(&self, _event: &NSEvent) {
983 if self.ivars().hiding.replace(false) {
984 NSCursor::unhide();
985 }
986 }
987 }
988);
989
990impl DayCursorOwner {
991 fn new(mtm: MainThreadMarker) -> Retained<Self> {
992 let this = Self::alloc(mtm).set_ivars(CursorIvars {
993 cursor: RefCell::new(None),
994 hidden: Cell::new(false),
995 hiding: Cell::new(false),
996 });
997 unsafe { msg_send![super(this), init] }
998 }
999}
1000
1001#[allow(deprecated)]
1009fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1010 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1011 Some(match c {
1012 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1013 Cursor::Pointer => NSCursor::pointingHandCursor(),
1014 Cursor::Text => NSCursor::IBeamCursor(),
1015 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1016 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1017 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1018 Cursor::Grabbing => NSCursor::closedHandCursor(),
1019 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1020 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1021 Cursor::Copy => NSCursor::dragCopyCursor(),
1022 Cursor::Alias => NSCursor::dragLinkCursor(),
1023 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1024 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1025 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1026 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1027 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1028 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1029 NSCursor::frameResizeCursorFromPosition_inDirections(
1030 NSCursorFrameResizePosition::TopRight,
1031 NSCursorFrameResizeDirections::All,
1032 )
1033 }
1034 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1035 NSCursor::frameResizeCursorFromPosition_inDirections(
1036 NSCursorFrameResizePosition::TopLeft,
1037 NSCursorFrameResizeDirections::All,
1038 )
1039 }
1040 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1041 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1042 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1043 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1044 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1045 Cursor::None => return None,
1046 Cursor::Native(name) => match &**name {
1047 "disappearingItem" => NSCursor::disappearingItemCursor(),
1048 "dragCopy" => NSCursor::dragCopyCursor(),
1049 "dragLink" => NSCursor::dragLinkCursor(),
1050 "contextualMenu" => NSCursor::contextualMenuCursor(),
1051 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1052 _ => return None,
1053 },
1054 })
1055}
1056
1057fn slider_value_settled() -> bool {
1064 let Some(mtm) = MainThreadMarker::new() else {
1065 return false;
1066 };
1067 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1068 return false;
1069 };
1070 matches!(
1071 unsafe { event.r#type() },
1072 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1073 )
1074}
1075
1076struct FieldIvars {
1081 node: NodeId,
1082}
1083
1084define_class!(
1085 #[unsafe(super(NSTextField))]
1086 #[thread_kind = MainThreadOnly]
1087 #[name = "DayTextField"]
1088 #[ivars = FieldIvars]
1089 struct DayTextField;
1090
1091 impl DayTextField {
1092 #[unsafe(method(becomeFirstResponder))]
1097 fn become_first_responder(&self) -> bool {
1098 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1099 if ok {
1100 field_gained_focus(self.ivars().node);
1101 }
1102 ok
1103 }
1104 }
1105);
1106
1107impl DayTextField {
1108 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1109 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1110 unsafe { msg_send![super(this), init] }
1111 }
1112}
1113
1114define_class!(
1119 #[unsafe(super(NSSecureTextField))]
1120 #[thread_kind = MainThreadOnly]
1121 #[name = "DaySecureTextField"]
1122 #[ivars = FieldIvars]
1123 struct DaySecureTextField;
1124
1125 impl DaySecureTextField {
1126 #[unsafe(method(becomeFirstResponder))]
1128 fn become_first_responder(&self) -> bool {
1129 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1130 if ok {
1131 field_gained_focus(self.ivars().node);
1132 }
1133 ok
1134 }
1135 }
1136);
1137
1138impl DaySecureTextField {
1139 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1140 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1141 unsafe { msg_send![super(this), init] }
1142 }
1143}
1144
1145thread_local! {
1146 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1149}
1150
1151fn field_gained_focus(node: NodeId) {
1154 if FIELD_SWAP.with(|s| s.get()) {
1155 return;
1156 }
1157 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1160}
1161
1162fn text_field_node(v: &NSView) -> Option<NodeId> {
1165 v.downcast_ref::<DayTextField>()
1166 .map(|f| f.ivars().node)
1167 .or_else(|| {
1168 v.downcast_ref::<DaySecureTextField>()
1169 .map(|f| f.ivars().node)
1170 })
1171}
1172
1173fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1177 let target = DayTarget::new(mtm, node);
1178 let tf: Retained<NSTextField> = if secure {
1181 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1182 } else {
1183 Retained::into_super(DayTextField::new(mtm, node))
1184 };
1185 unsafe {
1186 tf.setEditable(true);
1187 tf.setBezeled(true);
1188 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1189 }
1190 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1191 tf
1192}
1193
1194fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1198 window.firstResponder().is_some_and(|fr| {
1199 if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1200 return true;
1201 }
1202 fr.downcast::<NSText>().is_ok_and(|text| {
1203 unsafe { text.delegate() }
1204 .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1205 })
1206 })
1207}
1208
1209fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1214 unsafe extern "C" {
1215 fn dlsym(
1216 handle: *mut std::ffi::c_void,
1217 symbol: *const std::ffi::c_char,
1218 ) -> *mut std::ffi::c_void;
1219 }
1220 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1222 unsafe {
1226 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1227 if slot.is_null() {
1228 None
1229 } else {
1230 (*slot).as_ref()
1231 }
1232 }
1233}
1234
1235fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1237 if let Some(v) = table.take(old) {
1238 table.insert(new, v);
1239 }
1240}
1241
1242struct LabelIvars {
1247 node: NodeId,
1248 has_links: Cell<bool>,
1249 has_runs: Cell<bool>,
1250 selectable: Cell<bool>,
1251}
1252
1253define_class!(
1254 #[unsafe(super(NSTextField))]
1255 #[thread_kind = MainThreadOnly]
1256 #[name = "DayLabel"]
1257 #[ivars = LabelIvars]
1258 struct DayLabel;
1259
1260 impl DayLabel {
1261 #[unsafe(method_id(menuForEvent:))]
1262 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1263 ffi_guard::contain(None, || {
1264 if !self.isSelectable()
1265 && let Some(menu) = inherited_context_menu(self, event)
1266 {
1267 return menu;
1268 }
1269 unsafe { msg_send![super(self), menuForEvent: event] }
1270 })
1271 }
1272
1273 #[unsafe(method(drawRect:))]
1274 fn draw_rect(&self, dirty: NSRect) {
1275 let mut ancestor = unsafe { self.superview() };
1279 let mut selection_color = None;
1280 if !self.ivars().has_runs.get() {
1281 while let Some(view) = ancestor {
1282 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1283 if unsafe { row.isSelected() } {
1284 selection_color = Some(unsafe {
1285 if row.isEmphasized() {
1286 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1287 } else {
1288 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1289 }
1290 });
1291 }
1292 break;
1293 }
1294 ancestor = unsafe { view.superview() };
1295 }
1296 }
1297 let cell = unsafe { self.cell() }
1298 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1299 if let (Some(color), Some(cell)) = (selection_color, cell) {
1300 let original = unsafe { cell.textColor() };
1301 unsafe {
1304 cell.setTextColor(Some(&color));
1305 let _: () = msg_send![super(self), drawRect: dirty];
1306 cell.setTextColor(original.as_deref());
1307 }
1308 } else {
1309 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1310 }
1311 }
1312 }
1313
1314 unsafe impl NSObjectProtocol for DayLabel {}
1315 unsafe impl NSTextDelegate for DayLabel {}
1316
1317 unsafe impl NSTextViewDelegate for DayLabel {
1318 #[unsafe(method(textView:clickedOnLink:atIndex:))]
1319 fn clicked_on_link(
1320 &self,
1321 _tv: &NSTextView,
1322 link: &objc2::runtime::AnyObject,
1323 _index: usize,
1324 ) -> bool {
1325 ffi_guard::contain(true, || {
1326 let url: Retained<NSString> = unsafe { msg_send![link, description] };
1328 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1329 true })
1331 }
1332 }
1333);
1334
1335impl DayLabel {
1336 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1337 let this = Self::alloc(mtm).set_ivars(LabelIvars {
1338 node,
1339 has_links: Cell::new(false),
1340 has_runs: Cell::new(false),
1341 selectable: Cell::new(false),
1342 });
1343 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1344 unsafe {
1345 this.setStringValue(&NSString::from_str(text));
1346 this.setEditable(false);
1347 this.setSelectable(false);
1348 this.setBordered(false);
1349 this.setBezeled(false);
1350 this.setDrawsBackground(false);
1351 }
1352 this
1353 }
1354
1355 fn set_links(&self, has_links: bool) {
1356 self.ivars().has_links.set(has_links);
1357 unsafe {
1358 self.setSelectable(has_links || self.ivars().selectable.get());
1359 self.setAllowsEditingTextAttributes(has_links);
1360 }
1361 }
1362}
1363
1364struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1365impl Drop for PanMonitor {
1366 fn drop(&mut self) {
1367 unsafe { NSEvent::removeMonitor(&self.0) };
1368 }
1369}
1370
1371fn install_sheet_escape_monitor() {
1376 SHEET_ESCAPE_MONITOR.with(|slot| {
1377 if slot.borrow().is_some() {
1378 return;
1379 }
1380 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1381 let event = unsafe { raw.as_ref() };
1382 ffi_guard::contain(raw.as_ptr(), || {
1383 let Some(mtm) = MainThreadMarker::new() else {
1384 return raw.as_ptr();
1385 };
1386 let escape = unsafe { event.charactersIgnoringModifiers() }
1387 .is_some_and(|s| s.to_string() == "\u{1b}");
1388 let Some(window) = event.window(mtm).filter(|_| escape) else {
1389 return raw.as_ptr();
1390 };
1391 let app = NSApplication::sharedApplication(mtm);
1392 if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1393 return raw.as_ptr();
1394 }
1395 match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1396 Some(node) => {
1397 emit(
1398 node,
1399 Event::NavBack {
1400 already_popped: false,
1401 },
1402 );
1403 std::ptr::null_mut()
1404 }
1405 None => raw.as_ptr(),
1406 }
1407 })
1408 });
1409 let monitor = unsafe {
1410 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1411 objc2_app_kit::NSEventMask::KeyDown,
1412 &block,
1413 )
1414 };
1415 *slot.borrow_mut() = monitor.map(PanMonitor);
1416 });
1417}
1418
1419fn install_container_pan_monitor() {
1422 PAN_MONITOR.with(|slot| {
1423 if slot.borrow().is_some() {
1424 return;
1425 }
1426 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1427 let event = unsafe { raw.as_ref() };
1428 ffi_guard::contain(raw.as_ptr(), || {
1429 let dx = unsafe { event.scrollingDeltaX() };
1430 let dy = unsafe { event.scrollingDeltaY() };
1431 if dx.abs() <= dy.abs() {
1432 return raw.as_ptr();
1433 }
1434 let Some(mtm) = MainThreadMarker::new() else {
1435 return raw.as_ptr();
1436 };
1437 let Some(window) = event.window(mtm) else {
1438 return raw.as_ptr();
1439 };
1440 let Some(content) = window.contentView() else {
1441 return raw.as_ptr();
1442 };
1443 let point =
1444 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1445 let mut view = content.hitTest(point);
1446 while let Some(v) = view {
1447 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1448 if v.downcast_ref::<DayCanvas>().is_some() {
1449 return raw.as_ptr();
1450 }
1451 let raw_phase = unsafe { event.phase() };
1452 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1453 day_spec::DragPhase::Began
1454 } else if raw_phase.intersects(
1455 objc2_app_kit::NSEventPhase::Ended
1456 | objc2_app_kit::NSEventPhase::Cancelled,
1457 ) {
1458 day_spec::DragPhase::Ended
1459 } else {
1460 day_spec::DragPhase::Changed
1461 };
1462 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1463 emit(
1464 node,
1465 Event::Pan {
1466 phase,
1467 delta: Point::new(dx, dy),
1468 location: Point::new(p.x, p.y),
1469 },
1470 );
1471 return std::ptr::null_mut();
1472 }
1473 view = unsafe { v.superview() };
1474 }
1475 raw.as_ptr()
1476 })
1477 });
1478 *slot.borrow_mut() = unsafe {
1479 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1480 objc2_app_kit::NSEventMask::ScrollWheel,
1481 &block,
1482 )
1483 }
1484 .map(PanMonitor);
1485 });
1486}
1487
1488type Surface = (f64, f64, f64, f64, f64);
1494
1495#[derive(Default)]
1496struct FlippedIvars {
1497 surface: Cell<Option<Surface>>,
1498 section_card: Cell<Option<f64>>,
1501 pane_backdrop: Cell<bool>,
1508}
1509
1510define_class!(
1511 #[unsafe(super(NSView))]
1512 #[thread_kind = MainThreadOnly]
1513 #[name = "DayFlipped"]
1514 #[ivars = FlippedIvars]
1515 struct DayFlipped;
1516
1517 impl DayFlipped {
1518 #[unsafe(method_id(menuForEvent:))]
1519 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1520 ffi_guard::contain(None, || {
1521 inherited_context_menu(self, event)
1522 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1523 })
1524 }
1525
1526 #[unsafe(method(isFlipped))]
1527 fn is_flipped(&self) -> bool {
1528 true
1529 }
1530
1531 #[unsafe(method(acceptsFirstResponder))]
1535 fn accepts_first_responder(&self) -> bool {
1536 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1537 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1538 }
1539
1540 #[unsafe(method(mouseDown:))]
1544 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1545 if transfer::pressed(self, event) { return; }
1546 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1547 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1548 && let Some(window) = self.window()
1549 {
1550 window.makeFirstResponder(Some(self));
1551 }
1552 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1553 }
1554
1555 #[unsafe(method(becomeFirstResponder))]
1556 fn become_first_responder(&self) -> bool {
1557 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1558 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1559 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1560 }
1561 true
1562 }
1563
1564 #[unsafe(method(resignFirstResponder))]
1565 fn resign_first_responder(&self) -> bool {
1566 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1567 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1568 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1569 }
1570 true
1571 }
1572
1573 #[unsafe(method(keyDown:))]
1577 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1578 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1579 let handled = ffi_guard::contain(false, || {
1580 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1581 return false;
1582 };
1583 let Some(key) = key_name(event) else {
1584 return false;
1585 };
1586 if !day_spec::keys::handled(node) {
1587 return false;
1588 }
1589 emit(
1590 node,
1591 Event::Key(day_spec::KeyEvent::named(
1592 key,
1593 key_modifiers(event.modifierFlags()),
1594 )),
1595 );
1596 true
1597 });
1598 if !handled {
1599 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1600 }
1601 }
1602
1603 #[unsafe(method(rightMouseDown:))]
1607 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1608 if let Some(menu) = self.menuForEvent(event) {
1609 unsafe {
1610 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1611 };
1612 } else {
1613 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1614 }
1615 }
1616
1617 #[unsafe(method(drawRect:))]
1618 fn draw_rect(&self, _dirty: NSRect) {
1619 let paint = || {
1620 if self.ivars().pane_backdrop.get() {
1621 let bounds = self.bounds();
1622 unsafe {
1623 NSColor::windowBackgroundColor().setFill();
1626 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1627 }
1628 }
1629 if let Some(radius) = self.ivars().section_card.get() {
1630 let bounds = self.bounds();
1631 unsafe {
1632 let cls = objc2::class!(NSColor);
1635 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1636 let color: objc2::rc::Retained<NSColor> = if has {
1637 msg_send![cls, quaternarySystemFillColor]
1638 } else {
1639 msg_send![cls, controlBackgroundColor]
1640 };
1641 color.setFill();
1642 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1643 bounds, radius, radius,
1644 );
1645 path.fill();
1646 }
1647 }
1648 if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1649 let bounds = self.bounds();
1650 unsafe {
1651 NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1652 let path = if radius > 0.0 {
1653 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1654 bounds, radius, radius,
1655 )
1656 } else {
1657 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1658 };
1659 path.fill();
1660 }
1661 }
1662 };
1663 unsafe {
1672 let names = objc2_foundation::NSArray::from_slice(&[
1673 objc2_app_kit::NSAppearanceNameAqua,
1674 objc2_app_kit::NSAppearanceNameDarkAqua,
1675 ]);
1676 let standard = self
1677 .effectiveAppearance()
1678 .bestMatchFromAppearancesWithNames(&names)
1679 .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1680 match standard {
1681 Some(appearance) => {
1682 let block = block2::StackBlock::new(paint);
1683 appearance.performAsCurrentDrawingAppearance(&block);
1684 }
1685 None => paint(),
1686 }
1687 }
1688 }
1689 }
1690 unsafe impl NSObjectProtocol for DayFlipped {}
1691 unsafe impl NSDraggingSource for DayFlipped {
1692 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1693 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1694 }
1695 impl DayFlipped {
1696 #[unsafe(method(mouseDragged:))]
1697 fn transfer_dragged(&self, event: &NSEvent) {
1698 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1699 }
1700 #[unsafe(method(draggingEntered:))]
1701 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1702 #[unsafe(method(draggingUpdated:))]
1703 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1704 #[unsafe(method(performDragOperation:))]
1705 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1706 }
1707
1708);
1709
1710impl DayFlipped {
1711 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1712 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1713 unsafe { msg_send![super(this), init] }
1714 }
1715
1716 fn set_section_card(&self, corner_radius: f64) {
1722 self.ivars().section_card.set(Some(corner_radius));
1723 unsafe {
1724 let _: () = msg_send![self, setNeedsDisplay: true];
1725 }
1726 }
1727
1728 fn set_pane_backdrop(&self) {
1730 self.ivars().pane_backdrop.set(true);
1731 unsafe {
1732 let _: () = msg_send![self, setNeedsDisplay: true];
1733 }
1734 }
1735
1736 fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1737 self.ivars()
1738 .surface
1739 .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1740 unsafe {
1741 let _: () = msg_send![self, setNeedsDisplay: true];
1742 if clips || corner_radius > 0.0 {
1743 let _: () = msg_send![self, setWantsLayer: true];
1744 let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1745 if !layer.is_null() {
1746 let _: () = msg_send![layer, setCornerRadius: corner_radius];
1747 let _: () = msg_send![layer, setMasksToBounds: true];
1748 }
1749 }
1750 }
1751 }
1752}
1753
1754struct CanvasIvars;
1759
1760define_class!(
1761 #[unsafe(super(NSView))]
1762 #[thread_kind = MainThreadOnly]
1763 #[name = "DayCanvas"]
1764 #[ivars = CanvasIvars]
1765 struct DayCanvas;
1766
1767 impl DayCanvas {
1768 #[unsafe(method(isFlipped))]
1769 fn is_flipped(&self) -> bool {
1770 true
1771 }
1772
1773 #[unsafe(method_id(menuForEvent:))]
1777 fn menu_for_event(
1778 &self,
1779 event: &objc2_app_kit::NSEvent,
1780 ) -> Option<Retained<NSMenu>> {
1781 let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1782 let Some(f) = f else {
1783 return unsafe { msg_send![super(self), menuForEvent: event] };
1784 };
1785 ffi_guard::contain(None, || {
1787 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1788 let items = f(day_spec::Point::new(p.x, p.y));
1789 if items.is_empty() {
1790 return None;
1791 }
1792 Some(build_ns_menu(self.mtm(), "", &items))
1793 })
1794 }
1795
1796 #[unsafe(method(acceptsFirstResponder))]
1801 fn accepts_first_responder(&self) -> bool {
1802 true
1803 }
1804
1805 #[unsafe(method(mouseDown:))]
1809 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1810 if let Some(window) = self.window() {
1811 window.makeFirstResponder(Some(self));
1812 }
1813 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1814 }
1815
1816 #[unsafe(method(becomeFirstResponder))]
1819 fn become_first_responder(&self) -> bool {
1820 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1821 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1822 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1823 }
1824 true
1825 }
1826
1827 #[unsafe(method(resignFirstResponder))]
1828 fn resign_first_responder(&self) -> bool {
1829 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1830 if MARKED.with(|t| t.remove(ptr)).is_some()
1833 && let Some(context) = self.inputContext()
1834 {
1835 context.discardMarkedText();
1836 }
1837 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1838 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1839 }
1840 true
1841 }
1842
1843 #[unsafe(method(keyDown:))]
1849 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1850 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1851 let handled = ffi_guard::contain(false, || {
1852 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1853 return false;
1854 };
1855 if !day_spec::keys::handled(node) {
1859 return false;
1860 }
1861 if day_spec::keys::text(node) {
1862 return full_route_key_down(self, node, event);
1863 }
1864 let Some(key) = key_name(event) else {
1865 return false;
1866 };
1867 emit(
1868 node,
1869 Event::Key(day_spec::KeyEvent::named(
1870 key,
1871 key_modifiers(event.modifierFlags()),
1872 )),
1873 );
1874 true
1875 });
1876 if !handled {
1877 let _: () = unsafe { msg_send![super(self), keyDown: event] };
1878 }
1879 }
1880
1881 #[unsafe(method_id(inputContext))]
1886 fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
1887 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1888 let takes_keyboard = KEY_NODES
1889 .with(|t| t.get(ptr))
1890 .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
1891 if takes_keyboard {
1892 unsafe { msg_send![super(self), inputContext] }
1893 } else {
1894 None
1895 }
1896 }
1897
1898 #[unsafe(method(drawRect:))]
1899 fn draw_rect(&self, _dirty: NSRect) {
1900 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1901 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1902 paint_ops(&ops);
1903 }
1904
1905 #[unsafe(method(mouseEntered:))]
1908 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1909 self.report_hover(event, day_spec::DragPhase::Began);
1910 }
1911
1912 #[unsafe(method(mouseMoved:))]
1913 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1914 self.report_hover(event, day_spec::DragPhase::Changed);
1915 }
1916
1917 #[unsafe(method(mouseExited:))]
1918 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1919 self.report_hover(event, day_spec::DragPhase::Ended);
1920 }
1921
1922 #[unsafe(method(scrollWheel:))]
1923 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1924 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1925 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1926 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1927 return;
1928 };
1929 ffi_guard::contain((), || {
1930 let raw = unsafe { event.phase() };
1933 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1934 day_spec::DragPhase::Began
1935 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1936 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1937 {
1938 day_spec::DragPhase::Ended
1939 } else {
1940 day_spec::DragPhase::Changed
1941 };
1942 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1943 event.scrollingDeltaY()
1944 });
1945 let win = unsafe { event.locationInWindow() };
1946 let loc = self.convertPoint_fromView(win, None);
1947 emit(
1948 node,
1949 Event::Pan {
1950 phase,
1951 delta,
1952 location: Point::new(loc.x, loc.y),
1953 },
1954 );
1955 })
1956 }
1957 }
1958
1959 unsafe impl NSObjectProtocol for DayCanvas {}
1960
1961 unsafe impl NSTextInputClient for DayCanvas {
1965 #[unsafe(method(insertText:replacementRange:))]
1966 unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
1967 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1968 MARKED.with(|t| t.remove(ptr));
1969 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1970 return;
1971 };
1972 let text = text_of_input_string(string);
1973 if text.is_empty() {
1974 return;
1975 }
1976 ffi_guard::contain((), || {
1977 let interpreting = INTERPRETING.with(|i| i.borrow().clone());
1978 let event = match interpreting {
1979 Some((key, mods)) if text.chars().count() == 1 => {
1981 day_spec::KeyEvent::typed_by(key, text, mods)
1982 }
1983 Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
1984 None => day_spec::KeyEvent::typed_text(text, 0),
1986 };
1987 emit(node, Event::Key(event));
1988 });
1989 }
1990
1991 #[unsafe(method(doCommandBySelector:))]
1996 unsafe fn do_command_by_selector(&self, _selector: Sel) {}
1997
1998 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
1999 unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2000 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2001 let text = text_of_input_string(string);
2002 if text.is_empty() {
2003 MARKED.with(|t| t.remove(ptr));
2004 } else {
2005 MARKED.with(|t| t.insert(ptr, text));
2006 }
2007 }
2008
2009 #[unsafe(method(unmarkText))]
2010 fn unmark_text(&self) {
2011 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2012 MARKED.with(|t| t.remove(ptr));
2013 }
2014
2015 #[unsafe(method(selectedRange))]
2016 fn selected_range(&self) -> NSRange {
2017 NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2018 }
2019
2020 #[unsafe(method(markedRange))]
2021 fn marked_range(&self) -> NSRange {
2022 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2023 match MARKED.with(|t| t.get(ptr)) {
2024 Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2025 None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2026 }
2027 }
2028
2029 #[unsafe(method(hasMarkedText))]
2030 fn has_marked_text(&self) -> bool {
2031 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2032 MARKED.with(|t| t.contains(ptr))
2033 }
2034
2035 #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2036 unsafe fn attributed_substring(
2037 &self,
2038 _range: NSRange,
2039 _actual: objc2_foundation::NSRangePointer,
2040 ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2041 None
2042 }
2043
2044 #[unsafe(method_id(validAttributesForMarkedText))]
2045 fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2046 NSArray::new()
2047 }
2048
2049 #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2052 unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2053 let bounds = self.bounds();
2054 let in_window = self.convertRect_toView(bounds, None);
2055 match self.window() {
2056 Some(window) => window.convertRectToScreen(in_window),
2057 None => in_window,
2058 }
2059 }
2060
2061 #[unsafe(method(characterIndexForPoint:))]
2062 fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2063 objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2064 }
2065 }
2066);
2067
2068impl DayCanvas {
2069 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2070 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2071 unsafe { msg_send![super(this), init] }
2072 }
2073
2074 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2082 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2083 let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2084 return;
2085 };
2086 ffi_guard::contain((), || {
2087 let win = unsafe { event.locationInWindow() };
2088 let loc = self.convertPoint_fromView(win, None);
2089 let b = self.bounds();
2090 let inside = loc.x >= b.origin.x
2091 && loc.x <= b.origin.x + b.size.width
2092 && loc.y >= b.origin.y
2093 && loc.y <= b.origin.y + b.size.height;
2094 if !inside && phase != day_spec::DragPhase::Ended {
2097 return;
2098 }
2099 emit(
2100 node,
2101 Event::Hover {
2102 phase,
2103 location: Point::new(loc.x, loc.y),
2104 },
2105 );
2106 });
2107 }
2108}
2109
2110fn install_tracking_area(h: &NSView) {
2114 let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2115 | NSTrackingAreaOptions::MouseMoved
2116 | NSTrackingAreaOptions::ActiveInKeyWindow
2117 | NSTrackingAreaOptions::InVisibleRect;
2118 let any: &objc2::runtime::AnyObject = h;
2119 let area = unsafe {
2120 NSTrackingArea::initWithRect_options_owner_userInfo(
2121 NSTrackingArea::alloc(),
2122 NSRect::ZERO,
2123 opts,
2124 Some(any),
2125 None,
2126 )
2127 };
2128 unsafe { h.addTrackingArea(&area) };
2129}
2130
2131struct GestureIvars {
2136 node: NodeId,
2137 kind: day_spec::GestureKind,
2138}
2139
2140define_class!(
2141 #[unsafe(super(NSObject))]
2142 #[thread_kind = MainThreadOnly]
2143 #[name = "DayGesture"]
2144 #[ivars = GestureIvars]
2145 struct DayGesture;
2146
2147 unsafe impl NSObjectProtocol for DayGesture {}
2148
2149 impl DayGesture {
2150 #[unsafe(method(fire:))]
2151 fn fire(&self, g: &NSGestureRecognizer) {
2152 ffi_guard::contain((), || {
2153 let node = self.ivars().node;
2154 let view = g.view();
2155 let loc = g.locationInView(view.as_deref());
2156 let at = Point::new(loc.x, loc.y);
2157 let phase = match g.state() {
2158 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2159 NSGestureRecognizerState::Ended
2160 | NSGestureRecognizerState::Cancelled
2161 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2162 _ => day_spec::DragPhase::Changed,
2163 };
2164 let obj: &objc2::runtime::AnyObject = g.as_ref();
2165 match self.ivars().kind {
2166 day_spec::GestureKind::Drag => {
2167 let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2168 let t = unsafe { pan.translationInView(view.as_deref()) };
2169 Point::new(t.x, t.y)
2170 } else {
2171 Point::ZERO
2172 };
2173 emit(node, Event::Drag { phase, location: at, translation });
2174 }
2175 day_spec::GestureKind::Pinch => {
2176 let scale = if let Some(m) =
2179 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2180 {
2181 1.0 + unsafe { m.magnification() }
2182 } else {
2183 1.0
2184 };
2185 emit(node, Event::Pinch { phase, scale, location: at });
2186 }
2187 _ => emit(node, Event::Tap(at)),
2188 }
2189 })
2190 }
2191 }
2192);
2193
2194impl DayGesture {
2195 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2196 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2197 unsafe { msg_send![super(this), init] }
2198 }
2199}
2200
2201struct NavHeader {
2210 bar: Retained<NSView>,
2211 title: Retained<NSTextField>,
2212 titles: Vec<String>,
2214 _target: Retained<DayTarget>,
2215}
2216
2217const NAV_HEADER_H: f64 = 34.0;
2219
2220use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2224
2225fn take_list_placement(state: &mut NavState) -> Option<f64> {
2229 if !state.list_visible || state.list_positioned {
2230 return None;
2231 }
2232 state.list_positioned = true;
2233 state.list_width
2234}
2235
2236const NAV_TABVIEW_INSET: f64 = 12.0;
2239const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2240
2241struct TabHost {
2253 view: Retained<objc2_app_kit::NSTabView>,
2254 target: Option<Retained<DayTarget>>,
2257}
2258
2259thread_local! {
2260 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2263}
2264
2265fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2269 unsafe {
2270 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2271 for (i, title) in titles.iter().enumerate().take(n) {
2272 tabs.view
2273 .tabViewItemAtIndex(i as isize)
2274 .setLabel(&NSString::from_str(title));
2275 }
2276 if n > 0 {
2277 TAB_PICK_SUPPRESS.with(|s| s.set(true));
2278 tabs.view
2279 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2280 TAB_PICK_SUPPRESS.with(|s| s.set(false));
2281 }
2282 }
2283}
2284
2285fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2289 let Some((titles, node)) = NAV_MENUS.with(|m| {
2290 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2291 let ivars = d.ivars();
2292 (
2293 ivars
2294 .items
2295 .borrow()
2296 .iter()
2297 .map(|s| s.to_string())
2298 .collect::<Vec<String>>(),
2299 ivars.node,
2300 )
2301 })
2302 }) else {
2303 return;
2304 };
2305 let mut up = unsafe { menu.superview() };
2306 while let Some(v) = up {
2307 let reached = NAV_STATE.with(|m| {
2308 let mut m = m.borrow_mut();
2309 let Some(s) = m.get_mut(&ptr_of(&v)) else {
2310 return false;
2311 };
2312 let selected = s.selected;
2313 if let Some(tabs) = s.tabs.as_mut() {
2314 if tabs.target.is_none() {
2315 let target = DayTarget::new(mtm, node);
2316 unsafe {
2317 tabs.view
2318 .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2319 };
2320 tabs.target = Some(target);
2321 }
2322 sync_tab_labels(tabs, &titles, selected);
2323 }
2324 true
2325 });
2326 if reached {
2327 return;
2328 }
2329 up = unsafe { v.superview() };
2330 }
2331}
2332
2333struct NavState {
2334 sidebar_wrap: Retained<NSView>,
2335 detail_wrap: Retained<NSView>,
2336 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2341 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2345 list_wrap: Option<Retained<NSView>>,
2351 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2352 list_width: Option<f64>,
2355 list_visible: bool,
2359 list_positioned: bool,
2365 pages: Vec<Retained<NSView>>,
2368 sidebar_page: Option<Retained<NSView>>,
2371 list_page: Option<Retained<NSView>>,
2374 positioned: bool,
2375 presentation: NavPresentation,
2379 selected: usize,
2382 tabs: Option<TabHost>,
2386 header: Option<NavHeader>,
2388 root_title: String,
2391 node: NodeId,
2393 title_strip: f64,
2397}
2398
2399fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2411 let pane = view_of(DayFlipped::new(mtm));
2412 unsafe {
2413 wrap.setFrame(pane.bounds());
2414 wrap.setAutoresizingMask(
2415 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2416 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2417 );
2418 pane.addSubview(wrap);
2419 }
2420 pane
2421}
2422
2423fn place_below_strip(wrap: &NSView, strip: f64) {
2425 let Some(pane) = (unsafe { wrap.superview() }) else {
2426 return;
2427 };
2428 let b = pane.bounds();
2429 unsafe {
2430 wrap.setFrame(NSRect::new(
2431 NSPoint::new(0.0, strip),
2432 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2433 ))
2434 };
2435}
2436
2437fn build_nav_header(
2445 mtm: MainThreadMarker,
2446 id: NodeId,
2447 detail_wrap: &NSView,
2448 root_title: &str,
2449) -> NavHeader {
2450 let bar = view_of(DayFlipped::new(mtm));
2451 let target = DayTarget::new(mtm, id);
2452 let back = unsafe {
2453 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2456 .expect("NSGoBackTemplate");
2457 let tobj: &objc2::runtime::AnyObject = target.as_ref();
2458 objc2_app_kit::NSButton::buttonWithImage_target_action(
2459 &img,
2460 Some(tobj),
2461 Some(sel!(navBack:)),
2462 mtm,
2463 )
2464 };
2465 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2466 unsafe {
2467 back.setFrame(NSRect::new(
2468 NSPoint::new(6.0, 4.0),
2469 NSSize::new(30.0, NAV_HEADER_H - 8.0),
2470 ));
2471 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2472 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2473 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2474 title.setFrame(NSRect::new(
2475 NSPoint::new(44.0, 9.0),
2476 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2477 ));
2478 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2479 bar.setFrame(NSRect::new(
2480 NSPoint::new(0.0, 0.0),
2481 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2482 ));
2483 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2484 bar.addSubview(&back);
2485 bar.addSubview(&title);
2486 bar.setHidden(true);
2487 detail_wrap.addSubview(&bar);
2488 }
2489 NavHeader {
2490 bar,
2491 title,
2492 titles: vec![root_title.to_string()],
2493 _target: target,
2494 }
2495}
2496
2497fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2501 let b = wrap.bounds();
2502 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2503 NSRect::new(
2504 NSPoint::new(0.0, top),
2505 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2506 )
2507}
2508
2509fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2516 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2517 if out.is_some() {
2518 return;
2519 }
2520 let found = NAV_MENUS.with(|m| {
2521 m.borrow()
2522 .get(&(v as *const NSView as usize))
2523 .map(|(_, d)| {
2524 let ivars = d.ivars();
2525 (
2526 ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2527 ivars.node,
2528 )
2529 })
2530 });
2531 if found.is_some() {
2532 *out = found;
2533 return;
2534 }
2535 for sub in unsafe { v.subviews() }.iter() {
2536 walk(&sub, out);
2537 }
2538 }
2539 let mut out = None;
2540 walk(page, &mut out);
2541 out
2542}
2543
2544fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2547 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2548 unsafe {
2549 item.setCanCollapse(shown);
2550 item.setCollapsed(!shown);
2551 match pres {
2552 NavPresentation::Split => {
2553 item.setAllowsFullHeightLayout(true);
2554 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2555 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2556 }
2557 NavPresentation::Rail => {
2563 item.setAllowsFullHeightLayout(true);
2564 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2565 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2566 }
2567 NavPresentation::Stack | NavPresentation::Tabs => {
2570 item.setMinimumThickness(0.0);
2571 item.setMaximumThickness(0.0);
2572 }
2573 }
2574 }
2575}
2576
2577pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2583 NAV_STATE.with(|m| {
2584 m.borrow()
2585 .values()
2586 .find(|st| {
2587 st.list_item.is_some()
2588 && st
2589 .sidebar_wrap
2590 .window()
2591 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2592 })
2593 .map(|st| unsafe { st._split_vc.splitView() })
2594 })
2595}
2596
2597fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2598 let visible = pages.len() >= 2;
2599 hdr.bar.setHidden(!visible);
2600 unsafe {
2601 hdr.title.setStringValue(&NSString::from_str(
2602 hdr.titles.last().map(String::as_str).unwrap_or(""),
2603 ));
2604 }
2605 let frame = nav_page_frame(wrap, visible);
2606 for page in pages {
2607 unsafe { page.setFrame(frame) };
2608 }
2609}
2610
2611fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2626 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2627 NAV_STATE.with(|m| {
2628 let st = m.borrow();
2629 let s = st.get(&ptr_of(host))?;
2630 Some((
2631 s.sidebar_page.clone(),
2632 s.detail_wrap.clone(),
2633 s.sidebar_wrap.clone(),
2634 s.sidebar_item.clone(),
2635 s.presentation,
2636 s.root_title.clone(),
2637 s.node,
2638 s.selected,
2639 ))
2640 })
2641 else {
2642 return;
2643 };
2644 if was == next {
2645 return;
2646 }
2647 apply_sidebar_item(&sidebar_item, next);
2648 NAV_STATE.with(|m| {
2653 if let Some(s) = m.borrow().get(&ptr_of(host)) {
2654 unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2655 }
2656 });
2657 let stacked = next == NavPresentation::Stack;
2660 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2661 if stacked && header.is_none() {
2662 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2663 }
2664 if let Some(hdr) = header.as_ref() {
2665 hdr.bar.setHidden(true);
2666 }
2667 let mut pages = NAV_STATE.with(|m| {
2673 m.borrow()
2674 .get(&ptr_of(host))
2675 .map(|s| s.pages.clone())
2676 .unwrap_or_default()
2677 });
2678 let shown_page = pages.get(sel).cloned();
2679 if let Some(page) = sidebar_page {
2682 pages.retain(|p| ptr_of(p) != ptr_of(&page));
2683 unsafe {
2684 if stacked {
2685 detail_wrap.addSubview(&page);
2686 pages.insert(0, page.clone());
2687 } else {
2688 page.setFrame(sidebar_wrap.bounds());
2689 sidebar_wrap.addSubview(&page);
2690 }
2691 }
2692 page.setHidden(false);
2694 }
2695 let shown = shown_page
2696 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2697 .unwrap_or_else(|| pages.len().saturating_sub(1));
2698 for (i, page) in pages.iter().enumerate() {
2699 page.setHidden(i != shown);
2700 }
2701 NAV_STATE.with(|m| {
2702 let mut m = m.borrow_mut();
2703 if let Some(s) = m.get_mut(&ptr_of(host)) {
2704 s.presentation = next;
2705 s.pages = pages;
2706 s.selected = shown;
2707 s.header = header;
2708 if let Some(hdr) = s.header.as_ref() {
2709 if stacked {
2711 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2712 } else {
2713 hdr.bar.setHidden(true);
2714 }
2715 }
2716 if !stacked {
2717 let frame = nav_page_frame(&s.detail_wrap, false);
2720 for page in &s.pages {
2721 unsafe { page.setFrame(frame) };
2722 }
2723 }
2724 }
2725 });
2726}
2727
2728struct CoverSheet(Retained<NSWindow>);
2737impl Drop for CoverSheet {
2738 fn drop(&mut self) {
2739 let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
2741 let raw = Retained::into_raw(self.0.clone()) as usize;
2744 dispatch2::DispatchQueue::main().exec_async(move || {
2745 ffi_guard::contain((), || unsafe {
2746 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2747 if let Some(parent) = window.sheetParent() {
2748 parent.endSheet(&window);
2749 }
2750 window.orderOut(None);
2751 window.setContentView(None);
2752 });
2753 });
2754 }
2755}
2756struct NavPageIvars {
2757 node: NodeId,
2758 top_inset: Cell<f64>,
2762 sheet: Cell<bool>,
2763 half: Cell<bool>,
2765 large: Cell<bool>,
2768}
2769
2770define_class!(
2771 #[unsafe(super(NSView))]
2772 #[thread_kind = MainThreadOnly]
2773 #[name = "DayNavPage"]
2774 #[ivars = NavPageIvars]
2775 struct DayNavPage;
2776
2777 impl DayNavPage {
2778 #[unsafe(method(isFlipped))]
2779 fn is_flipped(&self) -> bool {
2780 true
2781 }
2782
2783 #[unsafe(method(setFrameSize:))]
2784 fn set_frame_size(&self, size: NSSize) {
2785 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2786 ffi_guard::contain((), || {
2789 let inset = self.ivars().top_inset.get();
2790 emit(
2791 self.ivars().node,
2792 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2793 );
2794 })
2795 }
2796 }
2797);
2798
2799impl DayNavPage {
2800 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2801 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2802 node,
2803 top_inset: Cell::new(0.0),
2804 sheet: Cell::new(false),
2805 half: Cell::new(false),
2806 large: Cell::new(false),
2807 });
2808 unsafe { msg_send![super(this), init] }
2809 }
2810}
2811
2812struct InspectorState {
2821 content_wrap: Handle,
2822 panel_wrap: Handle,
2823 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2825 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2826}
2827
2828struct SplitState {
2836 split: Retained<objc2_app_kit::NSSplitView>,
2837 first_wrap: Handle,
2838 second_wrap: Handle,
2839 delegate: Retained<DaySplitDelegate>,
2840}
2841
2842struct SplitDelegateIvars {
2843 node: NodeId,
2844 min_pane: f64,
2845 share: Cell<f64>,
2848 positioned: Cell<bool>,
2850 suppress: Cell<bool>,
2852}
2853
2854define_class!(
2855 #[unsafe(super(NSObject))]
2856 #[thread_kind = MainThreadOnly]
2857 #[name = "DaySplitDelegate"]
2858 #[ivars = SplitDelegateIvars]
2859 struct DaySplitDelegate;
2860
2861 unsafe impl NSObjectProtocol for DaySplitDelegate {}
2862
2863 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2864 #[unsafe(method(splitViewDidResizeSubviews:))]
2865 fn did_resize(&self, notification: &NSNotification) {
2866 ffi_guard::contain((), || {
2867 let Some(obj) = notification.object() else {
2868 return;
2869 };
2870 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2871 return;
2872 };
2873 let iv = self.ivars();
2874 let usable = split_usable(&sv);
2875 if usable <= 0.0 {
2876 return;
2877 }
2878 if !iv.positioned.replace(true) {
2880 split_place(&sv, iv);
2881 return;
2882 }
2883 if iv.suppress.get() {
2884 return;
2885 }
2886 let Some(first) = sv.subviews().iter().next() else {
2887 return;
2888 };
2889 let f = first.frame();
2890 let a = if sv.isVertical() {
2891 f.size.width
2892 } else {
2893 f.size.height
2894 };
2895 let share = (a / usable).clamp(0.0, 1.0);
2896 if (share - iv.share.get()).abs() > 1e-4 {
2897 iv.share.set(share);
2898 emit(iv.node, Event::ValueChanged(share));
2899 }
2900 })
2901 }
2902
2903 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2904 fn constrain_min(
2905 &self,
2906 _sv: &objc2_app_kit::NSSplitView,
2907 proposed: f64,
2908 _index: isize,
2909 ) -> f64 {
2910 proposed.max(self.ivars().min_pane)
2911 }
2912
2913 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2914 fn constrain_max(
2915 &self,
2916 sv: &objc2_app_kit::NSSplitView,
2917 proposed: f64,
2918 _index: isize,
2919 ) -> f64 {
2920 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2921 }
2922 }
2923);
2924
2925impl DaySplitDelegate {
2926 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2927 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2928 node,
2929 min_pane,
2930 share: Cell::new(share.clamp(0.0, 1.0)),
2931 positioned: Cell::new(false),
2932 suppress: Cell::new(false),
2933 });
2934 unsafe { msg_send![super(this), init] }
2935 }
2936}
2937
2938fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2940 let frame = sv.frame();
2941 let len = if sv.isVertical() {
2942 frame.size.width
2943 } else {
2944 frame.size.height
2945 };
2946 (len - sv.dividerThickness()).max(0.0)
2947}
2948
2949fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2951 let usable = split_usable(sv);
2952 if usable <= 0.0 {
2953 return;
2954 }
2955 iv.suppress.set(true);
2956 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2957 iv.suppress.set(false);
2958}
2959
2960struct NavMenuIvars {
2967 node: NodeId,
2968 items: RefCell<Vec<Retained<NSString>>>,
2969 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2973 icon_fills: RefCell<Vec<f64>>,
2976 tints: RefCell<Vec<Option<day_spec::Color>>>,
2979 badges: RefCell<Vec<Option<Retained<NSString>>>>,
2981 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2984 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2985 badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2987 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2990 movable: RefCell<Vec<bool>>,
2992 regroup: std::cell::Cell<bool>,
2994 sorted: RefCell<Vec<bool>>,
2996 rows: RefCell<Vec<Option<usize>>>,
3000 row_objects: RefCell<Vec<Retained<NSString>>>,
3002 row_ids: RefCell<Vec<Retained<NSNumber>>>,
3007 suppress: std::cell::Cell<bool>,
3009}
3010
3011struct NavCellIvars {
3012 accessory: RefCell<Option<Retained<NSView>>>,
3015 count: RefCell<Option<Retained<NSTextField>>>,
3017 icon_fill: std::cell::Cell<f64>,
3019}
3020
3021define_class!(
3022 #[unsafe(super(objc2_app_kit::NSTableCellView))]
3027 #[thread_kind = MainThreadOnly]
3028 #[name = "DayNavCell"]
3029 #[ivars = NavCellIvars]
3030 struct DayNavCell;
3031
3032 unsafe impl NSObjectProtocol for DayNavCell {}
3033
3034 impl DayNavCell {
3035 #[unsafe(method(layout))]
3036 fn layout(&self) {
3037 let _: () = unsafe { msg_send![super(self), layout] };
3038 ffi_guard::contain((), || self.fit_accessories());
3039 }
3040 }
3041);
3042
3043impl DayNavCell {
3044 fn new(mtm: MainThreadMarker) -> Retained<Self> {
3045 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3046 accessory: RefCell::new(None),
3047 count: RefCell::new(None),
3048 icon_fill: std::cell::Cell::new(1.0),
3049 });
3050 unsafe { msg_send![super(this), init] }
3051 }
3052
3053 fn fit_accessories(&self) {
3058 let label = unsafe { self.textField() };
3059 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3060 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3061 (f.pointSize() - 2.0).max(9.0)
3062 });
3063 if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
3064 unsafe {
3065 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3066 size,
3067 objc2_app_kit::NSFontWeightRegular,
3068 )));
3069 }
3070 self.layoutSubtreeIfNeeded();
3071 }
3072 }
3073 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3074 let mut frame = label.frame();
3075 let end = accessory.frame().origin.x - 6.0;
3076 if frame.origin.x + frame.size.width > end {
3077 frame.size.width = (end - frame.origin.x).max(0.0);
3078 label.setFrame(frame);
3079 }
3080 }
3081 if let Some(icon) = unsafe { self.imageView() } {
3082 fit_nav_icon(&icon, self.ivars().icon_fill.get());
3083 nav_progress::fit(&icon);
3084 }
3085 }
3086}
3087
3088thread_local! {
3089 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3091}
3092
3093fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3102 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3103 return;
3104 };
3105 let slot = icon.frame();
3106 let key = config.hash() as u64;
3109 let side = NAV_GLYPH_SIDES
3110 .with(|m| m.borrow().get(&key).copied())
3111 .or_else(|| {
3112 let symbol =
3113 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3114 &NSString::from_str("gearshape"),
3115 None,
3116 )?;
3117 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3118 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3119 Some(side)
3120 });
3121 let Some(side) = side
3124 .filter(|s| *s > 0.0)
3125 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3126 else {
3127 return;
3128 };
3129 if slot.size.width <= side && slot.size.height <= side {
3130 return;
3131 }
3132 icon.setFrame(NSRect::new(
3133 NSPoint::new(
3134 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3135 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3136 ),
3137 NSSize::new(side, side),
3138 ));
3139}
3140
3141define_class!(
3142 #[unsafe(super(objc2_app_kit::NSTableRowView))]
3143 #[thread_kind = MainThreadOnly]
3144 #[name = "DayNavRowView"]
3145 struct DayNavRowView;
3146
3147 unsafe impl NSObjectProtocol for DayNavRowView {}
3148
3149 impl DayNavRowView {
3150 #[unsafe(method(isEmphasized))]
3156 fn is_emphasized(&self) -> bool {
3157 true
3158 }
3159 }
3160);
3161
3162define_class!(
3163 #[unsafe(super(objc2_app_kit::NSOutlineView))]
3164 #[thread_kind = MainThreadOnly]
3165 #[name = "DayNavOutlineView"]
3166 struct DayNavOutlineView;
3167
3168 unsafe impl NSObjectProtocol for DayNavOutlineView {}
3169
3170 impl DayNavOutlineView {
3171 #[unsafe(method_id(menuForEvent:))]
3175 fn menu_for_event(
3176 &self,
3177 event: &objc2_app_kit::NSEvent,
3178 ) -> Option<Retained<NSMenu>> {
3179 ffi_guard::contain(None, || {
3180 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3181 let row = unsafe { self.rowAtPoint(point) };
3182 let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3183 match data {
3185 None => None,
3186 Some(d) => {
3187 let items = d
3188 .item_of_row(row)
3189 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3190 .unwrap_or_default();
3191 if items.is_empty() {
3192 None
3193 } else {
3194 Some(build_ns_menu(d.mtm(), "", &items))
3195 }
3196 }
3197 }
3198 })
3199 }
3200 }
3201);
3202
3203define_class!(
3204 #[unsafe(super(NSObject))]
3205 #[thread_kind = MainThreadOnly]
3206 #[name = "DayNavMenuData"]
3207 #[ivars = NavMenuIvars]
3208 struct DayNavMenuData;
3209
3210 unsafe impl NSObjectProtocol for DayNavMenuData {}
3211
3212 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3213 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3214 fn number_of_children(
3215 &self,
3216 _ov: &objc2_app_kit::NSOutlineView,
3217 item: Option<&objc2::runtime::AnyObject>,
3218 ) -> isize {
3219 if item.is_none() {
3220 self.ivars().row_objects.borrow().len() as isize
3221 } else {
3222 0
3223 }
3224 }
3225
3226 #[unsafe(method_id(outlineView:child:ofItem:))]
3227 fn child_of_item(
3228 &self,
3229 _ov: &objc2_app_kit::NSOutlineView,
3230 index: isize,
3231 _item: Option<&objc2::runtime::AnyObject>,
3232 ) -> Retained<objc2::runtime::AnyObject> {
3233 let ids = self.ivars().row_ids.borrow();
3234 let id = ids
3238 .get(index as usize)
3239 .cloned()
3240 .unwrap_or_else(|| NSNumber::new_isize(-1));
3241 unsafe { objc2::rc::Retained::cast_unchecked(id) }
3242 }
3243
3244 #[unsafe(method(outlineView:isItemExpandable:))]
3245 fn is_expandable(
3246 &self,
3247 _ov: &objc2_app_kit::NSOutlineView,
3248 _item: &objc2::runtime::AnyObject,
3249 ) -> bool {
3250 false
3251 }
3252
3253 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3260 fn pasteboard_writer_for_item(
3261 &self,
3262 _ov: &objc2_app_kit::NSOutlineView,
3263 item: &objc2::runtime::AnyObject,
3264 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3265 let make = || {
3266 let row = Self::outline_row(item);
3267 let index = self.item_of_row(row)?;
3268 if !self.is_movable(index) {
3269 return None;
3270 }
3271 let pbitem = objc2_app_kit::NSPasteboardItem::new();
3272 unsafe {
3273 pbitem.setString_forType(
3274 &NSString::from_str(&row.to_string()),
3275 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3276 );
3277 }
3278 Some(ProtocolObject::from_retained(pbitem))
3279 };
3280 ffi_guard::contain(None, make)
3281 }
3282
3283 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3284 fn validate_drop(
3285 &self,
3286 ov: &objc2_app_kit::NSOutlineView,
3287 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3288 item: Option<&objc2::runtime::AnyObject>,
3289 child_index: isize,
3290 ) -> objc2_app_kit::NSDragOperation {
3291 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3292 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3293 return objc2_app_kit::NSDragOperation::None;
3294 };
3295 if drop.retarget {
3297 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3298 }
3299 objc2_app_kit::NSDragOperation::Move
3300 })
3301 }
3302
3303 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3304 fn accept_drop(
3305 &self,
3306 ov: &objc2_app_kit::NSOutlineView,
3307 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3308 item: Option<&objc2::runtime::AnyObject>,
3309 child_index: isize,
3310 ) -> bool {
3311 ffi_guard::contain(false, || {
3312 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3313 return false;
3314 };
3315 match drop.moves {
3318 Some(NavMove::Reorder { from, to }) => {
3319 emit(self.ivars().node, Event::ListReorder { from, to });
3320 }
3321 Some(NavMove::Regroup {
3322 from,
3323 section,
3324 before,
3325 }) => emit(
3326 self.ivars().node,
3327 Event::NavRegroup {
3328 from,
3329 section,
3330 before,
3331 },
3332 ),
3333 None => {}
3334 }
3335 true
3336 })
3337 }
3338 }
3339
3340 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3341
3342 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3343 #[unsafe(method(outlineView:isGroupItem:))]
3346 fn is_group_item(
3347 &self,
3348 _ov: &objc2_app_kit::NSOutlineView,
3349 item: &objc2::runtime::AnyObject,
3350 ) -> bool {
3351 let row = Self::outline_row(item);
3352 row >= 0 && self.item_of_row(row).is_none()
3353 }
3354
3355 #[unsafe(method(outlineView:shouldSelectItem:))]
3356 fn should_select(
3357 &self,
3358 _ov: &objc2_app_kit::NSOutlineView,
3359 item: &objc2::runtime::AnyObject,
3360 ) -> bool {
3361 self.item_of_row(Self::outline_row(item)).is_some()
3362 }
3363
3364 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3365 fn view_for(
3366 &self,
3367 ov: &objc2_app_kit::NSOutlineView,
3368 _col: Option<&objc2_app_kit::NSTableColumn>,
3369 item: &objc2::runtime::AnyObject,
3370 ) -> Option<Retained<NSView>> {
3371 let mtm = self.mtm();
3372 let row = Self::outline_row(item);
3373 let text = self
3374 .ivars()
3375 .row_objects
3376 .borrow()
3377 .get(usize::try_from(row).unwrap_or(usize::MAX))
3378 .cloned();
3379 text.map(|text| {
3381 let text: &NSString = &text;
3382 let Some(index) = self.item_of_row(row) else {
3383 let cell = DayNavCell::new(mtm);
3386 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3387 unsafe {
3388 label.cell().inspect(|c| {
3389 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3390 });
3391 cell.addSubview(&label);
3392 cell.setTextField(Some(&label));
3393 }
3394 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3395 };
3396 let icon = self
3397 .ivars()
3398 .icons
3399 .borrow()
3400 .get(index)
3401 .and_then(|o| o.clone());
3402 let badge = self
3403 .ivars()
3404 .badges
3405 .borrow()
3406 .get(index)
3407 .and_then(|o| o.clone());
3408 let badge_icon = self
3409 .ivars()
3410 .badge_icons
3411 .borrow()
3412 .get(index)
3413 .and_then(|o| o.clone());
3414 let badge_tint = self
3415 .ivars()
3416 .badge_tints
3417 .borrow()
3418 .get(index)
3419 .copied()
3420 .flatten();
3421 let cell = DayNavCell::new(mtm);
3425 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3426 unsafe {
3427 label.cell().inspect(|c| {
3430 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3431 });
3432 cell.addSubview(&label);
3433 cell.setTextField(Some(&label));
3434 let accessory = objc2_app_kit::NSStackView::new(mtm);
3441 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3442 accessory.setOrientation(
3443 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3444 );
3445 accessory.setSpacing(4.0);
3446 let mut has_accessory = false;
3447 let trailing: Retained<NSView> = match &badge {
3448 Some(text) => {
3449 let b = NSTextField::labelWithString(text, mtm);
3450 b.setTranslatesAutoresizingMaskIntoConstraints(false);
3451 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3452 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3453 b.setFont(Some(
3454 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3455 objc2_app_kit::NSFont::smallSystemFontSize(),
3456 objc2_app_kit::NSFontWeightRegular,
3457 ),
3458 ));
3459 b.setContentCompressionResistancePriority_forOrientation(
3460 objc2_app_kit::NSLayoutPriorityRequired,
3461 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3462 );
3463 *cell.ivars().count.borrow_mut() = Some(b.clone());
3464 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3465 objc2::rc::Retained::into_super(b),
3466 ));
3467 has_accessory = true;
3468 let v: Retained<NSView> =
3469 objc2::rc::Retained::into_super(accessory.clone());
3470 v
3471 }
3472 None => objc2::rc::Retained::into_super(accessory.clone()),
3473 };
3474 if let Some(img) = &badge_icon {
3479 let iv = objc2_app_kit::NSImageView::new(mtm);
3480 iv.setImage(Some(img));
3481 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3482 if let Some(c) = badge_tint {
3483 iv.setContentTintColor(Some(&nscolor(c)));
3484 }
3485 iv.setContentCompressionResistancePriority_forOrientation(
3486 objc2_app_kit::NSLayoutPriorityRequired,
3487 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3488 );
3489 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3490 has_accessory = true;
3491 }
3492 cell.addSubview(&trailing);
3493 if has_accessory {
3494 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3495 }
3496 objc2_app_kit::NSLayoutConstraint::activateConstraints(
3497 &objc2_foundation::NSArray::from_retained_slice(&[
3498 trailing
3499 .trailingAnchor()
3500 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3501 trailing
3502 .centerYAnchor()
3503 .constraintEqualToAnchor(&cell.centerYAnchor()),
3504 ]),
3505 );
3506 }
3507 if let Some(img) = icon {
3508 let fill = self.ivars().icon_fills.borrow().get(index).copied();
3509 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3510 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3511 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3512 unsafe {
3513 iv.setImage(Some(&img));
3514 if let Some(t) = tint {
3517 iv.setContentTintColor(Some(&nscolor(t)));
3518 }
3519 iv.setImageScaling(
3520 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3521 );
3522 cell.addSubview(&iv);
3523 cell.setImageView(Some(&iv));
3524 let progress = self
3525 .ivars()
3526 .icon_progress
3527 .borrow()
3528 .iter()
3529 .find(|(row, _)| *row == index)
3530 .map(|(_, f)| *f);
3531 nav_progress::update(&iv, progress);
3532 }
3533 }
3534 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3535 })
3536 }
3537
3538 #[unsafe(method_id(outlineView:rowViewForItem:))]
3539 fn row_view_for(
3540 &self,
3541 _ov: &objc2_app_kit::NSOutlineView,
3542 _item: &objc2::runtime::AnyObject,
3543 ) -> Retained<objc2_app_kit::NSTableRowView> {
3544 let row: Retained<DayNavRowView> =
3545 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3546 objc2::rc::Retained::into_super(row)
3547 }
3548
3549 #[unsafe(method(outlineViewSelectionDidChange:))]
3550 fn selection_did_change(&self, notification: &NSNotification) {
3551 ffi_guard::contain((), || {
3552 if self.ivars().suppress.get() {
3553 return;
3554 }
3555 let Some(obj) = (unsafe { notification.object() }) else {
3556 return;
3557 };
3558 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3559 return;
3560 };
3561 let row = unsafe { ov.selectedRow() };
3562 if let Some(item) = self.item_of_row(row) {
3563 emit(self.ivars().node, Event::SelectionChanged(item as i64));
3564 }
3565 })
3566 }
3567 }
3568);
3569
3570thread_local! {
3571 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3574}
3575
3576fn nav_icon_fills(
3578 names: &[Option<String>],
3579 images: &[Option<Retained<objc2_app_kit::NSImage>>],
3580) -> Vec<f64> {
3581 names
3582 .iter()
3583 .zip(images)
3584 .map(|(name, image)| match (name, image) {
3585 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3586 *m.borrow_mut()
3587 .entry(name.clone())
3588 .or_insert_with(|| nav_icon_fill(image))
3589 }),
3590 _ => 1.0,
3591 })
3592 .collect()
3593}
3594
3595fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3600 const PX: f64 = 64.0;
3601 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3602 return 1.0;
3603 };
3604 let (w, h) = (
3605 rep.pixelsWide().max(0) as usize,
3606 rep.pixelsHigh().max(0) as usize,
3607 );
3608 let stride = rep.bytesPerRow().max(0) as usize;
3609 let data = unsafe { rep.bitmapData() };
3610 if data.is_null() || stride < w * 4 {
3611 return 1.0;
3612 }
3613 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3616 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3617 for y in 0..h {
3618 for x in 0..w {
3619 if bytes[y * stride + x * 4 + 3] > 24 {
3620 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3621 }
3622 }
3623 }
3624 if x1 <= x0 || y1 <= y0 {
3625 return 1.0;
3626 }
3627 let size = image.size();
3630 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3631 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3632 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3633}
3634
3635fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3636 icons
3638 .iter()
3639 .map(|ic| {
3640 let name = ic.as_deref()?;
3641 let path = day_spec::resource::resolve_vector_svg(name)
3643 .or_else(|| day_spec::resource::resolve_image_file(name))?;
3644 use objc2::AllocAnyThread as _;
3645 let img = unsafe {
3646 objc2_app_kit::NSImage::initWithContentsOfFile(
3647 objc2_app_kit::NSImage::alloc(),
3648 &NSString::from_str(&path.to_string_lossy()),
3649 )
3650 }?;
3651 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3653 Some(img)
3654 })
3655 .collect()
3656}
3657
3658impl DayNavMenuData {
3659 #[allow(clippy::too_many_arguments)]
3660 fn new(
3661 mtm: MainThreadMarker,
3662 node: NodeId,
3663 items: &[String],
3664 icons: &[Option<String>],
3665 badges: &[Option<String>],
3666 badge_icons: &[Option<String>],
3667 badge_tints: &[Option<day_spec::Color>],
3668 sections: &[Option<String>],
3669 tints: &[Option<day_spec::Color>],
3670 menus: &[Vec<day_spec::MenuItem>],
3671 ) -> Retained<Self> {
3672 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3673 node,
3674 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3675 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3676 icons: RefCell::new(resolve_nav_icons(icons)),
3677 tints: RefCell::new(tints.to_vec()),
3678 menus: RefCell::new(menus.to_vec()),
3679 movable: RefCell::new(Vec::new()),
3680 regroup: std::cell::Cell::new(false),
3681 sorted: RefCell::new(Vec::new()),
3682 badges: RefCell::new(ns_badges(badges)),
3683 icon_progress: RefCell::new(Vec::new()),
3684 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3685 badge_tints: RefCell::new(badge_tints.to_vec()),
3686 rows: RefCell::new(Vec::new()),
3687 row_objects: RefCell::new(Vec::new()),
3688 row_ids: RefCell::new(Vec::new()),
3689 suppress: std::cell::Cell::new(false),
3690 });
3691 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3692 this.rebuild_rows(items, sections);
3693 this
3694 }
3695
3696 #[allow(clippy::too_many_arguments)]
3700 fn set_items(
3701 &self,
3702 items: &[String],
3703 icons: &[Option<String>],
3704 badges: &[Option<String>],
3705 badge_icons: &[Option<String>],
3706 badge_tints: &[Option<day_spec::Color>],
3707 sections: &[Option<String>],
3708 tints: &[Option<day_spec::Color>],
3709 menus: &[Vec<day_spec::MenuItem>],
3710 ) {
3711 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3712 let resolved = resolve_nav_icons(icons);
3713 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3714 *self.ivars().icons.borrow_mut() = resolved;
3715 *self.ivars().tints.borrow_mut() = tints.to_vec();
3716 *self.ivars().menus.borrow_mut() = menus.to_vec();
3717 *self.ivars().badges.borrow_mut() = ns_badges(badges);
3718 self.ivars().icon_progress.borrow_mut().clear();
3719 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3720 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3721 self.rebuild_rows(items, sections);
3722 }
3723
3724 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3728 let mut rows = Vec::with_capacity(items.len());
3729 let mut objects = Vec::with_capacity(items.len());
3730 for (i, label) in items.iter().enumerate() {
3731 if let Some(Some(header)) = sections.get(i) {
3732 rows.push(None);
3733 objects.push(NSString::from_str(header));
3734 }
3735 rows.push(Some(i));
3736 objects.push(NSString::from_str(label));
3737 }
3738 let ids = (0..objects.len())
3739 .map(|i| NSNumber::new_isize(i as isize))
3740 .collect();
3741 *self.ivars().rows.borrow_mut() = rows;
3742 *self.ivars().row_objects.borrow_mut() = objects;
3743 *self.ivars().row_ids.borrow_mut() = ids;
3744 }
3745
3746 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3749 item.downcast_ref::<NSNumber>()
3750 .map(|n| n.integerValue())
3751 .unwrap_or(-1)
3752 }
3753
3754 fn item_of_row(&self, row: isize) -> Option<usize> {
3756 if row < 0 {
3757 return None;
3758 }
3759 self.ivars()
3760 .rows
3761 .borrow()
3762 .get(row as usize)
3763 .copied()
3764 .flatten()
3765 }
3766
3767 fn row_of_item(&self, item: usize) -> Option<usize> {
3769 self.ivars()
3770 .rows
3771 .borrow()
3772 .iter()
3773 .position(|r| *r == Some(item))
3774 }
3775
3776 fn is_movable(&self, item: usize) -> bool {
3777 self.ivars()
3778 .movable
3779 .borrow()
3780 .get(item)
3781 .copied()
3782 .unwrap_or(false)
3783 }
3784
3785 fn nav_drop(
3790 &self,
3791 ov: &objc2_app_kit::NSOutlineView,
3792 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3793 item: Option<&objc2::runtime::AnyObject>,
3794 child_index: isize,
3795 ) -> Option<NavDrop> {
3796 let src = unsafe { info.draggingSource() }?;
3797 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3798 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3799 {
3800 return None;
3801 }
3802 let pb = unsafe { info.draggingPasteboard() };
3803 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3804 .to_string()
3805 .parse::<usize>()
3806 .ok()?;
3807 let rows = self.ivars().rows.borrow();
3808 let proposed = match item {
3811 Some(item) => Self::outline_row(item),
3812 None => child_index,
3813 };
3814 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3815 if self.ivars().regroup.get() {
3816 regroup_gap(
3817 &rows,
3818 &self.ivars().movable.borrow(),
3819 &self.ivars().sorted.borrow(),
3820 from_row,
3821 proposed,
3822 item.is_some(),
3823 )
3824 } else {
3825 reorder_gap(
3826 &rows,
3827 &self.ivars().movable.borrow(),
3828 from_row,
3829 proposed,
3830 item.is_some(),
3831 )
3832 }
3833 }
3834}
3835
3836#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3838struct NavDrop {
3839 gap: usize,
3841 retarget: bool,
3843 moves: Option<NavMove>,
3845}
3846
3847#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3849enum NavMove {
3850 Reorder { from: usize, to: usize },
3852 Regroup {
3855 from: usize,
3856 section: usize,
3857 before: Option<usize>,
3858 },
3859}
3860
3861fn reorder_gap(
3866 rows: &[Option<usize>],
3867 movable: &[bool],
3868 from_row: usize,
3869 proposed: usize,
3870 onto: bool,
3871) -> Option<NavDrop> {
3872 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3873 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3874 let in_run = |r: usize| rows[r].is_some_and(is_movable);
3875 let first = (0..from_row)
3876 .rev()
3877 .take_while(|r| in_run(*r))
3878 .last()
3879 .unwrap_or(from_row);
3880 let last = (from_row + 1..rows.len())
3881 .take_while(|r| in_run(*r))
3882 .last()
3883 .unwrap_or(from_row);
3884 let gap = proposed.clamp(first, last + 1);
3885 let target_row = if gap > from_row { gap - 1 } else { gap };
3887 let moves = (target_row != from_row)
3888 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3889 .flatten();
3890 Some(NavDrop {
3891 gap,
3892 retarget: gap != proposed || onto,
3893 moves,
3894 })
3895}
3896
3897fn regroup_gap(
3905 rows: &[Option<usize>],
3906 movable: &[bool],
3907 sorted: &[bool],
3908 from_row: usize,
3909 proposed: usize,
3910 onto: bool,
3911) -> Option<NavDrop> {
3912 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3913 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3914 let gap = match rows.get(proposed) {
3915 Some(None) if onto => proposed + 1,
3916 _ => proposed.min(rows.len()),
3917 };
3918 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3920 Some(header) => Some(header + 1),
3921 None => rows.first().copied().flatten().map(|_| 0),
3922 };
3923 let first = section_start(gap)?;
3924 let end = (first..rows.len())
3925 .find(|r| rows[*r].is_none())
3926 .unwrap_or(rows.len());
3927 let section = rows.get(first).copied().flatten()?;
3928 if !rows[first..end]
3929 .iter()
3930 .all(|r| r.is_some_and(|i| flag(movable, i)))
3931 {
3932 return None;
3933 }
3934 let own = section_start(from_row) == Some(first);
3935 if own && flag(sorted, from) {
3936 return None;
3937 }
3938 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3939 from,
3940 section,
3941 before: rows.get(gap).copied().flatten(),
3942 });
3943 Some(NavDrop {
3944 gap,
3945 retarget: gap != proposed || onto,
3946 moves,
3947 })
3948}
3949
3950#[cfg(test)]
3951mod nav_gap_tests {
3952 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3953
3954 const ROWS: [Option<usize>; 10] = [
3956 Some(0),
3957 None,
3958 Some(1),
3959 Some(2),
3960 Some(3),
3961 None,
3962 Some(4),
3963 Some(5),
3964 None,
3965 Some(6),
3966 ];
3967 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3969 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3970 const UNSORTED: [bool; 7] = [false; 7];
3971
3972 fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3973 Some(NavMove::Regroup {
3974 from,
3975 section,
3976 before,
3977 })
3978 }
3979
3980 #[test]
3981 fn regroup_gaps_name_the_section_above_and_the_row_below() {
3982 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3983 assert_eq!(
3985 at(2, 6),
3986 Some(NavDrop {
3987 gap: 6,
3988 retarget: false,
3989 moves: regroup(1, 4, Some(4)),
3990 })
3991 );
3992 assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3994 assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3996 assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3997 }
3998
3999 #[test]
4000 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4001 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4002 for gap in [0, 1, 9, 10] {
4004 assert_eq!(at(2, gap), None, "gap {gap}");
4005 }
4006 for gap in [2, 3, 4, 5] {
4008 assert_eq!(at(2, gap), None, "gap {gap}");
4009 }
4010 assert_eq!(at(0, 6), None);
4012 assert_eq!(at(1, 6), None);
4013 assert_eq!(at(9, 6), None);
4014 }
4015
4016 #[test]
4017 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4018 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4019 assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
4021 assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
4023 for gap in [2, 3] {
4025 let drop = at(2, gap).expect("offered");
4026 assert_eq!(drop.moves, None, "gap {gap}");
4027 }
4028 }
4029
4030 #[test]
4031 fn regroup_drops_onto_a_row_move_to_a_gap() {
4032 assert_eq!(
4034 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4035 Some(NavDrop {
4036 gap: 6,
4037 retarget: true,
4038 moves: regroup(1, 4, Some(4)),
4039 })
4040 );
4041 assert_eq!(
4042 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4043 Some(NavDrop {
4044 gap: 7,
4045 retarget: true,
4046 moves: regroup(1, 4, Some(5)),
4047 })
4048 );
4049 }
4050
4051 #[test]
4052 fn regroup_offers_nothing_above_a_leading_header() {
4053 let rows = [None, Some(0), None, Some(1)];
4055 let movable = [true, true];
4056 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4057 assert_eq!(at(0), None);
4058 assert_eq!(at(1).map(|d| d.moves), Some(None));
4059 assert_eq!(at(2).map(|d| d.moves), Some(None));
4060 assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
4061 assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
4062 }
4063
4064 #[test]
4065 fn reorder_gaps_clamp_to_the_run() {
4066 assert_eq!(
4068 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4069 Some(NavDrop {
4070 gap: 5,
4071 retarget: true,
4072 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4073 })
4074 );
4075 assert_eq!(
4077 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4078 Some(None)
4079 );
4080 assert_eq!(
4082 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4083 Some(NavMove::Reorder { from: 2, to: 1 })
4084 );
4085 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4086 }
4087}
4088
4089const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4091
4092fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4094 badges
4095 .iter()
4096 .map(|b| b.as_deref().map(NSString::from_str))
4097 .collect()
4098}
4099
4100fn post_realize_visible_rows(key: usize) {
4106 <AppKit as Platform>::post(Box::new(move || {
4107 if let Some((table, data)) = list_entry(key) {
4108 unsafe { table.layoutSubtreeIfNeeded() };
4109 let range = unsafe { table.rowsInRect(table.visibleRect()) };
4110 if let Some(source) = data.ivars().source.borrow().clone()
4111 && let Some(report) = &source.first_visible
4112 {
4113 report(range.location.min((source.len)().saturating_sub(1)));
4114 }
4115 for row in range.location..range.location + range.length {
4116 let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4117 if let Some(cell) = cell
4121 && cell.subviews().is_empty()
4122 {
4123 let source = data.ivars().source.borrow().clone();
4124 if let Some(source) = source {
4125 (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4126 }
4127 }
4128 }
4129 }
4130 day_core::pump_events();
4133 }));
4134}
4135
4136fn post_settle_list_drop(key: usize) {
4141 <AppKit as Platform>::post(Box::new(move || {
4142 day_core::pump_events();
4145 let Some((table, data)) = list_entry(key) else {
4146 return;
4147 };
4148 let Some(scroll) = table.enclosingScrollView() else {
4149 return;
4150 };
4151 let clip = scroll.contentView();
4152 let origin = clip.bounds().origin;
4153 let selected = table.selectedRowIndexes();
4154 let suppressed = data.ivars().suppress.replace(true);
4155 table.reloadData();
4156 table.layoutSubtreeIfNeeded();
4158 let restored = objc2_foundation::NSMutableIndexSet::new();
4159 for row in 0..table.numberOfRows().max(0) as usize {
4160 if selected.containsIndex(row) {
4161 restored.addIndex(row);
4162 }
4163 }
4164 table.selectRowIndexes_byExtendingSelection(&restored, false);
4165 let mut bounds = clip.bounds();
4166 bounds.origin = origin;
4167 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4168 scroll.reflectScrolledClipView(&clip);
4169 data.ivars().suppress.set(suppressed);
4170 post_realize_visible_rows(key);
4171 }));
4172}
4173
4174define_class!(
4183 #[unsafe(super(NSTableView))]
4184 #[thread_kind = MainThreadOnly]
4185 #[name = "DayListView"]
4186 struct DayListView;
4187 unsafe impl NSObjectProtocol for DayListView {}
4188 impl DayListView {
4189 #[unsafe(method_id(menuForEvent:))]
4192 fn menu_for_event(
4193 &self,
4194 event: &objc2_app_kit::NSEvent,
4195 ) -> Option<Retained<NSMenu>> {
4196 ffi_guard::contain(None, || {
4197 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4198 let row = unsafe { self.rowAtPoint(point) };
4199 let provider = if row >= 0 {
4200 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4201 .and_then(|cell| list_row_menu_provider(&cell))
4202 } else {
4203 None
4204 };
4205 match provider {
4206 Some((view, provider)) => {
4207 let point = view.convertPoint_fromView(
4208 unsafe { event.locationInWindow() }, None,
4209 );
4210 let items = provider(day_spec::Point::new(point.x, point.y));
4211 if items.is_empty() {
4212 None
4213 } else {
4214 Some(build_ns_menu(self.mtm(), "", &items))
4215 }
4216 }
4217 None => unsafe { msg_send![super(self), menuForEvent: event] },
4218 }
4219 })
4220 }
4221
4222 #[unsafe(method(becomeFirstResponder))]
4223 fn become_first_responder(&self) -> bool {
4224 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4225 if accepted {
4226 self.report_focus(true);
4227 }
4228 accepted
4229 }
4230
4231 #[unsafe(method(resignFirstResponder))]
4232 fn resign_first_responder(&self) -> bool {
4233 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4234 if accepted {
4235 self.report_focus(false);
4236 }
4237 accepted
4238 }
4239
4240 #[unsafe(method(keyDown:))]
4241 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4242 ffi_guard::contain((), || {
4243 let key = unsafe { event.keyCode() };
4244 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4245 let row = unsafe { self.selectedRow() };
4246 if row >= 0 && let Some(target) = unsafe { self.target() } {
4247 let _: () = unsafe { msg_send![&*target, activateRow: self] };
4248 return;
4249 }
4250 }
4251 let _: () = unsafe { msg_send![super(self), keyDown: event] };
4252 });
4253 }
4254 }
4255);
4256
4257fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4260 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4261 return Some((view.retain(), provider));
4262 }
4263 view.subviews()
4264 .iter()
4265 .find_map(|view| list_row_menu_provider(&view))
4266}
4267
4268fn inherited_context_menu(
4272 view: &NSView,
4273 event: &objc2_app_kit::NSEvent,
4274) -> Option<Option<Retained<NSMenu>>> {
4275 let mut current = Some(view.retain());
4276 while let Some(view) = current {
4277 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4278 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4279 let items = provider(day_spec::Point::new(point.x, point.y));
4280 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4281 }
4282 current = unsafe { view.superview() };
4283 }
4284 None
4285}
4286
4287impl DayListView {
4288 fn report_focus(&self, focused: bool) {
4289 ffi_guard::contain((), || {
4290 if let Some(target) = unsafe { self.target() }
4291 && let Some(data) = target.downcast_ref::<DayListData>()
4292 {
4293 emit(data.ivars().node, Event::FocusChanged(focused));
4294 }
4295 });
4296 }
4297}
4298
4299struct ListIvars {
4300 node: NodeId,
4301 source: RefCell<Option<ListSource>>,
4303 selectable: std::cell::Cell<bool>,
4304 multi: std::cell::Cell<bool>,
4306 suppress: std::cell::Cell<bool>,
4308 tokens: RefCell<Vec<u64>>,
4311 automatic: bool,
4315 sections: bool,
4319 header_estimate: std::cell::Cell<f64>,
4321 heights: RefCell<std::collections::HashMap<u64, f64>>,
4324 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4327 estimate: std::cell::Cell<f64>,
4330 heights_pending: std::cell::Cell<bool>,
4332}
4333
4334define_class!(
4335 #[unsafe(super(NSObject))]
4336 #[thread_kind = MainThreadOnly]
4337 #[name = "DayListData"]
4338 #[ivars = ListIvars]
4339 struct DayListData;
4340
4341 unsafe impl NSObjectProtocol for DayListData {}
4342 unsafe impl NSControlTextEditingDelegate for DayListData {}
4343
4344 impl DayListData {
4345 #[unsafe(method(respondsToSelector:))]
4349 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4350 if selector == objc2::sel!(tableView:heightOfRow:)
4351 && !self.ivars().automatic
4352 && !self.ivars().sections
4353 {
4354 false
4355 } else {
4356 unsafe { msg_send![super(self), respondsToSelector: selector] }
4357 }
4358 }
4359
4360 #[unsafe(method(listViewportChanged:))]
4361 fn list_viewport_changed(&self, notification: &NSNotification) {
4362 ffi_guard::contain((), || {
4363 let source = self.ivars().source.borrow().clone();
4364 if let Some(source) = source && let Some(report) = &source.first_visible
4365 && let Some(object) = notification.object()
4366 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4367 && let Some(document) = clip.documentView()
4368 && let Some(table) = document.downcast_ref::<NSTableView>() {
4369 let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4370 report(visible.location.min((source.len)().saturating_sub(1)));
4371 }
4372 });
4373 }
4374
4375 #[unsafe(method(activateRow:))]
4376 fn activate_row(&self, table: &NSTableView) {
4377 ffi_guard::contain((), || {
4378 let row = unsafe { table.selectedRow() };
4379 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4380 });
4381 }
4382 #[unsafe(method(doubleClickRow:))]
4383 fn double_click_row(&self, table: &NSTableView) {
4384 ffi_guard::contain((), || {
4385 let row = unsafe { table.clickedRow() };
4386 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4387 });
4388 }
4389 }
4390
4391 unsafe impl NSTableViewDataSource for DayListData {
4392 #[unsafe(method(numberOfRowsInTableView:))]
4393 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4394 ffi_guard::contain(0, || {
4398 self.ivars()
4399 .source
4400 .borrow()
4401 .as_ref()
4402 .map(|s| (s.len)() as isize)
4403 .unwrap_or(0)
4404 })
4405 }
4406
4407 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4413 fn pasteboard_writer_for_row(
4414 &self,
4415 _tv: &NSTableView,
4416 row: isize,
4417 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4418 let make = || {
4421 let reorderable = self
4423 .ivars()
4424 .source
4425 .borrow()
4426 .as_ref()
4427 .is_some_and(|s| s.reorder.is_some());
4428 if !reorderable || row < 0 || self.is_header(row) {
4430 return None;
4431 }
4432 let item = objc2_app_kit::NSPasteboardItem::new();
4433 unsafe {
4434 item.setString_forType(
4435 &NSString::from_str(&row.to_string()),
4436 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4437 );
4438 }
4439 Some(ProtocolObject::from_retained(item))
4440 };
4441 ffi_guard::contain(None, make)
4442 }
4443
4444 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4445 fn validate_drop(
4446 &self,
4447 tv: &NSTableView,
4448 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4449 row: isize,
4450 _op: objc2_app_kit::NSTableViewDropOperation,
4451 ) -> objc2_app_kit::NSDragOperation {
4452 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4454 let Some((from, len)) = self.drag_context(tv, info) else {
4455 return objc2_app_kit::NSDragOperation::None;
4456 };
4457 let ins = row.clamp(0, len as isize) as usize;
4460 let to = insertion_to_target(from, ins, len);
4461 let accepted = self.can_move(from, to);
4462 if accepted < 0 {
4463 return objc2_app_kit::NSDragOperation::None;
4464 }
4465 let accepted = (accepted as usize).min(len.saturating_sub(1));
4466 if accepted != to {
4467 unsafe {
4469 tv.setDropRow_dropOperation(
4470 target_to_insertion(from, accepted) as isize,
4471 objc2_app_kit::NSTableViewDropOperation::Above,
4472 );
4473 }
4474 }
4475 objc2_app_kit::NSDragOperation::Move
4476 })
4477 }
4478
4479 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4480 fn accept_drop(
4481 &self,
4482 tv: &NSTableView,
4483 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4484 row: isize,
4485 _op: objc2_app_kit::NSTableViewDropOperation,
4486 ) -> bool {
4487 let drop = || {
4489 let Some((from, len)) = self.drag_context(tv, info) else {
4490 return false;
4491 };
4492 let ins = row.clamp(0, len as isize) as usize;
4493 let to = insertion_to_target(from, ins, len);
4494 let accepted = self.can_move(from, to);
4495 if accepted < 0 {
4496 return false;
4497 }
4498 let accepted = (accepted as usize).min(len.saturating_sub(1));
4499 if accepted == from {
4500 return true; }
4502 let mv = self
4506 .ivars()
4507 .source
4508 .borrow()
4509 .as_ref()
4510 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4511 let Some(mv) = mv else { return false };
4512 mv(from, accepted);
4513 {
4516 let mut toks = self.ivars().tokens.borrow_mut();
4517 if from < toks.len() && accepted < toks.len() {
4518 let t = toks.remove(from);
4519 toks.insert(accepted, t);
4520 }
4521 }
4522 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4523 if let Some(scroll) = tv.enclosingScrollView() {
4524 post_settle_list_drop(ptr_of(&scroll));
4525 }
4526 true
4527 };
4528 ffi_guard::contain(false, drop)
4530 }
4531 }
4532
4533 unsafe impl NSTableViewDelegate for DayListData {
4534 #[unsafe(method(tableView:heightOfRow:))]
4539 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4540 ffi_guard::contain(44.0, || {
4541 let ivars = self.ivars();
4542 let header = self.is_header(row);
4543 if !header && !ivars.automatic {
4545 return unsafe { tv.rowHeight() };
4546 }
4547 let token = ivars
4548 .source
4549 .borrow()
4550 .as_ref()
4551 .filter(|s| row >= 0 && (row as usize) < (s.len)())
4552 .map(|s| (s.token_at)(row as usize));
4553 token
4554 .and_then(|t| ivars.heights.borrow().get(&t).copied())
4555 .unwrap_or_else(|| {
4556 if header {
4557 ivars.header_estimate.get()
4558 } else {
4559 ivars.estimate.get()
4560 }
4561 })
4562 })
4563 }
4564
4565 #[unsafe(method(tableView:isGroupRow:))]
4569 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4570 ffi_guard::contain(false, || self.is_header(row))
4571 }
4572
4573 #[unsafe(method(tableView:shouldSelectRow:))]
4575 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4576 ffi_guard::contain(true, || !self.is_header(row))
4577 }
4578
4579 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4580 fn view_for_row(
4581 &self,
4582 tv: &NSTableView,
4583 _col: Option<&NSTableColumn>,
4584 row: isize,
4585 ) -> Option<Retained<NSView>> {
4586 ffi_guard::contain(None, || {
4588 let mtm = self.mtm();
4589 let header = self.is_header(row);
4591 let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4592 let cell: Retained<NSView> =
4594 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4595 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4596 unsafe { v.setIdentifier(Some(&ident)) };
4597 v
4598 });
4599 let source = self.ivars().source.borrow().clone();
4603 if let Some(source) = source {
4604 let raw = Retained::as_ptr(&cell) as RawHandle;
4605 (source.bind_row)(row as usize, raw);
4606 if self.ivars().automatic || header {
4607 self.note_row_height(tv, &source, row, raw, header);
4608 }
4609 }
4610 Some(cell)
4611 })
4612 }
4613
4614 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4615 fn did_remove_row_view(
4616 &self,
4617 _tv: &NSTableView,
4618 row_view: &objc2_app_kit::NSTableRowView,
4619 _row: isize,
4620 ) {
4621 ffi_guard::contain((), || {
4627 let Some(cell) = row_view.subviews().iter().find(|sub| {
4628 sub.identifier()
4629 .map(|i| {
4630 let i = i.to_string();
4631 i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4632 })
4633 .unwrap_or(false)
4634 }) else {
4635 return;
4636 };
4637 let cell = Retained::into_raw(cell) as usize;
4640 let Some(this) = (unsafe {
4641 Retained::retain(self as *const DayListData as *mut DayListData)
4642 }) else {
4643 return;
4644 };
4645 let this = Retained::into_raw(this) as usize;
4646 <AppKit as Platform>::post(Box::new(move || {
4647 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4649 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4650 let (Some(this), Some(cell)) = (this, cell) else {
4651 return;
4652 };
4653 if cell.window().is_some() {
4654 return; }
4656 let recycle = this
4657 .ivars()
4658 .source
4659 .borrow()
4660 .as_ref()
4661 .map(|s| s.recycle.clone());
4662 if let Some(recycle) = recycle {
4663 recycle(Retained::as_ptr(&cell) as RawHandle);
4664 }
4665 }));
4666 })
4667 }
4668
4669 #[unsafe(method(tableViewSelectionDidChange:))]
4670 fn selection_did_change(&self, notification: &NSNotification) {
4671 ffi_guard::contain((), || {
4672 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4673 return;
4674 }
4675 let Some(obj) = (unsafe { notification.object() }) else {
4676 return;
4677 };
4678 let Ok(tv) = obj.downcast::<NSTableView>() else {
4679 return;
4680 };
4681 if self.ivars().multi.get() {
4682 let idx = unsafe { tv.selectedRowIndexes() };
4684 let mut rows = Vec::with_capacity(idx.count());
4685 let mut i = idx.firstIndex();
4686 while i != objc2_foundation::NSNotFound as usize {
4687 rows.push(i as i64);
4688 i = unsafe { idx.indexGreaterThanIndex(i) };
4689 }
4690 emit(self.ivars().node, Event::SelectionSet(rows));
4691 } else {
4692 let row = unsafe { tv.selectedRow() };
4693 if row >= 0 {
4694 emit(self.ivars().node, Event::SelectionChanged(row as i64));
4695 } else {
4696 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4704 }
4705 }
4706 })
4707 }
4708
4709 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4715 fn row_actions_for_row(
4716 &self,
4717 tv: &NSTableView,
4718 row: isize,
4719 edge: objc2_app_kit::NSTableRowActionEdge,
4720 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4721 ffi_guard::contain(NSArray::new(), || {
4723 let sw = self
4724 .ivars()
4725 .source
4726 .borrow()
4727 .as_ref()
4728 .and_then(|s| s.swipe.clone());
4729 let Some(sw) = sw else {
4730 return NSArray::new();
4731 };
4732 if row < 0 {
4733 return NSArray::new();
4734 }
4735 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4737 day_spec::SwipeEdge::Leading
4738 } else {
4739 day_spec::SwipeEdge::Trailing
4740 };
4741 let offer = (sw.actions_at)(row as usize, day_edge);
4742 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4743 .iter()
4744 .enumerate()
4745 .map(|(i, a)| {
4746 let style = if a.destructive {
4747 objc2_app_kit::NSTableViewRowActionStyle::Destructive
4748 } else {
4749 objc2_app_kit::NSTableViewRowActionStyle::Regular
4750 };
4751 let perform = sw.perform.clone();
4752 let table = tv.retain();
4755 let handler = block2::RcBlock::new(
4756 move |_action: std::ptr::NonNull<
4757 objc2_app_kit::NSTableViewRowAction,
4758 >,
4759 row: isize| {
4760 ffi_guard::contain((), || {
4761 perform(row as usize, day_edge, i);
4762 unsafe { table.setRowActionsVisible(false) };
4765 })
4766 },
4767 );
4768 let action =
4769 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4770 style,
4771 &NSString::from_str(&a.label),
4772 &handler,
4773 );
4774 if let Some(t) = a.tint {
4775 unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4776 }
4777 if let Some(sym) = a.symbol {
4781 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4782 &NSString::from_str(day_spec::sf_symbol_name(sym)),
4783 None,
4784 );
4785 if let Some(img) = img {
4786 unsafe { action.setImage(Some(&img)) };
4787 }
4788 }
4789 action
4790 })
4791 .collect();
4792 NSArray::from_retained_slice(&actions)
4793 })
4794 }
4795 }
4796);
4797
4798impl DayListData {
4799 fn new(
4800 mtm: MainThreadMarker,
4801 node: NodeId,
4802 selectable: bool,
4803 multi: bool,
4804 automatic: bool,
4805 sections: bool,
4806 ) -> Retained<Self> {
4807 let this = Self::alloc(mtm).set_ivars(ListIvars {
4808 node,
4809 source: RefCell::new(None),
4810 selectable: std::cell::Cell::new(selectable),
4811 multi: std::cell::Cell::new(multi),
4812 suppress: std::cell::Cell::new(false),
4813 tokens: RefCell::new(Vec::new()),
4814 automatic,
4815 sections,
4816 header_estimate: std::cell::Cell::new(28.0),
4817 heights: RefCell::new(std::collections::HashMap::new()),
4818 cell_tokens: RefCell::new(std::collections::HashMap::new()),
4819 estimate: std::cell::Cell::new(44.0),
4820 heights_pending: std::cell::Cell::new(false),
4821 });
4822 unsafe { msg_send![super(this), init] }
4823 }
4824
4825 fn note_row_height(
4829 &self,
4830 table: &NSTableView,
4831 source: &ListSource,
4832 row: isize,
4833 cell: RawHandle,
4834 header: bool,
4835 ) {
4836 let height = (source.cell_height)(cell);
4837 if height <= 0.0 || row < 0 {
4838 return;
4839 }
4840 let token = (source.token_at)(row as usize);
4841 self.ivars()
4842 .cell_tokens
4843 .borrow_mut()
4844 .insert(cell as usize, token);
4845 self.ivars().heights.borrow_mut().insert(token, height);
4846 if header {
4847 self.ivars().header_estimate.set(height);
4848 } else {
4849 self.ivars().estimate.set(height);
4850 }
4851 let drawn = unsafe { table.rectOfRow(row) }.size.height;
4852 if (drawn - height).abs() > 0.5 {
4853 self.post_row_heights(table);
4854 }
4855 }
4856
4857 fn is_header(&self, row: isize) -> bool {
4859 row >= 0
4860 && self
4861 .ivars()
4862 .source
4863 .borrow()
4864 .as_ref()
4865 .and_then(|s| s.is_header.clone())
4866 .is_some_and(|is_header| is_header(row as usize))
4867 }
4868
4869 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4872 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4873 if let Some(token) = token {
4874 self.ivars().heights.borrow_mut().insert(token, height);
4875 self.post_row_heights(table);
4876 }
4877 }
4878
4879 fn post_row_heights(&self, table: &NSTableView) {
4883 if self.ivars().heights_pending.replace(true) {
4884 return;
4885 }
4886 let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4889 return;
4890 };
4891 let this = Retained::into_raw(this) as usize;
4892 let table = Retained::into_raw(table.retain()) as usize;
4893 <AppKit as Platform>::post(Box::new(move || {
4894 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4896 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4897 let (Some(this), Some(table)) = (this, table) else {
4898 return;
4899 };
4900 this.ivars().heights_pending.set(false);
4901 ffi_guard::contain((), || this.apply_row_heights(&table));
4902 }));
4903 }
4904
4905 fn apply_row_heights(&self, table: &NSTableView) {
4906 let Some(source) = self.ivars().source.borrow().clone() else {
4907 return;
4908 };
4909 let count = unsafe { table.numberOfRows() }.max(0) as usize;
4910 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4911 let first = shown.location.saturating_sub(8);
4913 let last = (shown.location + shown.length + 8)
4914 .min(count)
4915 .min((source.len)());
4916 let changed = objc2_foundation::NSMutableIndexSet::new();
4917 {
4918 let heights = self.ivars().heights.borrow();
4919 for row in first..last {
4920 if let Some(&height) = heights.get(&(source.token_at)(row)) {
4921 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4922 if (drawn - height).abs() > 0.5 {
4923 unsafe { changed.addIndex(row) };
4924 }
4925 }
4926 }
4927 }
4928 if changed.count() == 0 {
4929 return;
4930 }
4931 NSAnimationContext::beginGrouping();
4933 NSAnimationContext::currentContext().setDuration(0.0);
4934 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4935 NSAnimationContext::endGrouping();
4936 }
4937
4938 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4950 let source = self.ivars().source.borrow();
4951 let source = source.as_ref()?;
4952 let n = (source.len)();
4953 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4954 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4955 if old.len() != n || n == 0 || old == new {
4956 return None;
4957 }
4958 let (mut so, mut sn) = (old.clone(), new.clone());
4959 so.sort_unstable();
4960 sn.sort_unstable();
4961 if so != sn {
4962 return None;
4963 }
4964 for i in 0..n {
4965 if old[i] != new[i]
4966 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4967 {
4968 return None;
4969 }
4970 }
4971 let mut work = old;
4972 let mut moves = Vec::new();
4973 for i in 0..n {
4974 if work[i] == new[i] {
4975 continue;
4976 }
4977 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4978 let t = work.remove(j);
4979 work.insert(i, t);
4980 moves.push((j, i));
4981 }
4982 Some(moves)
4983 }
4984
4985 fn drag_context(
4989 &self,
4990 tv: &NSTableView,
4991 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4992 ) -> Option<(usize, usize)> {
4993 let src = unsafe { info.draggingSource() }?;
4994 if Retained::as_ptr(&src) as *const std::ffi::c_void
4995 != tv as *const NSTableView as *const std::ffi::c_void
4996 {
4997 return None;
4998 }
4999 let pb = unsafe { info.draggingPasteboard() };
5000 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5001 .to_string()
5002 .parse::<usize>()
5003 .ok()?;
5004 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5005 (from < len).then_some((from, len))
5006 }
5007
5008 fn can_move(&self, from: usize, to: usize) -> i64 {
5010 self.ivars()
5011 .source
5012 .borrow()
5013 .as_ref()
5014 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5015 .unwrap_or(-1)
5016 }
5017}
5018
5019const DAY_ROW_CELL: &str = "day.cell";
5021const DAY_HEADER_CELL: &str = "day.header";
5022
5023const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5025
5026fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5029 let to = if ins > from { ins - 1 } else { ins };
5030 to.min(len.saturating_sub(1))
5031}
5032
5033fn target_to_insertion(from: usize, to: usize) -> usize {
5035 if to > from { to + 1 } else { to }
5036}
5037
5038type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5040
5041fn list_entry(key: usize) -> Option<ListEntry> {
5048 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5049}
5050
5051struct TreeIvars {
5056 node: NodeId,
5057 source: RefCell<Option<TreeSource>>,
5059 selectable: std::cell::Cell<bool>,
5060 suppress: std::cell::Cell<bool>,
5062 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5066}
5067
5068define_class!(
5069 #[unsafe(super(NSObject))]
5070 #[thread_kind = MainThreadOnly]
5071 #[name = "DayTreeData"]
5072 #[ivars = TreeIvars]
5073 struct DayTreeData;
5074
5075 unsafe impl NSObjectProtocol for DayTreeData {}
5076
5077 unsafe impl NSOutlineViewDataSource for DayTreeData {
5078 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5079 fn number_of_children(
5080 &self,
5081 _ov: &objc2_app_kit::NSOutlineView,
5082 item: Option<&objc2::runtime::AnyObject>,
5083 ) -> isize {
5084 ffi_guard::contain(0, || {
5088 let parent = item.and_then(Self::token_of_item);
5089 if item.is_some() && parent.is_none() {
5090 return 0; }
5092 self.ivars()
5093 .source
5094 .borrow()
5095 .as_ref()
5096 .map(|s| (s.children_len)(parent) as isize)
5097 .unwrap_or(0)
5098 })
5099 }
5100
5101 #[unsafe(method_id(outlineView:child:ofItem:))]
5102 fn child_of_item(
5103 &self,
5104 _ov: &objc2_app_kit::NSOutlineView,
5105 index: isize,
5106 item: Option<&objc2::runtime::AnyObject>,
5107 ) -> Retained<objc2::runtime::AnyObject> {
5108 let token = ffi_guard::contain(0, || {
5112 let parent = item.and_then(Self::token_of_item);
5113 self.ivars()
5114 .source
5115 .borrow()
5116 .as_ref()
5117 .map(|s| (s.child_token)(parent, index.max(0) as usize))
5118 .unwrap_or(0)
5119 });
5120 let ns = self.intern(token);
5121 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5122 }
5123
5124 #[unsafe(method(outlineView:isItemExpandable:))]
5125 fn is_expandable(
5126 &self,
5127 _ov: &objc2_app_kit::NSOutlineView,
5128 item: &objc2::runtime::AnyObject,
5129 ) -> bool {
5130 ffi_guard::contain(false, || {
5131 let Some(token) = Self::token_of_item(item) else {
5132 return false;
5133 };
5134 self.ivars()
5135 .source
5136 .borrow()
5137 .as_ref()
5138 .map(|s| (s.expandable)(token))
5139 .unwrap_or(false)
5140 })
5141 }
5142
5143 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5149 fn pasteboard_writer_for_item(
5150 &self,
5151 _ov: &objc2_app_kit::NSOutlineView,
5152 item: &objc2::runtime::AnyObject,
5153 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5154 let make = || {
5155 let movable = self
5156 .ivars()
5157 .source
5158 .borrow()
5159 .as_ref()
5160 .is_some_and(|s| s.moves.is_some());
5161 let token = Self::token_of_item(item)?;
5162 if !movable {
5163 return None;
5164 }
5165 let pbitem = objc2_app_kit::NSPasteboardItem::new();
5166 unsafe {
5167 pbitem.setString_forType(
5168 &NSString::from_str(&token.to_string()),
5169 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5170 );
5171 }
5172 Some(ProtocolObject::from_retained(pbitem))
5173 };
5174 ffi_guard::contain(None, make)
5175 }
5176
5177 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5178 fn validate_drop(
5179 &self,
5180 ov: &objc2_app_kit::NSOutlineView,
5181 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5182 item: Option<&objc2::runtime::AnyObject>,
5183 child_index: isize,
5184 ) -> objc2_app_kit::NSDragOperation {
5185 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5186 match self.drop_proposal(ov, info, item, child_index) {
5187 Some((token, parent, index)) if self.can_move(token, parent, index) => {
5188 objc2_app_kit::NSDragOperation::Move
5189 }
5190 _ => objc2_app_kit::NSDragOperation::None,
5191 }
5192 })
5193 }
5194
5195 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5196 fn accept_drop(
5197 &self,
5198 ov: &objc2_app_kit::NSOutlineView,
5199 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5200 item: Option<&objc2::runtime::AnyObject>,
5201 child_index: isize,
5202 ) -> bool {
5203 let drop = || {
5204 let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5205 else {
5206 return false;
5207 };
5208 if !self.can_move(token, parent, index) {
5209 return false;
5210 }
5211 let mv = self
5214 .ivars()
5215 .source
5216 .borrow()
5217 .as_ref()
5218 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5219 let Some(mv) = mv else { return false };
5220 mv(token, parent, index);
5221 true
5222 };
5223 ffi_guard::contain(false, drop)
5224 }
5225 }
5226
5227 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5228
5229 unsafe impl NSOutlineViewDelegate for DayTreeData {
5230 #[unsafe(method(outlineView:isGroupItem:))]
5231 fn is_group_item(
5232 &self,
5233 _ov: &objc2_app_kit::NSOutlineView,
5234 item: &objc2::runtime::AnyObject,
5235 ) -> bool {
5236 Self::token_of_item(item).is_some_and(|t| {
5237 self.ivars()
5238 .source
5239 .borrow()
5240 .as_ref()
5241 .is_some_and(|s| (s.section_header)(t))
5242 })
5243 }
5244 #[unsafe(method(outlineView:shouldSelectItem:))]
5245 fn should_select_item(
5246 &self,
5247 _ov: &objc2_app_kit::NSOutlineView,
5248 item: &objc2::runtime::AnyObject,
5249 ) -> bool {
5250 Self::token_of_item(item).is_some_and(|t| {
5251 self.ivars()
5252 .source
5253 .borrow()
5254 .as_ref()
5255 .is_some_and(|s| !(s.section_header)(t))
5256 })
5257 }
5258
5259 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5260 fn view_for_item(
5261 &self,
5262 ov: &objc2_app_kit::NSOutlineView,
5263 _col: Option<&NSTableColumn>,
5264 item: &objc2::runtime::AnyObject,
5265 ) -> Option<Retained<NSView>> {
5266 ffi_guard::contain(None, || {
5268 let mtm = self.mtm();
5269 let token = Self::token_of_item(item)?;
5270 let ident = NSString::from_str("day.tree.cell");
5271 let cell: Retained<NSView> =
5275 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5276 let v: Retained<NSView> =
5277 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5278 unsafe { v.setIdentifier(Some(&ident)) };
5279 v
5280 });
5281 if let Some(source) = self.ivars().source.borrow().as_ref() {
5282 let raw = Retained::as_ptr(&cell) as RawHandle;
5283 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5284 unsafe {
5285 cell.setTextField(None);
5286 }
5287 }
5288 (source.bind_row)(token, raw);
5289 if (source.section_header)(token) {
5292 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5293 for child in unsafe { view.subviews() }.iter() {
5294 if let Ok(label) = child.clone().downcast::<NSTextField>() {
5295 return Some(label);
5296 }
5297 if let Some(label) = label_in(&child) {
5298 return Some(label);
5299 }
5300 }
5301 None
5302 }
5303 if let Some(label) = label_in(&cell) {
5304 let cell = cell.downcast_ref::<DayTreeCell>()?;
5305 unsafe {
5306 cell.setTextField(Some(&label));
5307 }
5308 }
5309 }
5310 }
5311 Some(cell)
5312 })
5313 }
5314
5315 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5316 fn type_select_string(
5317 &self,
5318 _ov: &objc2_app_kit::NSOutlineView,
5319 _col: Option<&NSTableColumn>,
5320 item: &objc2::runtime::AnyObject,
5321 ) -> Option<Retained<NSString>> {
5322 ffi_guard::contain(None, || {
5323 let token = Self::token_of_item(item)?;
5324 let text = self
5325 .ivars()
5326 .source
5327 .borrow()
5328 .as_ref()
5329 .map(|s| (s.type_select_text)(token))
5330 .unwrap_or_default();
5331 (!text.is_empty()).then(|| NSString::from_str(&text))
5333 })
5334 }
5335
5336 #[unsafe(method_id(outlineView:rowViewForItem:))]
5337 fn row_view_for_item(
5338 &self,
5339 ov: &objc2_app_kit::NSOutlineView,
5340 _item: &objc2::runtime::AnyObject,
5341 ) -> Retained<objc2_app_kit::NSTableRowView> {
5342 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5343 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5345 } else {
5346 let rv: Retained<DayTreeRowView> =
5348 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5349 Retained::into_super(rv)
5350 }
5351 }
5352
5353 #[unsafe(method(outlineViewSelectionDidChange:))]
5354 fn selection_did_change(&self, notification: &NSNotification) {
5355 ffi_guard::contain((), || {
5356 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5357 return;
5358 }
5359 let Some(obj) = (unsafe { notification.object() }) else {
5360 return;
5361 };
5362 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5363 return;
5364 };
5365 let idx = unsafe { ov.selectedRowIndexes() };
5367 let mut tokens = Vec::with_capacity(idx.count());
5368 let mut i = idx.firstIndex();
5369 while i != objc2_foundation::NSNotFound as usize {
5370 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5371 && let Some(tok) = Self::token_of_item(&item)
5372 {
5373 tokens.push(tok);
5374 }
5375 i = unsafe { idx.indexGreaterThanIndex(i) };
5376 }
5377 emit(self.ivars().node, Event::TreeSelection(tokens));
5378 })
5379 }
5380
5381 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5382 fn did_remove_row_view(
5383 &self,
5384 ov: &objc2_app_kit::NSOutlineView,
5385 row_view: &objc2_app_kit::NSTableRowView,
5386 _row: isize,
5387 ) {
5388 ffi_guard::contain((), || {
5394 let mut cell_ptr: Option<usize> = None;
5395 for sub in row_view.subviews().iter() {
5396 let is_cell = sub
5397 .identifier()
5398 .map(|i| i.to_string() == "day.tree.cell")
5399 .unwrap_or(false);
5400 if is_cell {
5401 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5402 }
5403 }
5404 let Some(cell) = cell_ptr else { return };
5405 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5406 return;
5407 };
5408 let key = Retained::as_ptr(&scroll) as usize;
5409 let retained =
5413 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5414 as usize;
5415 <AppKit as Platform>::post(Box::new(move || {
5416 let cell_view: Retained<NSView> =
5419 match unsafe { Retained::from_raw(retained as *mut NSView) } {
5420 Some(v) => v,
5421 None => return,
5422 };
5423 let recycle = tree_entry(key).and_then(|(_, data)| {
5424 data.ivars()
5425 .source
5426 .borrow()
5427 .as_ref()
5428 .map(|s| s.recycle.clone())
5429 });
5430 let Some(recycle) = recycle else { return };
5431 if cell_view.window().is_some() {
5432 return; }
5434 recycle(cell as RawHandle);
5435 }));
5436 })
5437 }
5438
5439 #[unsafe(method(outlineViewItemDidExpand:))]
5440 fn item_did_expand(&self, notification: &NSNotification) {
5441 self.report_disclosure(notification, true);
5442 }
5443
5444 #[unsafe(method(outlineViewItemDidCollapse:))]
5445 fn item_did_collapse(&self, notification: &NSNotification) {
5446 self.report_disclosure(notification, false);
5447 }
5448 }
5449);
5450
5451impl DayTreeData {
5452 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5453 let this = Self::alloc(mtm).set_ivars(TreeIvars {
5454 node,
5455 source: RefCell::new(None),
5456 selectable: std::cell::Cell::new(selectable),
5457 suppress: std::cell::Cell::new(false),
5458 items: RefCell::new(HashMap::new()),
5459 });
5460 unsafe { msg_send![super(this), init] }
5461 }
5462
5463 fn intern(&self, token: u64) -> Retained<NSNumber> {
5465 self.ivars()
5466 .items
5467 .borrow_mut()
5468 .entry(token)
5469 .or_insert_with(|| NSNumber::new_u64(token))
5470 .clone()
5471 }
5472
5473 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5474 item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5475 }
5476
5477 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5480 ffi_guard::contain((), || {
5481 if self.ivars().suppress.get() {
5482 return;
5483 }
5484 let token = unsafe { notification.userInfo() }
5485 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5486 .and_then(|item| Self::token_of_item(&item));
5487 if let Some(token) = token {
5488 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5489 }
5490 })
5491 }
5492
5493 fn drop_proposal(
5497 &self,
5498 ov: &objc2_app_kit::NSOutlineView,
5499 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5500 item: Option<&objc2::runtime::AnyObject>,
5501 child_index: isize,
5502 ) -> Option<(u64, Option<u64>, Option<usize>)> {
5503 let src = unsafe { info.draggingSource() }?;
5504 if Retained::as_ptr(&src) as *const std::ffi::c_void
5505 != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5506 {
5507 return None;
5508 }
5509 let pb = unsafe { info.draggingPasteboard() };
5510 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5511 .to_string()
5512 .parse::<u64>()
5513 .ok()?;
5514 let parent = match item {
5515 Some(i) => Some(Self::token_of_item(i)?), None => None,
5517 };
5518 let index = (child_index >= 0).then_some(child_index as usize);
5519 Some((token, parent, index))
5520 }
5521
5522 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5524 self.ivars()
5525 .source
5526 .borrow()
5527 .as_ref()
5528 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5529 .map(|v| v == MoveVerdict::Allow)
5530 .unwrap_or(false)
5531 }
5532}
5533
5534define_class!(
5540 #[unsafe(super(objc2_app_kit::NSOutlineView))]
5541 #[thread_kind = MainThreadOnly]
5542 #[name = "DayOutlineView"]
5543 struct DayOutlineView;
5544
5545 impl DayOutlineView {
5546 #[unsafe(method(layout))]
5547 fn layout(&self) {
5548 sync_tree_width(self);
5549 let _: () = unsafe { msg_send![super(self), layout] };
5550 }
5551
5552 #[unsafe(method_id(menuForEvent:))]
5555 fn menu_for_event(
5556 &self,
5557 event: &objc2_app_kit::NSEvent,
5558 ) -> Option<Retained<NSMenu>> {
5559 ffi_guard::contain(None, || {
5560 let scroll = unsafe { self.enclosingScrollView() }?;
5561 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5562 let row_menu = data
5563 .ivars()
5564 .source
5565 .borrow()
5566 .as_ref()
5567 .and_then(|s| s.row_menu.clone())?;
5568 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5569 let row = unsafe { self.rowAtPoint(p) };
5570 if row < 0 {
5571 return None;
5572 }
5573 let token =
5574 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5575 let items = row_menu(token);
5576 if items.is_empty() {
5577 return None;
5578 }
5579 Some(build_ns_menu(self.mtm(), "", &items))
5580 })
5581 }
5582 }
5583);
5584
5585define_class!(
5592 #[unsafe(super(objc2_app_kit::NSTableRowView))]
5593 #[thread_kind = MainThreadOnly]
5594 #[name = "DayTreeRowView"]
5595 struct DayTreeRowView;
5596
5597 impl DayTreeRowView {
5598 #[unsafe(method(drawSelectionInRect:))]
5599 fn draw_selection_in_rect(&self, _dirty: NSRect) {
5600 if !unsafe { self.isSelected() } {
5601 return;
5602 }
5603 let color = if unsafe { self.isEmphasized() } {
5604 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5605 } else {
5606 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5607 };
5608 let b = self.bounds();
5609 let pill = NSRect::new(
5610 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5611 NSSize::new(
5612 (b.size.width - 10.0).max(0.0),
5613 (b.size.height - 2.0).max(0.0),
5614 ),
5615 );
5616 unsafe {
5617 color.setFill();
5618 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5619 pill, 5.0, 5.0,
5620 )
5621 .fill();
5622 }
5623 }
5624 }
5625);
5626
5627define_class!(
5631 #[unsafe(super(objc2_app_kit::NSTableCellView))]
5632 #[thread_kind = MainThreadOnly]
5633 #[name = "DayTreeCell"]
5634 struct DayTreeCell;
5635
5636 impl DayTreeCell {
5637 #[unsafe(method(isFlipped))]
5638 fn is_flipped(&self) -> bool {
5639 true
5640 }
5641
5642 #[unsafe(method(layout))]
5643 fn layout(&self) {
5644 let _: () = unsafe { msg_send![super(self), layout] };
5645 ffi_guard::contain((), || {
5646 let width = self.bounds().size.width;
5647 if width <= 0.0 {
5648 return;
5649 }
5650 let mut cur = unsafe { self.superview() };
5654 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5655 while let Some(v) = cur {
5656 cur = unsafe { v.superview() };
5657 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5658 outline = Some(ov);
5659 break;
5660 }
5661 }
5662 let Some(ov) = outline else { return };
5663 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5664 return;
5665 };
5666 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5667 .and_then(|(_, data)| {
5668 data.ivars()
5669 .source
5670 .borrow()
5671 .as_ref()
5672 .map(|s| s.layout_cell_size.clone())
5673 });
5674 if let Some(f) = f {
5675 f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5676 }
5677 })
5678 }
5679 }
5680);
5681
5682impl DayTreeCell {
5683 fn new(mtm: MainThreadMarker) -> Retained<Self> {
5684 unsafe { msg_send![Self::alloc(mtm), init] }
5685 }
5686}
5687
5688const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5690
5691type TreeEntry = (
5693 Retained<objc2_app_kit::NSOutlineView>,
5694 Retained<DayTreeData>,
5695);
5696
5697fn tree_entry(key: usize) -> Option<TreeEntry> {
5700 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5701}
5702
5703fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5707 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5708 return;
5709 };
5710 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5711 let f = outline.frame();
5712 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5713 unsafe {
5714 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5715 outline.sizeLastColumnToFit();
5716 }
5717 }
5718}
5719
5720fn post_realize_visible_tree_rows(key: usize) {
5723 <AppKit as Platform>::post(Box::new(move || {
5724 if let Some((outline, _)) = tree_entry(key) {
5725 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5726 for row in range.location..range.location + range.length {
5727 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5728 }
5729 }
5730 day_core::pump_events();
5731 }));
5732}
5733
5734type NavMenuEntry = (
5736 Retained<objc2_app_kit::NSOutlineView>,
5737 Retained<DayNavMenuData>,
5738);
5739
5740fn ns_rect(r: day_spec::Rect) -> NSRect {
5741 NSRect::new(
5742 NSPoint::new(r.origin.x, r.origin.y),
5743 NSSize::new(r.size.width, r.size.height),
5744 )
5745}
5746
5747fn draw_op(op: &DrawOp) {
5748 unsafe {
5749 match op {
5750 DrawOp::Stamp(st) => {
5756 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5757 for p in &st.at {
5758 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5759 unsafe { batch.appendBezierPath(©) };
5760 }
5761 }
5762 let color = match &st.paint {
5763 day_spec::Paint::Solid(c) => *c,
5764 _ => day_spec::Color::WHITE,
5767 };
5768 match &st.stroke {
5769 None => {
5770 nscolor(color).setFill();
5771 unsafe { batch.fill() };
5772 }
5773 Some(style) => {
5774 nscolor(color).setStroke();
5775 apply_stroke_style(&batch, style);
5776 unsafe { batch.stroke() };
5777 }
5778 }
5779 }
5780 DrawOp::Fill(shape, paint) => match paint {
5781 day_spec::Paint::Solid(color) => {
5782 nscolor(*color).setFill();
5783 if let Some(p) = bezier(shape) {
5784 p.fill();
5785 }
5786 }
5787 day_spec::Paint::Linear(g) => {
5788 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5791 let b = shape.bounds();
5792 let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5793 NSGraphicsContext::saveGraphicsState_class();
5794 p.addClip();
5795 grad.drawFromPoint_toPoint_options(
5796 NSPoint::new(s.x, s.y),
5797 NSPoint::new(e.x, e.y),
5798 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5799 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5800 );
5801 NSGraphicsContext::restoreGraphicsState_class();
5802 }
5803 }
5804 day_spec::Paint::Radial(g) => {
5805 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5808 let b = shape.bounds();
5809 NSGraphicsContext::saveGraphicsState_class();
5810 p.addClip();
5811 concat_unit_to_bounds(b);
5812 let c = NSPoint::new(g.center.x, g.center.y);
5813 grad.drawFromCenter_radius_toCenter_radius_options(
5814 c,
5815 0.0,
5816 c,
5817 g.radius,
5818 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5819 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5820 );
5821 NSGraphicsContext::restoreGraphicsState_class();
5822 }
5823 }
5824 },
5825 DrawOp::Stroke(shape, paint, style) => {
5826 if let Some(p) = bezier(shape) {
5827 apply_stroke_style(&p, style);
5828 match paint {
5829 day_spec::Paint::Solid(color) => {
5830 nscolor(*color).setStroke();
5831 p.stroke();
5832 }
5833 _ => {
5839 let Some(ctx) = NSGraphicsContext::currentContext() else {
5840 return;
5841 };
5842 let cg = ctx.CGContext();
5843 NSGraphicsContext::saveGraphicsState_class();
5844 objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5845 objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5846 &cg,
5847 ));
5848 objc2_core_graphics::CGContext::clip(Some(&cg));
5849 draw_gradient_in(paint, shape.bounds());
5850 NSGraphicsContext::restoreGraphicsState_class();
5851 }
5852 }
5853 }
5854 }
5855 DrawOp::Clip(shape) => {
5856 if let Some(p) = bezier(shape) {
5858 p.addClip();
5859 }
5860 }
5861 DrawOp::Text {
5862 text,
5863 at,
5864 size,
5865 color,
5866 anchor,
5867 font,
5868 } => {
5869 let font = canvas_nsfont(*size, font);
5870 let attrs = canvas_text_attrs(&font, *color);
5871 let ns = NSString::from_str(text);
5872 let mut origin = NSPoint::new(at.x, at.y);
5873 if *anchor != day_spec::TextAnchor::LEADING {
5878 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5879 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5880 origin.x += dx;
5881 origin.y += dy;
5882 }
5883 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5884 }
5885 DrawOp::Image {
5889 image,
5890 rect,
5891 opacity,
5892 } => {
5893 let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5894 if let Some(img) = img {
5895 let dest = NSRect::new(
5896 NSPoint::new(rect.origin.x, rect.origin.y),
5897 NSSize::new(rect.size.width, rect.size.height),
5898 );
5899 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5903 dest,
5904 NSRect::ZERO,
5905 objc2_app_kit::NSCompositingOperation::SourceOver,
5906 *opacity,
5907 true,
5908 None,
5909 );
5910 }
5911 }
5912 DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5913 DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5914 DrawOp::Concat(m) => {
5915 let t = NSAffineTransform::new();
5916 t.setTransformStruct(NSAffineTransformStruct {
5917 m11: m.a,
5918 m12: m.b,
5919 m21: m.c,
5920 m22: m.d,
5921 tX: m.tx,
5922 tY: m.ty,
5923 });
5924 t.concat();
5925 }
5926 }
5927 }
5928}
5929
5930fn nsgradient(
5932 stops: &[(f64, day_spec::Color)],
5933) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5934 if stops.is_empty() {
5935 return None;
5936 }
5937 let colors = objc2_foundation::NSArray::from_retained_slice(
5938 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5939 );
5940 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5941 unsafe {
5942 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5943 objc2_app_kit::NSGradient::alloc(),
5944 &colors,
5945 locations.as_ptr(),
5946 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5947 )
5948 }
5949}
5950
5951fn concat_unit_to_bounds(b: day_spec::Rect) {
5954 let t = NSAffineTransform::new();
5955 t.setTransformStruct(NSAffineTransformStruct {
5956 m11: b.size.width,
5957 m12: 0.0,
5958 m21: 0.0,
5959 m22: b.size.height,
5960 tX: b.origin.x,
5961 tY: b.origin.y,
5962 });
5963 unsafe { t.concat() };
5964}
5965
5966fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5972 use day_spec::{LineCap, LineJoin};
5973 unsafe {
5974 p.setLineWidth(style.width);
5975 p.setLineCapStyle(match style.cap {
5976 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5977 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5978 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5979 });
5980 if style.is_plain() {
5981 return;
5982 }
5983 p.setLineJoinStyle(match style.join {
5984 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5985 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5986 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5987 });
5988 p.setMiterLimit(style.miter_limit);
5989 if !style.dash.is_empty() {
5990 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5991 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5992 }
5993 }
5994}
5995
5996fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6000 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6001 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6002 match paint {
6003 day_spec::Paint::Linear(g) => {
6004 if let Some(grad) = nsgradient(&g.stops) {
6005 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6006 unsafe {
6007 grad.drawFromPoint_toPoint_options(
6008 NSPoint::new(s.x, s.y),
6009 NSPoint::new(e.x, e.y),
6010 opts,
6011 )
6012 };
6013 }
6014 }
6015 day_spec::Paint::Radial(g) => {
6016 if let Some(grad) = nsgradient(&g.stops) {
6017 NSGraphicsContext::saveGraphicsState_class();
6018 concat_unit_to_bounds(bounds);
6019 let c = NSPoint::new(g.center.x, g.center.y);
6020 unsafe {
6021 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
6022 };
6023 NSGraphicsContext::restoreGraphicsState_class();
6024 }
6025 }
6026 day_spec::Paint::Solid(_) => {}
6027 }
6028}
6029
6030fn apply_button_content(
6031 btn: &NSButton,
6032 title: &str,
6033 icon: Option<&day_spec::Icon>,
6034 icon_only: bool,
6035) {
6036 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6037 if let Some(image) = &image {
6038 let size = image.size();
6039 let longest = size.width.max(size.height);
6040 if longest > 0.0 {
6041 image.setSize(objc2_foundation::NSSize::new(
6042 size.width * 20.0 / longest,
6043 size.height * 20.0 / longest,
6044 ));
6045 }
6046 }
6047 let style = BUTTON_STYLES
6048 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6049 .unwrap_or_default();
6050 BUTTON_IMAGES.with(|images| {
6051 images.remove(ptr_of(btn));
6052 if let Some(image) = &image {
6053 images.insert(ptr_of(btn), image.clone());
6054 }
6055 });
6056 set_button_title(btn, title, style);
6057 unsafe {
6060 btn.setImagePosition(if image.is_none() {
6061 objc2_app_kit::NSCellImagePosition::NoImage
6062 } else if icon_only {
6063 objc2_app_kit::NSCellImagePosition::ImageOnly
6064 } else {
6065 objc2_app_kit::NSCellImagePosition::ImageLeading
6066 });
6067 }
6068 set_button_image(btn, style);
6069 unsafe {
6070 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6073 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6074 }
6075 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6076 btn.setToolTip(tooltip.as_deref());
6077 }
6078}
6079
6080fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6084 use day_spec::props::ButtonStyleSpec as S;
6085 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6086 let image = image.map(|source| {
6087 let S::Tinted(fill) = style else {
6088 return source;
6089 };
6090 let size = source.size();
6091 let ink = nscolor(S::on_tint(fill));
6092 let draw = block2::RcBlock::new(move |rect: NSRect| {
6093 source.drawInRect_fromRect_operation_fraction(
6094 rect,
6095 NSRect::ZERO,
6096 objc2_app_kit::NSCompositingOperation::SourceOver,
6097 1.0,
6098 );
6099 unsafe {
6100 ink.setFill();
6101 objc2_app_kit::NSRectFillUsingOperation(
6102 rect,
6103 objc2_app_kit::NSCompositingOperation::SourceIn,
6104 );
6105 }
6106 objc2::runtime::Bool::YES
6107 });
6108 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6109 });
6110 unsafe {
6111 let position = btn.imagePosition();
6112 let image = image.map(|source| {
6117 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6120 return source;
6121 }
6122 let size = source.size();
6123 let template = source.isTemplate();
6124 let padded = NSSize::new(size.width + 8.0, size.height);
6125 let draw = block2::RcBlock::new(move |_rect: NSRect| {
6126 source.drawInRect_fromRect_operation_fraction(
6127 NSRect::new(NSPoint::new(0.0, 0.0), size),
6128 NSRect::ZERO,
6129 objc2_app_kit::NSCompositingOperation::SourceOver,
6130 1.0,
6131 );
6132 objc2::runtime::Bool::YES
6133 });
6134 let out =
6135 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6136 out.setTemplate(template);
6137 out
6138 });
6139 btn.setImage(image.as_deref());
6140 btn.setImagePosition(position);
6141 btn.setImageHugsTitle(true);
6142 }
6143}
6144
6145fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6151 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6152 unsafe {
6153 if on {
6154 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6155 }
6156 btn.setState(if on {
6157 NSControlStateValueOn
6158 } else {
6159 NSControlStateValueOff
6160 });
6161 }
6162}
6163
6164const TINT_CORNER_RADIUS: f64 = 6.0;
6167
6168fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6178 use day_spec::props::ButtonStyleSpec as S;
6179 let title = unsafe { btn.title() }.to_string();
6180 unsafe {
6181 btn.setKeyEquivalent(&NSString::from_str(""));
6183 btn.setBezelColor(None);
6184 btn.setBordered(!matches!(style, S::Plain));
6185 match style {
6186 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6187 S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6188 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6191 }
6192 btn.setWantsLayer(true);
6193 if let Some(layer) = btn.layer() {
6194 match style {
6195 S::Tinted(c) => {
6196 layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6197 layer.setCornerRadius(TINT_CORNER_RADIUS);
6198 }
6199 _ => layer.setBackgroundColor(None),
6200 }
6201 }
6202 }
6203 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6204 let ink = match style {
6205 S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6206 _ => None,
6207 };
6208 unsafe {
6209 btn.setContentTintColor(ink.as_deref());
6210 }
6211 set_button_title(btn, &title, style);
6212 set_button_image(btn, style);
6213}
6214
6215fn set_button_title(
6225 btn: &objc2_app_kit::NSButton,
6226 title: &str,
6227 style: day_spec::props::ButtonStyleSpec,
6228) {
6229 use day_spec::props::ButtonStyleSpec as S;
6230 let position = unsafe { btn.imagePosition() };
6233 let S::Tinted(fill) = style else {
6234 unsafe {
6236 btn.setTitle(&NSString::from_str(title));
6237 btn.setImagePosition(position);
6238 }
6239 return;
6240 };
6241 unsafe {
6242 let col = nscolor(S::on_tint(fill));
6243 let font = btn
6244 .font()
6245 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6246 let para = objc2_app_kit::NSMutableParagraphStyle::new();
6249 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6250 let keys: [&NSString; 3] = [
6251 objc2_app_kit::NSFontAttributeName,
6252 objc2_app_kit::NSForegroundColorAttributeName,
6253 objc2_app_kit::NSParagraphStyleAttributeName,
6254 ];
6255 let objs: [&objc2::runtime::AnyObject; 3] = [
6256 font.as_ref() as &objc2::runtime::AnyObject,
6257 col.as_ref() as &objc2::runtime::AnyObject,
6258 para.as_ref() as &objc2::runtime::AnyObject,
6259 ];
6260 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6261 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6262 objc2_foundation::NSAttributedString::alloc(),
6263 &NSString::from_str(title),
6264 Some(&attrs),
6265 );
6266 btn.setAttributedTitle(&s);
6267 btn.setImagePosition(position);
6268 }
6269}
6270
6271define_class!(
6274 #[unsafe(super(objc2_app_kit::NSImageView))]
6275 #[thread_kind = MainThreadOnly]
6276 #[name = "DayFillImageView"]
6277 struct FillImageView;
6278
6279 impl FillImageView {
6280 #[unsafe(method(drawRect:))]
6281 fn draw_rect(&self, dirty: NSRect) {
6282 let bounds = self.bounds();
6283 let image = unsafe { self.image() };
6284 let Some(size) = image.map(|image| image.size()).filter(|size| {
6285 size.width > 0.0 && size.height > 0.0
6286 && bounds.size.width > 0.0 && bounds.size.height > 0.0
6287 }) else {
6288 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6289 return;
6290 };
6291 let x = bounds.size.width / size.width;
6292 let y = bounds.size.height / size.height;
6293 let scale = x.max(y) / x.min(y);
6294 let cx = bounds.origin.x + bounds.size.width / 2.0;
6295 let cy = bounds.origin.y + bounds.size.height / 2.0;
6296 NSGraphicsContext::saveGraphicsState_class();
6297 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6298 let transform = NSAffineTransform::transform();
6299 transform.translateXBy_yBy(cx, cy);
6300 transform.scaleBy(scale);
6301 transform.translateXBy_yBy(-cx, -cy);
6302 transform.concat();
6303 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6304 NSGraphicsContext::restoreGraphicsState_class();
6305 }
6306
6307 #[unsafe(method(setFrameSize:))]
6308 fn set_frame_size(&self, size: NSSize) {
6309 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6310 NSView::setNeedsDisplay(self, true);
6311 }
6312 }
6313);
6314
6315fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6316 use day_spec::Shape;
6317 use objc2_app_kit::NSBezierPath;
6318 unsafe {
6319 Some(match shape {
6320 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6321 Shape::RoundedRect(r, rad) => {
6322 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6323 }
6324 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6325 Shape::Arc {
6326 rect,
6327 start_deg,
6328 sweep_deg,
6329 } => {
6330 let p = NSBezierPath::new();
6331 let center = NSPoint::new(
6332 rect.origin.x + rect.size.width / 2.0,
6333 rect.origin.y + rect.size.height / 2.0,
6334 );
6335 let radius = rect.size.width.min(rect.size.height) / 2.0;
6336 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6338 center,
6339 radius,
6340 *start_deg,
6341 *start_deg + *sweep_deg,
6342 );
6343 p
6344 }
6345 Shape::Line(a, b) => {
6346 let p = NSBezierPath::new();
6347 p.moveToPoint(NSPoint::new(a.x, a.y));
6348 p.lineToPoint(NSPoint::new(b.x, b.y));
6349 p
6350 }
6351 Shape::Polygon(pts) => {
6352 if pts.len() < 2 {
6353 return None;
6354 }
6355 let p = NSBezierPath::new();
6356 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6357 for pt in &pts[1..] {
6358 p.lineToPoint(NSPoint::new(pt.x, pt.y));
6359 }
6360 p.closePath();
6361 p
6362 }
6363 Shape::Path(path) => {
6364 use day_spec::PathSeg;
6365 if path.segs.is_empty() {
6366 return None;
6367 }
6368 let p = NSBezierPath::new();
6369 let mut cur = NSPoint::new(0.0, 0.0);
6373 for seg in &path.segs {
6374 match seg {
6375 PathSeg::Move(a) => {
6376 cur = NSPoint::new(a.x, a.y);
6377 p.moveToPoint(cur);
6378 }
6379 PathSeg::Line(a) => {
6380 cur = NSPoint::new(a.x, a.y);
6381 p.lineToPoint(cur);
6382 }
6383 PathSeg::Quad(c, a) => {
6384 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6385 let c1 = NSPoint::new(
6386 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6387 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6388 );
6389 let c2 = NSPoint::new(
6390 end.x + 2.0 / 3.0 * (ctl.x - end.x),
6391 end.y + 2.0 / 3.0 * (ctl.y - end.y),
6392 );
6393 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6394 cur = end;
6395 }
6396 PathSeg::Cubic(c1, c2, a) => {
6397 cur = NSPoint::new(a.x, a.y);
6398 p.curveToPoint_controlPoint1_controlPoint2(
6399 cur,
6400 NSPoint::new(c1.x, c1.y),
6401 NSPoint::new(c2.x, c2.y),
6402 );
6403 }
6404 PathSeg::Close => p.closePath(),
6405 }
6406 }
6407 p.setWindingRule(match path.rule {
6408 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6409 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6410 });
6411 p
6412 }
6413 })
6414 }
6415}
6416
6417struct UndoIvars {
6425 state: std::cell::RefCell<day_spec::UndoState>,
6426}
6427
6428define_class!(
6429 #[unsafe(super(objc2_foundation::NSUndoManager))]
6430 #[thread_kind = MainThreadOnly]
6431 #[name = "DayUndoManager"]
6432 #[ivars = UndoIvars]
6433 struct DayUndoManager;
6434
6435 impl DayUndoManager {
6439 #[unsafe(method(canUndo))]
6440 fn can_undo(&self) -> bool {
6441 self.ivars().state.borrow().can_undo
6442 }
6443
6444 #[unsafe(method(canRedo))]
6445 fn can_redo(&self) -> bool {
6446 self.ivars().state.borrow().can_redo
6447 }
6448
6449 #[unsafe(method(undo))]
6450 fn do_undo(&self) {
6451 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6452 }
6453
6454 #[unsafe(method(redo))]
6455 fn do_redo(&self) {
6456 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6457 }
6458
6459 #[unsafe(method_id(undoMenuItemTitle))]
6460 fn undo_menu_item_title(&self) -> Retained<NSString> {
6461 let label = self.ivars().state.borrow().undo_label.clone();
6464 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6465 }
6466
6467 #[unsafe(method_id(redoMenuItemTitle))]
6468 fn redo_menu_item_title(&self) -> Retained<NSString> {
6469 let label = self.ivars().state.borrow().redo_label.clone();
6470 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6471 }
6472 }
6473);
6474
6475fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6476 UNDO_FRONT.with(|u| {
6477 u.borrow_mut()
6478 .get_or_insert_with(|| {
6479 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6480 state: std::cell::RefCell::new(day_spec::UndoState::default()),
6481 });
6482 unsafe { msg_send![super(this), init] }
6483 })
6484 .clone()
6485 })
6486}
6487
6488struct WinIvars {
6496 node: Option<NodeId>,
6497 group: Option<String>,
6500 last_state: Cell<i32>,
6503}
6504
6505define_class!(
6506 #[unsafe(super(NSObject))]
6507 #[thread_kind = MainThreadOnly]
6508 #[name = "DayWinDelegate"]
6509 #[ivars = WinIvars]
6510 struct DayWinDelegate;
6511
6512 unsafe impl NSObjectProtocol for DayWinDelegate {}
6513
6514 impl DayWinDelegate {
6518 #[unsafe(method(undo:))]
6522 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6523 ffi_guard::contain((), || {
6524 if let Some(m) = self.acting_undo_manager() {
6525 unsafe { m.undo() };
6526 }
6527 });
6528 }
6529
6530 #[unsafe(method(redo:))]
6532 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6533 ffi_guard::contain((), || {
6534 if let Some(m) = self.acting_undo_manager() {
6535 unsafe { m.redo() };
6536 }
6537 });
6538 }
6539
6540 #[unsafe(method(cut:))]
6541 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6542 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6543 }
6544
6545 #[unsafe(method(copy:))]
6546 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6547 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6548 }
6549
6550 #[unsafe(method(paste:))]
6551 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6552 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6553 }
6554
6555 #[unsafe(method(selectAll:))]
6556 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6557 ffi_guard::contain((), || {
6558 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6559 });
6560 }
6561
6562 #[unsafe(method(validateMenuItem:))]
6566 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6567 ffi_guard::contain(false, || {
6568 let state = EDIT_STATE.with(|s| s.get());
6569 match unsafe { item.action() } {
6570 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6573 Some(m) => {
6574 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6575 unsafe { m.canUndo() }
6576 }
6577 None => false,
6578 },
6579 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6580 Some(m) => {
6581 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6582 unsafe { m.canRedo() }
6583 }
6584 None => false,
6585 },
6586 Some(a) if a == sel!(selectAll:) => state.can_select_all,
6587 Some(a) if a == sel!(cut:) => state.can_cut,
6588 Some(a) if a == sel!(copy:) => state.can_copy,
6589 Some(a) if a == sel!(paste:) => {
6590 state.can_paste && {
6591 let pb = unsafe { NSPasteboard::generalPasteboard() };
6592 pb.types().is_some_and(|types| !types.is_empty())
6593 }
6594 }
6595 _ => true,
6596 }
6597 })
6598 }
6599 }
6600
6601 unsafe impl NSWindowDelegate for DayWinDelegate {
6602 #[unsafe(method(windowDidResize:))]
6603 fn window_did_resize(&self, notification: &NSNotification) {
6604 ffi_guard::contain((), || {
6605 if let Some(obj) = unsafe { notification.object() }
6606 && let Ok(win) = obj.downcast::<NSWindow>()
6607 && let Some(size) = pin_below_title_bar(&win)
6608 {
6609 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6610 emit(target, Event::WindowResized(size));
6611 }
6612 self.report_state_of(notification);
6614 })
6615 }
6616
6617 #[unsafe(method(windowShouldClose:))]
6618 fn window_should_close(&self, _window: &NSWindow) -> bool {
6619 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6620 }
6621
6622 #[unsafe(method(windowWillClose:))]
6623 fn window_will_close(&self, _notification: &NSNotification) {
6624 ffi_guard::contain((), || {
6625 match self.ivars().node {
6626 Some(node) => emit(node, Event::WindowClosed),
6629 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6634 None => {
6635 let app = NSApplication::sharedApplication(self.mtm());
6636 unsafe { app.terminate(None) };
6637 }
6638 }
6639 })
6640 }
6641
6642 #[unsafe(method_id(windowWillReturnUndoManager:))]
6643 fn window_will_return_undo_manager(
6644 &self,
6645 _window: &NSWindow,
6646 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6647 ffi_guard::contain(None, || {
6651 UNDO_FRONT.with(|u| {
6652 u.borrow()
6653 .as_ref()
6654 .map(|m| Retained::into_super(m.clone()))
6655 })
6656 })
6657 }
6658
6659 #[unsafe(method(windowDidBecomeKey:))]
6660 fn window_did_become_key(&self, _notification: &NSNotification) {
6661 ffi_guard::contain((), || {
6662 if let Some(node) = self.ivars().node {
6663 emit(node, Event::WindowFocused(true));
6664 }
6665 })
6666 }
6667
6668 #[unsafe(method(windowDidResignKey:))]
6669 fn window_did_resign_key(&self, _notification: &NSNotification) {
6670 ffi_guard::contain((), || {
6671 if let Some(node) = self.ivars().node {
6672 emit(node, Event::WindowFocused(false));
6673 }
6674 })
6675 }
6676
6677 #[unsafe(method(windowDidMiniaturize:))]
6678 fn window_did_miniaturize(&self, notification: &NSNotification) {
6679 ffi_guard::contain((), || self.report_state_of(notification))
6680 }
6681
6682 #[unsafe(method(windowDidDeminiaturize:))]
6683 fn window_did_deminiaturize(&self, notification: &NSNotification) {
6684 ffi_guard::contain((), || self.report_state_of(notification))
6685 }
6686
6687 #[unsafe(method(windowDidEnterFullScreen:))]
6688 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6689 ffi_guard::contain((), || self.report_state_of(notification))
6690 }
6691
6692 #[unsafe(method(windowDidExitFullScreen:))]
6693 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6694 ffi_guard::contain((), || self.report_state_of(notification))
6695 }
6696 }
6697
6698 impl DayWinDelegate {
6702 #[unsafe(method(newWindowForTab:))]
6703 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6704 ffi_guard::contain((), || {
6705 let _ = match self.ivars().group.as_deref() {
6708 Some(group) => day_core::windows::open_new_window_for_group(group),
6709 None => day_core::windows::open_new_window(),
6710 };
6711 })
6712 }
6713 }
6714);
6715
6716impl DayWinDelegate {
6717 fn report_state_of(&self, notification: &NSNotification) {
6718 if let Some(obj) = unsafe { notification.object() }
6719 && let Ok(win) = obj.downcast::<NSWindow>()
6720 {
6721 self.report_state(&win);
6722 }
6723 }
6724}
6725
6726fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6729 match unsafe { event.keyCode() } {
6730 123 => Some("ArrowLeft"),
6731 124 => Some("ArrowRight"),
6732 125 => Some("ArrowDown"),
6733 126 => Some("ArrowUp"),
6734 _ => {
6742 let held = NSEventModifierFlags::Command
6743 | NSEventModifierFlags::Option
6744 | NSEventModifierFlags::Control;
6745 if event.modifierFlags().intersects(held) {
6746 return None;
6747 }
6748 let typed = event.characters()?.to_string();
6749 let mut chars = typed.chars();
6750 match (chars.next(), chars.next()) {
6751 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6752 _ => None,
6753 }
6754 }
6755 }
6756}
6757
6758fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6761 Some(match unsafe { event.keyCode() } {
6762 123 => "ArrowLeft",
6763 124 => "ArrowRight",
6764 125 => "ArrowDown",
6765 126 => "ArrowUp",
6766 36 | 76 => "Enter",
6767 48 => "Tab",
6768 53 => "Escape",
6769 51 => "Backspace",
6770 117 => "Delete",
6771 115 => "Home",
6772 119 => "End",
6773 116 => "PageUp",
6774 121 => "PageDown",
6775 114 => "Insert",
6776 122 => "F1",
6777 120 => "F2",
6778 99 => "F3",
6779 118 => "F4",
6780 96 => "F5",
6781 97 => "F6",
6782 98 => "F7",
6783 100 => "F8",
6784 101 => "F9",
6785 109 => "F10",
6786 103 => "F11",
6787 111 => "F12",
6788 _ => return None,
6789 })
6790}
6791
6792fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
6803 let ptr = (view as *const DayCanvas).cast::<NSView>() as usize;
6804 let flags = event.modifierFlags();
6805 let mods = key_modifiers(flags);
6806 if flags.contains(NSEventModifierFlags::Command) {
6807 return false;
6808 }
6809 let composing = MARKED.with(|t| t.contains(ptr));
6810 if !composing && let Some(named) = named_key(event) {
6811 emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
6812 return true;
6813 }
6814 let unmodified = unsafe { event.charactersIgnoringModifiers() }
6815 .map(|s| s.to_string())
6816 .unwrap_or_default();
6817 let typeable = !unmodified.is_empty()
6819 && !unmodified
6820 .chars()
6821 .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
6822 if !composing && flags.contains(NSEventModifierFlags::Control) {
6823 if typeable {
6824 emit(
6825 node,
6826 Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
6827 );
6828 }
6829 return true;
6830 }
6831 if !composing && !typeable {
6832 return true;
6833 }
6834 INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
6835 view.interpretKeyEvents(&NSArray::from_slice(&[event]));
6836 INTERPRETING.with(|i| *i.borrow_mut() = None);
6837 true
6838}
6839
6840fn text_of_input_string(string: &AnyObject) -> String {
6842 if let Some(s) = string.downcast_ref::<NSString>() {
6843 s.to_string()
6844 } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
6845 s.string().to_string()
6846 } else {
6847 String::new()
6848 }
6849}
6850
6851fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6853 let mut modifiers = 0u8;
6854 if f.contains(NSEventModifierFlags::Shift) {
6855 modifiers |= day_spec::KeyEvent::SHIFT;
6856 }
6857 if f.contains(NSEventModifierFlags::Command) {
6858 modifiers |= day_spec::KeyEvent::PRIMARY;
6859 }
6860 if f.contains(NSEventModifierFlags::Option) {
6861 modifiers |= day_spec::KeyEvent::ALT;
6862 }
6863 if f.contains(NSEventModifierFlags::Control) {
6864 modifiers |= day_spec::KeyEvent::CONTROL;
6865 }
6866 modifiers
6867}
6868
6869impl DayWinDelegate {
6870 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6875 let responder = NSApplication::sharedApplication(self.mtm())
6876 .keyWindow()
6877 .and_then(|w| w.firstResponder());
6878 responder
6879 .and_then(|r| unsafe { r.undoManager() })
6880 .or_else(|| {
6881 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6882 })
6883 }
6884}
6885
6886impl DayWinDelegate {
6887 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6888 let this = Self::alloc(mtm).set_ivars(WinIvars {
6889 node,
6890 group,
6891 last_state: Cell::new(day_spec::WindowState::Normal.code()),
6892 });
6893 unsafe { msg_send![super(this), init] }
6894 }
6895
6896 fn report_state(&self, window: &NSWindow) {
6900 let state = ns_window_state(window);
6901 if self.ivars().last_state.replace(state.code()) != state.code() {
6902 log::debug!("appkit: window state now {state:?}");
6903 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6904 emit(target, Event::WindowStateChanged(state));
6905 }
6906 }
6907}
6908
6909fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6912 if window.isMiniaturized() {
6913 day_spec::WindowState::Minimized
6914 } else if window
6915 .styleMask()
6916 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6917 {
6918 day_spec::WindowState::Fullscreen
6919 } else if window.isZoomed() {
6920 day_spec::WindowState::Maximized
6921 } else {
6922 day_spec::WindowState::Normal
6923 }
6924}
6925
6926fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6929 use day_spec::WindowState as S;
6930 let current = ns_window_state(window);
6931 if current == state {
6932 return;
6933 }
6934 unsafe {
6935 match current {
6936 S::Minimized => window.deminiaturize(None),
6937 S::Fullscreen => {
6941 window.toggleFullScreen(None);
6942 return;
6943 }
6944 S::Maximized if state != S::Minimized => window.zoom(None),
6945 _ => {}
6946 }
6947 match state {
6948 S::Normal => {}
6949 S::Minimized => window.miniaturize(None),
6950 S::Maximized => {
6951 if !window.isZoomed() {
6952 window.zoom(None)
6953 }
6954 }
6955 S::Fullscreen => window.toggleFullScreen(None),
6956 }
6957 }
6958}
6959
6960#[distributed_slice]
6966pub static RENDERERS: [fn() -> Renderer<AppKit>];
6967
6968struct SecondaryWin {
6972 window: Retained<NSWindow>,
6973 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
6975 content: Handle,
6976}
6977
6978struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6981impl Drop for MenuEscapeMonitor {
6982 fn drop(&mut self) {
6983 unsafe { NSEvent::removeMonitor(&self.0) };
6984 }
6985}
6986
6987pub struct AppKit {
6988 menu_escape_monitor: Option<MenuEscapeMonitor>,
6989 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6990
6991 mtm: MainThreadMarker,
6992 registry: Registry<AppKit>,
6993 window: Option<Retained<NSWindow>>,
6994 content: Option<Handle>,
6995 secondary: Vec<SecondaryWin>,
6996 app_name: String,
6997 cascade: Option<NSPoint>,
7002 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7005}
7006
7007impl AppKit {
7008 fn swap_text_field(
7013 &mut self,
7014 h: &Handle,
7015 old: &NSTextField,
7016 node: NodeId,
7017 secure: bool,
7018 ) -> Retained<NSTextField> {
7019 let new = new_text_field(self.mtm, node, secure);
7020 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7021 let window = h.window();
7024 let focused = window
7025 .as_deref()
7026 .is_some_and(|w| owns_first_responder(w, h));
7027 let selection = old.currentEditor().map(|e| e.selectedRange());
7028 unsafe {
7029 new.setStringValue(&old.stringValue());
7030 new.setPlaceholderString(old.placeholderString().as_deref());
7031 new.setEnabled(old.isEnabled());
7032 new.setFont(old.font().as_deref());
7033 new.setFrame(h.frame());
7034 new.setHidden(h.isHidden());
7035 new.setMenu(h.menu().as_deref());
7036 new.setToolTip(h.toolTip().as_deref());
7037 if h.wantsLayer() {
7039 new.setWantsLayer(true);
7040 new.setAlphaValue(h.alphaValue());
7041 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7042 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7043 if !from.is_null() && !to.is_null() {
7044 let t: CGAffineTransform = msg_send![from, affineTransform];
7045 let _: () = msg_send![to, setAffineTransform: t];
7046 }
7047 }
7048 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7051 new.setAccessibilityIdentifier(Some(&id));
7052 }
7053 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7054 new.setAccessibilityLabel(Some(&label));
7055 }
7056 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7057 new.setAccessibilityHelp(Some(&help));
7058 }
7059 if !h.isAccessibilityElement() {
7060 new.setAccessibilityElement(false);
7061 }
7062 }
7063 for r in unsafe { h.gestureRecognizers() }.iter() {
7065 unsafe {
7066 h.removeGestureRecognizer(&r);
7067 new.addGestureRecognizer(&r);
7068 }
7069 }
7070 GESTURES.with(|m| {
7071 let mut m = m.borrow_mut();
7072 if let Some(targets) = m.remove(&old_key) {
7073 m.insert(new_key, targets);
7074 }
7075 });
7076 if let Some((owner, area)) = self.cursors.remove(&old_key) {
7077 unsafe {
7078 h.removeTrackingArea(&area);
7079 new.addTrackingArea(&area);
7080 }
7081 self.cursors.insert(new_key, (owner, area));
7082 }
7083 PAN_NODES.with(|t| rekey(t, old_key, new_key));
7084 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7085 KEY_NODES.with(|t| rekey(t, old_key, new_key));
7086 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7087 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7088 transfer::moved(h, &new);
7089 unsafe { old.setDelegate(None) };
7092 TARGETS.with(|m| {
7093 m.borrow_mut().remove(&old_key);
7094 });
7095 if let Some(parent) = unsafe { h.superview() } {
7096 unsafe {
7097 parent.addSubview_positioned_relativeTo(
7098 &new,
7099 objc2_app_kit::NSWindowOrderingMode::Above,
7100 Some(h),
7101 );
7102 h.removeFromSuperview();
7103 }
7104 }
7105 if focused && let Some(window) = window {
7106 FIELD_SWAP.with(|s| s.set(true));
7107 let taken = window.makeFirstResponder(Some(&new));
7108 FIELD_SWAP.with(|s| s.set(false));
7109 if taken && let Some(editor) = new.currentEditor() {
7112 let len = unsafe { new.stringValue() }.length();
7113 let range = selection
7114 .filter(|r| r.location.saturating_add(r.length) <= len)
7115 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7116 editor.setSelectedRange(range);
7117 }
7118 }
7119 day_spec::sidetable::sweep(old_key);
7121 new
7122 }
7123
7124 pub fn new() -> Self {
7125 let mtm =
7126 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7127 let mut registry = Registry::default();
7128 for f in RENDERERS {
7129 registry.register(f());
7130 }
7131 AppKit {
7132 menu_escape_monitor: None,
7133 mtm,
7134 registry,
7135 window: None,
7136 sharing: None,
7137 content: None,
7138 secondary: Vec::new(),
7139 app_name: "Day".into(),
7140 cascade: None,
7141 cursors: HashMap::new(),
7142 }
7143 }
7144
7145 pub fn mtm(&self) -> MainThreadMarker {
7147 self.mtm
7148 }
7149
7150 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7152 if let Some(w) = self
7153 .secondary
7154 .iter()
7155 .find(|w| ptr_of(&w.content) == ptr_of(host))
7156 {
7157 return Some(w.window.clone());
7158 }
7159 self.content
7160 .as_ref()
7161 .filter(|c| ptr_of(c) == ptr_of(host))
7162 .and(self.window.clone())
7163 }
7164
7165 fn make_window(
7171 &self,
7172 options: &WindowOptions,
7173 prefs_style: bool,
7174 node: Option<NodeId>,
7175 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7176 let mtm = self.mtm;
7177 let (title, size, min_size, tabbing) = (
7178 options.title.as_str(),
7179 options.size,
7180 options.min_size,
7181 &options.tabbing,
7182 );
7183 let content_rect =
7184 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7185 let style = window_chrome::style_mask(options, prefs_style);
7187 let window = window_chrome::alloc_window(
7188 mtm,
7189 content_rect,
7190 style,
7191 options.chrome == day_spec::WindowChrome::Frameless,
7192 );
7193 unsafe { window.setReleasedWhenClosed(false) };
7194 window.setTitle(&NSString::from_str(title));
7195 if let Some(min) = min_size {
7196 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7197 }
7198 if let Some(max) = options.max_size {
7199 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7200 }
7201 use day_spec::WindowTabbing as T;
7202 use objc2_app_kit::NSWindowTabbingMode as M;
7203 let group = match tabbing {
7204 T::Group(g) | T::Preferred(g) => Some(g.clone()),
7205 T::Automatic | T::Disallowed => None,
7206 };
7207 match tabbing {
7208 _ if prefs_style => window.setTabbingMode(M::Disallowed),
7209 T::Disallowed => window.setTabbingMode(M::Disallowed),
7210 T::Automatic => unsafe {
7214 window.setTabbingIdentifier(&NSString::from_str("day.normal"))
7215 },
7216 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7217 T::Preferred(g) => {
7218 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7219 window.setTabbingMode(M::Preferred);
7220 }
7221 }
7222 if group.is_some() {
7223 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7226 }
7227 let delegate = DayWinDelegate::new(mtm, node, group);
7228 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7229 let content = view_of(DayFlipped::new(mtm));
7230 window.setContentView(Some(&content));
7231 window_chrome::apply(&window, &content, options);
7232 window.setAutorecalculatesKeyViewLoop(true);
7241 (window, delegate, content)
7242 }
7243}
7244
7245impl Default for AppKit {
7246 fn default() -> Self {
7247 Self::new()
7248 }
7249}
7250
7251fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7252 Retained::from(x.as_ref())
7253}
7254
7255fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7256 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7257}
7258
7259fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7262 use objc2_app_kit::*;
7263 unsafe {
7264 Some(match f {
7265 Font::LargeTitle => NSFontTextStyleLargeTitle,
7266 Font::Title => NSFontTextStyleTitle1,
7267 Font::Title2 => NSFontTextStyleTitle2,
7268 Font::Title3 => NSFontTextStyleTitle3,
7269 Font::Headline => NSFontTextStyleHeadline,
7270 Font::Subheadline => NSFontTextStyleSubheadline,
7271 Font::Body => NSFontTextStyleBody,
7272 Font::Callout => NSFontTextStyleCallout,
7273 Font::Footnote => NSFontTextStyleFootnote,
7274 Font::Caption => NSFontTextStyleCaption1,
7275 Font::Caption2 => NSFontTextStyleCaption2,
7276 Font::System(_) | Font::Custom(..) => return None,
7277 })
7278 }
7279}
7280
7281fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7282 use day_spec::FontWeight as W;
7283 use objc2_app_kit::*;
7284 unsafe {
7285 match w {
7286 W::UltraLight => NSFontWeightUltraLight,
7287 W::Thin => NSFontWeightThin,
7288 W::Light => NSFontWeightLight,
7289 W::Regular => NSFontWeightRegular,
7290 W::Medium => NSFontWeightMedium,
7291 W::Semibold => NSFontWeightSemibold,
7292 W::Bold => NSFontWeightBold,
7293 W::Heavy => NSFontWeightHeavy,
7294 W::Black => NSFontWeightBlack,
7295 }
7296 }
7297}
7298
7299fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7302 use day_spec::FontWeight as W;
7303 match w {
7304 W::UltraLight => 2,
7305 W::Thin => 3,
7306 W::Light => 4,
7307 W::Regular => 5,
7308 W::Medium => 6,
7309 W::Semibold => 8,
7310 W::Bold => 9,
7311 W::Heavy => 10,
7312 W::Black => 12,
7313 }
7314}
7315
7316fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7321 use objc2_app_kit::*;
7322 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7323 let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7324 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7325 let mut traits = NSFontTraitMask::empty();
7326 if weight >= day_spec::FontWeight::Semibold {
7327 traits |= NSFontTraitMask::BoldFontMask;
7328 }
7329 if font.italic {
7330 traits |= NSFontTraitMask::ItalicFontMask;
7331 }
7332 let Some(family) = font.family.as_deref() else {
7333 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7334 return if font.italic {
7335 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7336 } else {
7337 base
7338 };
7339 };
7340 let ns_family = NSString::from_str(family);
7341 if let Some(f) = unsafe {
7342 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7343 } {
7344 return f;
7345 }
7346 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7347 return if traits.is_empty() {
7348 f
7349 } else {
7350 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7351 };
7352 }
7353 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7354 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7355}
7356
7357fn canvas_text_attrs(
7360 font: &NSFont,
7361 color: day_spec::Color,
7362) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7363 let col = nscolor(color);
7364 let keys: [&NSString; 2] = unsafe {
7366 [
7367 objc2_app_kit::NSFontAttributeName,
7368 objc2_app_kit::NSForegroundColorAttributeName,
7369 ]
7370 };
7371 let objs: [&objc2::runtime::AnyObject; 2] = [
7372 font as &objc2::runtime::AnyObject,
7373 col.as_ref() as &objc2::runtime::AnyObject,
7374 ];
7375 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7376}
7377
7378fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7381 use objc2_app_kit::*;
7382 let base: Retained<NSFont> = match spec.style {
7383 Font::System(pt) => {
7384 let w = spec
7385 .weight
7386 .map(ns_weight)
7387 .unwrap_or(unsafe { NSFontWeightRegular });
7388 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7389 }
7390 Font::Custom(name, pt) => {
7394 match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7395 Some(f) => {
7396 if spec
7397 .weight
7398 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7399 {
7400 let mtm = objc2::MainThreadMarker::new()
7401 .expect("labels realize on the main thread");
7402 unsafe {
7403 NSFontManager::sharedFontManager(mtm)
7404 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7405 }
7406 } else {
7407 f
7408 }
7409 }
7410 None => {
7411 log::warn!(
7412 "unknown font family {name:?} — falling back to the system font \
7413 (is the file in the project's fonts/ directory?)"
7414 );
7415 let w = spec
7416 .weight
7417 .map(ns_weight)
7418 .unwrap_or(unsafe { NSFontWeightRegular });
7419 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7420 }
7421 }
7422 }
7423 style => {
7424 let ts = ns_text_style(style).expect("semantic style");
7427 let opts = objc2_foundation::NSDictionary::new();
7428 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7429 match spec.weight {
7430 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7432 None => f,
7433 }
7434 }
7435 };
7436 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7441 let w = spec
7442 .weight
7443 .map(ns_weight)
7444 .unwrap_or(unsafe { NSFontWeightRegular });
7445 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7446 } else {
7447 base
7448 };
7449 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7453 let w = spec
7454 .weight
7455 .map(ns_weight)
7456 .unwrap_or(unsafe { NSFontWeightRegular });
7457 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7458 } else {
7459 base
7460 };
7461 let base = if spec.scale != 1.0 {
7465 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7466 let pts = spec.resolved_points(base.pointSize());
7467 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7468 } else {
7469 base
7470 };
7471 if spec.italic {
7472 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7473 unsafe {
7474 NSFontManager::sharedFontManager(mtm)
7475 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7476 }
7477 } else {
7478 base
7479 }
7480}
7481
7482fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7492 use objc2_foundation::{NSMutableAttributedString, NSRange};
7493 unsafe {
7494 let cur = tf.attributedStringValue();
7495 let m = NSMutableAttributedString::initWithAttributedString(
7496 NSMutableAttributedString::alloc(),
7497 &cur,
7498 );
7499 let style = objc2_app_kit::NSMutableParagraphStyle::new();
7500 style.setAlignment(align);
7501 style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7504 m.addAttribute_value_range(
7505 objc2_app_kit::NSParagraphStyleAttributeName,
7506 &style,
7507 NSRange::new(0, cur.length()),
7508 );
7509 tf.setAttributedStringValue(&m);
7510 }
7511}
7512
7513fn attributed_label(
7514 text: &str,
7515 base_font: &NSFont,
7516 color: Option<day_spec::Color>,
7517 role: day_spec::props::TextRole,
7518 runs: &[day_spec::TextRun],
7519) -> Retained<objc2_foundation::NSAttributedString> {
7520 use objc2_foundation::{NSMutableAttributedString, NSRange};
7521 let ns = NSString::from_str(text);
7522 let s = unsafe {
7523 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7524 };
7525 let whole = NSRange::new(0, ns.length());
7526 unsafe {
7527 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7528 let fg = color.map(nscolor).unwrap_or_else(|| match role {
7536 day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7537 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7538 });
7539 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7540 }
7541 for r in runs {
7542 let Some(range) = utf16_range(text, &r.range) else {
7543 continue;
7544 };
7545 unsafe {
7546 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7547 if let Some(c) = r.color {
7548 s.addAttribute_value_range(
7549 objc2_app_kit::NSForegroundColorAttributeName,
7550 &nscolor(c),
7551 range,
7552 );
7553 }
7554 if let Some(c) = r.background {
7555 s.addAttribute_value_range(
7556 objc2_app_kit::NSBackgroundColorAttributeName,
7557 &nscolor(c),
7558 range,
7559 );
7560 }
7561 if r.underline.is_on() {
7562 let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7563 s.addAttribute_value_range(
7564 objc2_app_kit::NSUnderlineStyleAttributeName,
7565 &style,
7566 range,
7567 );
7568 }
7569 if r.strikethrough {
7570 let one = objc2_foundation::NSNumber::new_i64(1);
7571 s.addAttribute_value_range(
7572 objc2_app_kit::NSStrikethroughStyleAttributeName,
7573 &one,
7574 range,
7575 );
7576 }
7577 if let Some(url) = r.link.as_deref() {
7578 let value = NSString::from_str(url);
7581 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7582 }
7583 }
7584 }
7585 s.into_super()
7586}
7587
7588fn ns_underline(u: day_spec::Underline) -> i64 {
7592 use day_spec::Underline as U;
7593 match u {
7594 U::None => 0,
7595 U::Single => 0x01,
7596 U::Double => 0x09,
7597 U::Dotted => 0x01 | 0x0100,
7598 U::Wavy => 0x01 | 0x0400,
7599 }
7600}
7601
7602fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7604 let start = text.get(..r.start)?.encode_utf16().count();
7605 let len = text.get(r.clone())?.encode_utf16().count();
7606 Some(objc2_foundation::NSRange::new(start, len))
7607}
7608
7609fn register_bundled_fonts() {
7614 #[link(name = "CoreText", kind = "framework")]
7616 unsafe extern "C" {
7617 fn CTFontManagerRegisterFontsForURL(
7618 font_url: *const std::ffi::c_void,
7619 scope: u32, error: *mut *const std::ffi::c_void,
7621 ) -> bool;
7622 }
7623 for path in day_spec::fonts::bundled_fonts() {
7624 let url = unsafe {
7625 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7626 };
7627 let ok = unsafe {
7628 CTFontManagerRegisterFontsForURL(
7629 Retained::as_ptr(&url) as *const std::ffi::c_void,
7630 1,
7631 std::ptr::null_mut(),
7632 )
7633 };
7634 if !ok {
7635 log::warn!("could not register bundled font {}", path.display());
7636 }
7637 }
7638}
7639
7640fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7643 match a {
7644 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7645 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7646 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7647 }
7648}
7649
7650fn configure_label_cell(tf: &NSTextField) {
7651 if let Some(cell) = unsafe { tf.cell() } {
7652 unsafe {
7653 cell.setWraps(true);
7654 cell.setUsesSingleLineMode(false);
7655 cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7656 }
7657 }
7658}
7659
7660fn content_of(parent: &Handle) -> Retained<NSView> {
7662 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7663 && let Some(doc) = unsafe { sv.documentView() }
7664 {
7665 return doc;
7666 }
7667 parent.clone()
7668}
7669
7670fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7676 let Some(a) = anim else {
7677 body();
7678 return;
7679 };
7680 let (dur, timing) = appkit_timing(a);
7681 unsafe {
7682 NSAnimationContext::beginGrouping();
7683 let ctx = NSAnimationContext::currentContext();
7684 ctx.setDuration(dur);
7685 ctx.setTimingFunction(Some(&timing));
7686 ctx.setAllowsImplicitAnimation(true);
7687 body();
7688 NSAnimationContext::endGrouping();
7689 }
7690}
7691
7692fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7695 unsafe {
7696 let named = |n| {
7697 (
7698 a.duration_secs().max(0.01),
7699 CAMediaTimingFunction::functionWithName(n),
7700 )
7701 };
7702 match a.curve {
7703 Curve::Linear => named(kCAMediaTimingFunctionLinear),
7704 Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7705 Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7706 Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7707 Curve::Spring { damping, .. } => {
7708 let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7710 (
7711 a.duration_secs().max(0.05),
7712 CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7713 )
7714 }
7715 }
7716 }
7717}
7718
7719fn warn_missing_renderer(kind: PieceKind) {
7724 day_spec::placeholder::report(kind, "appkit");
7725}
7726
7727pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7731 view_of(unsafe {
7732 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7733 })
7734}
7735
7736impl Toolkit for AppKit {
7737 fn ui_idle(&mut self) -> bool {
7740 toolbar::chrome_settled()
7741 }
7742
7743 type Handle = Handle;
7744
7745 fn dark_mode(&mut self) -> bool {
7746 let app = NSApplication::sharedApplication(self.mtm());
7749 app.effectiveAppearance()
7750 .name()
7751 .to_string()
7752 .contains("Dark")
7753 }
7754
7755 fn reduce_motion(&mut self) -> bool {
7758 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7759 }
7760
7761 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7765 use day_spec::AppBadge;
7766 let label = match badge {
7767 AppBadge::None => None,
7768 AppBadge::Count(0) => None,
7770 AppBadge::Count(n) => Some(n.to_string()),
7771 AppBadge::Text(t) if t.is_empty() => None,
7772 AppBadge::Text(t) => Some(t.clone()),
7773 AppBadge::Dot => Some("\u{2022}".to_string()),
7775 };
7776 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7777 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7778 unsafe { tile.setBadgeLabel(ns.as_deref()) };
7779 tile.display();
7780 }
7781
7782 fn set_appearance(&mut self, dark: Option<bool>) {
7783 let app = NSApplication::sharedApplication(self.mtm());
7784 let appearance = dark.and_then(|d| {
7785 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7786 if d {
7787 objc2_app_kit::NSAppearanceNameDarkAqua
7788 } else {
7789 objc2_app_kit::NSAppearanceNameAqua
7790 }
7791 })
7792 });
7793 unsafe { app.setAppearance(appearance.as_deref()) };
7795 }
7796
7797 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7798 controls::refresh_gesture::attach(handle, host);
7799 }
7800
7801 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7802 unsafe {
7803 handle.setHidden(!visible);
7804 }
7805 }
7806
7807 fn capability(&self, cap: Cap) -> Support {
7808 match cap {
7809 Cap::SearchField => Support::Native,
7810 Cap::ComboBox => Support::Native,
7811 Cap::Stepper => Support::Native,
7812 Cap::DateTimePicker => Support::Native,
7813 Cap::ColorPicker => Support::Native,
7814 Cap::PullRefresh => Support::Emulated,
7815 Cap::Pager => Support::Emulated,
7816 Cap::PullRefreshGesture => Support::Emulated,
7817 Cap::Cursor => Support::Native,
7821 Cap::FontList => Support::Native,
7823 Cap::ListItem => Support::Native,
7825 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7829 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7832 Cap::Announce => Support::Native,
7835 Cap::ReduceMotion => Support::Native,
7838 Cap::Snapshot
7839 | Cap::NativeSymbols
7840 | Cap::NavTabs
7849 | Cap::NavSplit
7850 | Cap::NavRepresent
7854 | Cap::NavContentList
7857 | Cap::Dialogs
7858 | Cap::FileDialogs
7859 | Cap::FolderDialog
7861 | Cap::Animation
7862 | Cap::TextEditable
7864 | Cap::TextSelectable
7865 | Cap::TextSpellCheck
7866 | Cap::NavReorder | Cap::ListReorder
7869 | Cap::ListRecycling
7872 | Cap::ListSwipeActions
7875 | Cap::ListSections
7877 | Cap::Tree
7880 | Cap::TreeSections
7881 | Cap::TreeMove
7882 | Cap::MultiWindow
7884 | Cap::WindowStates
7887 | Cap::WindowFullscreen
7888 | Cap::ContentProtection
7890 | Cap::WindowTabbing
7893 | Cap::DockMenu
7895 | Cap::FramelessWindow
7899 | Cap::OverlayTitleBar
7900 | Cap::TransparentWindow
7901 | Cap::WindowMaterial
7902 | Cap::DragRegion
7904 | Cap::StatusItem
7907 | Cap::AppProgress
7908 | Cap::DockVisibility
7909 | Cap::WindowGeometry
7912 | Cap::WindowPosition
7913 | Cap::WindowLevel
7914 | Cap::WindowAppearance
7915 | Cap::RequestAttention
7916 | Cap::Monitors
7917 | Cap::DynamicShortcuts
7919 | Cap::Toolbar
7921 | Cap::ToolbarSearch
7923 | Cap::AppMenu
7924 | Cap::AppBadgeCount
7927 | Cap::AppBadgeText
7928 | Cap::UndoBridge
7931 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7932 | Cap::AppBadgeDot
7933 | Cap::Appearance
7934 | Cap::BaselineAlignment
7936 | Cap::Inspector
7939 | Cap::Split
7941 | Cap::TextRuns
7942 | Cap::TextLinks => Support::Native,
7943 Cap::Cover => Support::Emulated,
7946 Cap::CoverSheet => Support::Native,
7948 _ => Support::Unsupported,
7949 }
7950 }
7951
7952 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7953 let mtm = self.mtm;
7954 match Builtin::from_key(kind) {
7955 Some(Builtin::Container) => {
7956 let v = DayFlipped::new(mtm);
7957 if let Some(p) = props.downcast_ref::<ContainerProps>() {
7958 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7959 v.set_section_card(p.corner_radius);
7960 } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7961 v.set_surface(p.background, p.corner_radius, p.clips);
7962 }
7963 }
7964 view_of(v)
7965 }
7966 Some(Builtin::Scroll) => {
7967 let horizontal = props
7968 .downcast_ref::<day_spec::props::ScrollProps>()
7969 .map(|p| p.horizontal)
7970 .unwrap_or(false);
7971 let sv = unsafe { NSScrollView::new(mtm) };
7972 unsafe {
7973 sv.setHasVerticalScroller(!horizontal);
7974 sv.setHasHorizontalScroller(horizontal);
7975 sv.setDrawsBackground(false);
7976 sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7982 }
7983 let doc = DayFlipped::new(mtm);
7984 unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7985 view_of(sv)
7986 }
7987 Some(Builtin::Label) => {
7988 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7993 return placeholder_view(mtm, kind);
7994 };
7995 let tf = DayLabel::new(mtm, id, &p.text);
7996 configure_label_cell(&tf);
7997 if !p.wraps || p.max_lines > 0 {
7998 unsafe {
7999 tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8000 if !p.wraps || p.max_lines == 1 {
8001 tf.setUsesSingleLineMode(true);
8002 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8003 }
8004 }
8005 }
8006 unsafe { tf.setFont(Some(&nsfont(p.font))) };
8007 match (p.color, p.role) {
8011 (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8012 (None, day_spec::props::TextRole::Secondary) => unsafe {
8013 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
8014 },
8015 (None, day_spec::props::TextRole::Primary) => {}
8016 }
8017 if !p.runs.is_empty() {
8018 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8019 unsafe { tf.setAttributedStringValue(&s) };
8020 }
8021 tf.ivars().has_runs.set(!p.runs.is_empty());
8022 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8023 if p.align != day_spec::props::TextAlign::Leading {
8028 unsafe { tf.setAlignment(nstextalign(p.align)) };
8029 if !p.runs.is_empty() {
8030 set_paragraph_alignment(&tf, nstextalign(p.align));
8031 }
8032 }
8033 view_of(Retained::into_super(tf))
8034 }
8035 Some(Builtin::Button) => {
8036 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8037 return placeholder_view(mtm, kind);
8038 };
8039 let target = DayTarget::new(mtm, id);
8040 let btn = unsafe {
8041 NSButton::buttonWithTitle_target_action(
8042 &NSString::from_str(&p.title),
8043 Some(&*target),
8044 Some(sel!(action:)),
8045 mtm,
8046 )
8047 };
8048 apply_button_style(&btn, p.style);
8049 if p.icon.is_some() {
8050 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8051 }
8052 unsafe { btn.setEnabled(p.enabled) };
8053 set_button_selected(&btn, p.selected);
8054 let view = view_of(btn);
8055 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8056 view
8057 }
8058 Some(Builtin::Toggle) => {
8059 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8060 return placeholder_view(mtm, kind);
8061 };
8062 let target = DayTarget::new(mtm, id);
8063 let sw = unsafe { NSSwitch::new(mtm) };
8064 unsafe {
8065 sw.setState(if p.on { 1 } else { 0 });
8066 sw.setEnabled(p.enabled);
8067 sw.setTarget(Some(&*target));
8068 sw.setAction(Some(sel!(action:)));
8069 }
8070 let view = view_of(sw);
8071 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8072 view
8073 }
8074 Some(Builtin::Slider) => {
8075 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8076 return placeholder_view(mtm, kind);
8077 };
8078 let target = DayTarget::new(mtm, id);
8079 let sl = unsafe {
8080 NSSlider::sliderWithValue_minValue_maxValue_target_action(
8081 p.value,
8082 p.min,
8083 p.max,
8084 Some(&*target),
8085 Some(sel!(action:)),
8086 mtm,
8087 )
8088 };
8089 unsafe { sl.setContinuous(true) };
8090 let view = view_of(sl);
8091 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8092 view
8093 }
8094 Some(Builtin::Picker) => picker::realize_any(self, props, id),
8095 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8096 Some(Builtin::TextField) => {
8097 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8098 return placeholder_view(mtm, kind);
8099 };
8100 let tf = new_text_field(mtm, id, false);
8101 unsafe {
8102 tf.setStringValue(&NSString::from_str(&p.text));
8103 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8104 }
8105 view_of(tf)
8106 }
8107 Some(Builtin::Divider) => {
8108 let b = unsafe { NSBox::new(mtm) };
8109 unsafe { b.setBoxType(NSBoxType::Separator) };
8110 view_of(b)
8111 }
8112 Some(Builtin::Progress) => {
8113 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8114 return placeholder_view(mtm, kind);
8115 };
8116 if p.value.is_none() {
8117 return crate::controls::spinner::make(self, p, id);
8118 }
8119 let pi = unsafe { NSProgressIndicator::new(mtm) };
8120 unsafe {
8121 match p.value {
8122 Some(v) => {
8123 pi.setStyle(NSProgressIndicatorStyle::Bar);
8124 pi.setIndeterminate(false);
8125 pi.setMinValue(0.0);
8126 pi.setMaxValue(1.0);
8127 pi.setDoubleValue(v);
8128 }
8129 None => {
8130 pi.setStyle(NSProgressIndicatorStyle::Spinning);
8131 pi.setIndeterminate(true);
8132 pi.startAnimation(None);
8133 }
8134 }
8135 }
8136 view_of(pi)
8137 }
8138 Some(Builtin::Canvas) => {
8139 let canvas = DayCanvas::new(mtm);
8140 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8141 view_of(canvas)
8142 }
8143 Some(Builtin::Inspector) => {
8144 let (visible, width, leading) = props
8145 .downcast_ref::<InspectorProps>()
8146 .map(|p| {
8147 (
8148 p.visible,
8149 p.width,
8150 p.edge == day_spec::props::PaneEdge::Leading,
8151 )
8152 })
8153 .unwrap_or((false, 280.0, false));
8154 let content_wrap = view_of(DayFlipped::new(mtm));
8155 let panel_flipped = DayFlipped::new(mtm);
8156 panel_flipped.set_pane_backdrop();
8160 let panel_wrap = view_of(panel_flipped);
8161 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8162 let _ = unsafe { split_vc.view() };
8165 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8166 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8167 unsafe {
8168 content_vc.setView(&content_wrap);
8169 panel_vc.setView(&panel_wrap);
8170 }
8171 let content_item = unsafe {
8172 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8173 };
8174 let panel_item = unsafe {
8179 if leading {
8180 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8181 } else {
8182 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8183 }
8184 };
8185 unsafe {
8186 panel_item.setCanCollapse(false);
8190 panel_item.setCollapsed(!visible);
8191 panel_item.setMinimumThickness(width);
8192 panel_item.setMaximumThickness(width);
8193 panel_item.setAllowsFullHeightLayout(true);
8194 if leading {
8195 split_vc.addSplitViewItem(&panel_item);
8196 split_vc.addSplitViewItem(&content_item);
8197 } else {
8198 split_vc.addSplitViewItem(&content_item);
8199 split_vc.addSplitViewItem(&panel_item);
8200 }
8201 }
8202 let split = unsafe { split_vc.splitView() };
8203 unsafe {
8204 split.setVertical(true);
8205 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8206 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8210 }
8211 let view = view_of(split);
8212 INSPECTOR_STATE.with(|m| {
8213 m.borrow_mut().insert(
8214 ptr_of(&view),
8215 InspectorState {
8216 content_wrap,
8217 panel_wrap,
8218 _split_vc: split_vc,
8219 panel_item,
8220 },
8221 )
8222 });
8223 view
8224 }
8225 Some(Builtin::InspectorPane) => {
8226 let pane = view_of(DayNavPage::new(mtm, id));
8230 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8231 let panel = props
8232 .downcast_ref::<InspectorPaneProps>()
8233 .map(|p| p.panel)
8234 .unwrap_or(false);
8235 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8236 pane
8237 }
8238 Some(Builtin::Split) => {
8239 let (axis, fraction, min_pane) = props
8240 .downcast_ref::<SplitProps>()
8241 .map(|p| (p.axis, p.fraction, p.min_pane))
8242 .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8243 let wrap = view_of(DayFlipped::new(mtm));
8244 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8245 let first_wrap = view_of(DayFlipped::new(mtm));
8246 let second_wrap = view_of(DayFlipped::new(mtm));
8247 unsafe {
8248 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8250 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8251 split.addArrangedSubview(&first_wrap);
8252 split.addArrangedSubview(&second_wrap);
8253 split.setFrame(wrap.bounds());
8254 split.setAutoresizingMask(
8255 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8256 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8257 );
8258 wrap.addSubview(&split);
8259 }
8260 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8261 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8262 SPLIT_STATE.with(|m| {
8263 m.borrow_mut().insert(
8264 ptr_of(&wrap),
8265 SplitState {
8266 split,
8267 first_wrap,
8268 second_wrap,
8269 delegate,
8270 },
8271 )
8272 });
8273 wrap
8274 }
8275 Some(Builtin::SplitPane) => {
8276 let pane = view_of(DayNavPage::new(mtm, id));
8279 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8280 let second = props
8281 .downcast_ref::<SplitPaneProps>()
8282 .map(|p| p.second)
8283 .unwrap_or(false);
8284 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8285 pane
8286 }
8287 Some(Builtin::Nav) => {
8288 let presentation = props
8289 .downcast_ref::<NavProps>()
8290 .map(|p| p.presentation)
8291 .unwrap_or(NavPresentation::Split);
8292 let is_split = presentation.is_split();
8293 let sidebar_wrap = view_of(DayFlipped::new(mtm));
8302 let detail_wrap = view_of(DayFlipped::new(mtm));
8303 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8304 let _ = unsafe { split_vc.view() };
8310 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8313 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8314 unsafe {
8315 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8316 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8317 }
8318 let sidebar_item = unsafe {
8319 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8320 };
8321 let detail_item = unsafe {
8322 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8323 };
8324 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8330 let list_visible = props
8336 .downcast_ref::<NavProps>()
8337 .is_none_or(|p| p.list_visible);
8338 let (list_wrap, list_item) = match list_width {
8339 Some(w) => {
8340 let wrap = view_of(DayFlipped::new(mtm));
8341 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8342 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8343 let item = unsafe {
8344 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8345 };
8346 unsafe {
8347 item.setCanCollapse(true);
8348 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8349 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8350 item.setCollapsed(!list_visible);
8351 }
8352 (Some(wrap), Some(item))
8353 }
8354 None => (None, None),
8355 };
8356 unsafe {
8357 sidebar_item.setCanCollapse(is_split);
8360 sidebar_item.setCollapsed(!is_split);
8361 if is_split {
8362 sidebar_item.setAllowsFullHeightLayout(true);
8366 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8367 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8368 } else {
8369 sidebar_item.setMinimumThickness(0.0);
8370 sidebar_item.setMaximumThickness(0.0);
8371 }
8372 split_vc.addSplitViewItem(&sidebar_item);
8373 if let Some(item) = list_item.as_ref() {
8374 split_vc.addSplitViewItem(item);
8375 }
8376 split_vc.addSplitViewItem(&detail_item);
8377 }
8378 let split = unsafe { split_vc.splitView() };
8379 unsafe {
8386 let after = split.nextResponder();
8387 split.setNextResponder(Some(&split_vc));
8388 let own_view = split_vc.view();
8398 let vc_resp: *const objc2_app_kit::NSResponder = {
8399 let r: &objc2_app_kit::NSResponder = &split_vc;
8400 r
8401 };
8402 let view_resp: *const objc2_app_kit::NSResponder = {
8403 let r: &objc2_app_kit::NSResponder = &own_view;
8404 r
8405 };
8406 let upstream = after.filter(|a| {
8407 let p: *const objc2_app_kit::NSResponder = &**a;
8408 p != vc_resp && p != view_resp
8409 });
8410 split_vc.setNextResponder(upstream.as_deref());
8411 }
8412 unsafe {
8413 split.setVertical(true);
8414 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8415 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8423 }
8424 let root_title = props
8425 .downcast_ref::<NavProps>()
8426 .map(|p| p.title.clone())
8427 .unwrap_or_default();
8428 let header = if presentation == NavPresentation::Stack {
8431 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8432 } else {
8433 None
8434 };
8435 let tabs = (presentation == NavPresentation::Tabs).then(|| {
8438 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8439 let b = detail_wrap.bounds();
8444 let frame = NSRect::new(
8445 NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8446 NSSize::new(
8447 (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8448 (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8449 ),
8450 );
8451 unsafe {
8452 tv.setTabViewType(
8453 if props
8454 .downcast_ref::<NavProps>()
8455 .is_some_and(|p| p.documents.is_some())
8456 {
8457 objc2_app_kit::NSTabViewType::NoTabsNoBorder
8458 } else {
8459 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8460 },
8461 );
8462 tv.setFrame(frame);
8463 tv.setAutoresizingMask(
8464 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8465 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8466 );
8467 detail_wrap.addSubview(&tv);
8468 }
8469 TabHost {
8470 view: tv,
8471 target: None,
8472 }
8473 });
8474 let view = view_of(split);
8475 NAV_STATE.with(|m| {
8476 m.borrow_mut().insert(
8477 ptr_of(&view),
8478 NavState {
8479 sidebar_wrap,
8480 detail_wrap,
8481 _split_vc: split_vc,
8482 sidebar_item,
8483 list_wrap,
8484 list_item,
8485 pages: Vec::new(),
8486 list_page: None,
8487 sidebar_page: None,
8488 list_width,
8489 list_visible,
8490 list_positioned: false,
8491 positioned: false,
8492 presentation,
8493 selected: 0,
8494 tabs,
8495 header,
8496 root_title,
8497 node: id,
8498 title_strip: 0.0,
8499 },
8500 )
8501 });
8502 view
8503 }
8504 Some(Builtin::NavPage) => {
8505 let page = view_of(DayNavPage::new(mtm, id));
8506 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8507 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8508 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8509 }
8510 page
8511 }
8512 Some(Builtin::Cover) => {
8516 let page = DayNavPage::new(mtm, id);
8517 let cover_props = props.downcast_ref::<CoverProps>();
8518 page.ivars()
8521 .sheet
8522 .set(cover_props.is_some_and(|p| p.sheet || p.half));
8523 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8524 page.ivars().large.set(cover_props.is_some_and(|p| p.large));
8525 unsafe { page.setHidden(true) };
8526 view_of(page)
8527 }
8528 Some(Builtin::NavMenu) => {
8529 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8530 return placeholder_view(mtm, kind);
8531 };
8532 let data = DayNavMenuData::new(
8533 mtm,
8534 id,
8535 &p.items,
8536 &p.icons,
8537 &p.badges,
8538 &p.badge_icons,
8539 &p.badge_tints,
8540 &p.sections,
8541 &p.tints,
8542 &p.menus,
8543 );
8544 *data.ivars().movable.borrow_mut() = p.movable.clone();
8545 data.ivars().regroup.set(p.regroup);
8546 *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8547 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8549 let o: Retained<DayNavOutlineView> =
8550 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8551 NAV_OUTLINE_MENUS
8552 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8553 unsafe { msg_send![&*o, self] }
8554 };
8555 let col = unsafe {
8556 objc2_app_kit::NSTableColumn::initWithIdentifier(
8557 objc2_app_kit::NSTableColumn::alloc(mtm),
8558 &NSString::from_str("item"),
8559 )
8560 };
8561 unsafe {
8562 outline.addTableColumn(&col);
8563 outline.setOutlineTableColumn(Some(&col));
8564 outline.setHeaderView(None);
8565 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8578 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8583 outline.setFloatsGroupRows(true);
8586 outline.setIndentationPerLevel(0.0);
8587 outline.registerForDraggedTypes(
8590 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8591 DAY_NAV_PASTEBOARD_TYPE,
8592 )]),
8593 );
8594 outline.setDraggingSourceOperationMask_forLocal(
8595 objc2_app_kit::NSDragOperation::Move,
8596 true,
8597 );
8598 outline.setDraggingSourceOperationMask_forLocal(
8599 objc2_app_kit::NSDragOperation::None,
8600 false,
8601 );
8602 outline.setDraggingDestinationFeedbackStyle(
8603 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8604 );
8605 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8606 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8607 outline.reloadData();
8608 }
8609 let scroll = unsafe { NSScrollView::new(mtm) };
8610 unsafe {
8611 scroll.setDrawsBackground(false);
8612 scroll.setHasVerticalScroller(true);
8613 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8617 scroll.setHasHorizontalScroller(false);
8619 outline.setAutoresizingMask(
8620 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8621 );
8622 outline.setColumnAutoresizingStyle(
8623 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8624 );
8625 scroll.setDocumentView(Some(&outline));
8626 }
8627 let view = view_of(scroll);
8628 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8631 data.ivars().suppress.set(true);
8632 unsafe {
8633 outline.selectRowIndexes_byExtendingSelection(
8634 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8635 false,
8636 )
8637 };
8638 data.ivars().suppress.set(false);
8639 }
8640 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8641 view
8642 }
8643 Some(Builtin::List) => {
8644 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8645 return placeholder_view(mtm, kind);
8646 };
8647 let table: Retained<DayListView> =
8649 unsafe { msg_send![DayListView::alloc(mtm), init] };
8650 let table = Retained::into_super(table);
8651 let col = unsafe {
8652 NSTableColumn::initWithIdentifier(
8653 NSTableColumn::alloc(mtm),
8654 &NSString::from_str("day.list.col"),
8655 )
8656 };
8657 let data = DayListData::new(
8658 mtm,
8659 id,
8660 p.selectable,
8661 p.multi_select,
8662 p.row_height == RowHeight::Automatic,
8663 p.sections,
8664 );
8665 unsafe {
8666 if p.multi_select {
8667 table.setAllowsMultipleSelection(true);
8668 }
8669 table.addTableColumn(&col);
8670 table.setHeaderView(None);
8671 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8680 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8684 if p.separators == Some(true) {
8688 table.setGridStyleMask(
8689 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8690 );
8691 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8692 }
8693 table.setColumnAutoresizingStyle(
8694 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8695 );
8696 table.setFloatsGroupRows(p.sections);
8699 match p.row_height {
8700 RowHeight::Uniform(h) => table.setRowHeight(h),
8701 RowHeight::Automatic => table.setRowHeight(44.0),
8702 }
8703 if !p.selectable {
8704 table.setSelectionHighlightStyle(
8705 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8706 );
8707 }
8708 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8712 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8713 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8714 table.setTarget(Some(&*data));
8715 if p.activatable {
8716 table.setDoubleAction(Some(sel!(doubleClickRow:)));
8717 }
8718 if p.reorderable {
8719 table.registerForDraggedTypes(
8723 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8724 DAY_ROW_PASTEBOARD_TYPE,
8725 )]),
8726 );
8727 table.setDraggingSourceOperationMask_forLocal(
8728 objc2_app_kit::NSDragOperation::Move,
8729 true,
8730 );
8731 table.setDraggingSourceOperationMask_forLocal(
8732 objc2_app_kit::NSDragOperation::None,
8733 false,
8734 );
8735 table.setDraggingDestinationFeedbackStyle(
8736 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8737 );
8738 }
8739 }
8740 let scroll = unsafe { NSScrollView::new(mtm) };
8741 unsafe {
8742 scroll.setDrawsBackground(false);
8743 scroll.setHasVerticalScroller(true);
8744 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8748 scroll.setDocumentView(Some(&table));
8749 let clip = scroll.contentView();
8750 clip.setPostsBoundsChangedNotifications(true);
8751 objc2_foundation::NSNotificationCenter::defaultCenter()
8752 .addObserver_selector_name_object(
8753 &data,
8754 sel!(listViewportChanged:),
8755 Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8756 Some(&clip),
8757 );
8758 }
8759 let view = view_of(scroll);
8760 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8761 view
8762 }
8763 Some(Builtin::Tree) => {
8764 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8765 return placeholder_view(mtm, kind);
8766 };
8767 let outline: Retained<objc2_app_kit::NSOutlineView> = {
8769 let o: Retained<DayOutlineView> =
8770 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8771 unsafe { msg_send![&*o, self] }
8772 };
8773 let col = unsafe {
8774 NSTableColumn::initWithIdentifier(
8775 NSTableColumn::alloc(mtm),
8776 &NSString::from_str("day.tree.col"),
8777 )
8778 };
8779 let data = DayTreeData::new(mtm, id, p.selectable);
8780 unsafe {
8781 if p.multi_select {
8782 outline.setAllowsMultipleSelection(true);
8783 }
8784 outline.addTableColumn(&col);
8785 outline.setOutlineTableColumn(Some(&col));
8786 outline.setHeaderView(None);
8787 if p.section_headers {
8788 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8791 outline.setFloatsGroupRows(true);
8792 } else {
8793 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8796 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8797 }
8798 outline.setColumnAutoresizingStyle(
8799 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8800 );
8801 outline.setAutoresizesOutlineColumn(true);
8802 if let Some(indent) = p.indent {
8803 outline.setIndentationPerLevel(indent);
8804 }
8805 match p.row_height {
8806 RowHeight::Uniform(h) => outline.setRowHeight(h),
8807 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8808 RowHeight::Automatic => {}
8809 }
8810 if !p.selectable {
8811 outline.setSelectionHighlightStyle(
8812 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8813 );
8814 }
8815 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8816 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8817 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8818 if p.movable {
8819 outline.registerForDraggedTypes(
8824 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8825 DAY_TREE_PASTEBOARD_TYPE,
8826 )]),
8827 );
8828 outline.setDraggingSourceOperationMask_forLocal(
8829 objc2_app_kit::NSDragOperation::Move,
8830 true,
8831 );
8832 outline.setDraggingSourceOperationMask_forLocal(
8833 objc2_app_kit::NSDragOperation::None,
8834 false,
8835 );
8836 }
8837 }
8838 let scroll = unsafe { NSScrollView::new(mtm) };
8839 unsafe {
8840 scroll.setDrawsBackground(false);
8841 scroll.setHasVerticalScroller(true);
8842 scroll.setHasHorizontalScroller(false);
8843 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8844 outline.setAutoresizingMask(
8845 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8846 );
8847 scroll.setDocumentView(Some(&outline));
8848 }
8849 let view = view_of(scroll);
8850 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8851 view
8852 }
8853 Some(Builtin::Image) => {
8854 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8855 return placeholder_view(mtm, kind);
8856 };
8857 let iv: Retained<objc2_app_kit::NSImageView> =
8858 if p.content_mode == ContentMode::Fill {
8859 let view: Retained<FillImageView> =
8860 unsafe { msg_send![FillImageView::alloc(mtm), init] };
8861 Retained::from(
8862 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8863 )
8864 } else {
8865 unsafe { objc2_app_kit::NSImageView::new(mtm) }
8866 };
8867 let scaling = match p.content_mode {
8870 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8871 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8872 };
8873 unsafe { iv.setImageScaling(scaling) };
8874 if let Some(img) = appkit_image_for(&p.source) {
8875 if p.tint.is_some() || p.template {
8880 unsafe { img.setTemplate(true) };
8881 }
8882 unsafe { iv.setImage(Some(&img)) };
8883 }
8884 if let Some(t) = p.tint {
8885 unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8886 }
8887 IMAGE_MODES.with(|t| {
8888 t.insert(
8889 ptr_of(&iv),
8890 ImageMode {
8891 template: p.template,
8892 tinted: p.tint.is_some(),
8893 },
8894 )
8895 });
8896 view_of(iv)
8897 }
8898 Some(Builtin::ListItem) => {
8899 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8900 else {
8901 return placeholder_view(mtm, kind);
8902 };
8903 make_list_item(p, mtm)
8904 }
8905 Some(Builtin::ListCell) | None => {
8908 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8909 return make(self, props, id);
8910 }
8911 warn_missing_renderer(kind);
8915 placeholder_view(mtm, kind)
8916 }
8917 }
8918 }
8919
8920 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8921 match kind {
8922 kinds::LIST_ITEM => {
8923 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8924 return;
8925 };
8926 let props = LIST_ITEMS.with(|m| {
8927 let mut m = m.borrow_mut();
8928 let props = m.get_mut(&ptr_of(h))?;
8929 use day_spec::props::ListItemPatch as P;
8930 match p {
8931 P::Title(t) => props.title = t.clone(),
8932 P::Subtitle(t) => props.subtitle = t.clone(),
8933 P::Detail(t) => props.detail = t.clone(),
8934 P::Icon(i) => props.icon = i.clone(),
8935 P::IconTint(c) => props.icon_tint = *c,
8936 P::Checked(on) => props.checked = *on,
8937 }
8938 Some(props.clone())
8939 });
8940 if let Some(props) = props {
8941 dress_list_item(h, &props, self.mtm());
8942 }
8943 }
8944 kinds::IMAGE => {
8945 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8946 match p {
8947 day_spec::props::ImagePatch::Tint(c) => {
8948 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8952 let key = ptr_of(&iv);
8953 let template = IMAGE_MODES
8954 .with(|t| {
8955 t.with(key, |m| {
8956 m.tinted = c.is_some();
8957 m.renders_template()
8958 })
8959 })
8960 .unwrap_or(c.is_some());
8961 if let Some(img) = unsafe { iv.image() } {
8962 unsafe { img.setTemplate(template) };
8963 }
8964 unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8965 }
8966 }
8967 day_spec::props::ImagePatch::Source(source) => {
8971 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8972 if let Some(img) = appkit_image_for(source) {
8978 let template = IMAGE_MODES
8979 .with(|t| t.get(ptr_of(&iv)))
8980 .is_some_and(|m| m.renders_template());
8981 unsafe {
8982 img.setTemplate(template);
8983 iv.setImage(Some(&img));
8984 }
8985 }
8986 }
8987 }
8988 }
8989 }
8990 }
8991 kinds::CONTAINER => {
8992 if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8993 patch.downcast_ref::<ContainerPatch>(),
8994 h.clone().downcast::<DayFlipped>(),
8995 ) {
8996 v.set_surface(*c, 0.0, false);
9004 }
9005 }
9006 kinds::LABEL => {
9007 if let (Some(p), Ok(tf)) = (
9008 patch.downcast_ref::<LabelPatch>(),
9009 h.clone().downcast::<NSTextField>(),
9010 ) {
9011 match p {
9012 LabelPatch::Text(t) => {
9013 unsafe { tf.setStringValue(&NSString::from_str(t)) };
9014 if let Some(label) = h.downcast_ref::<DayLabel>() {
9015 label.ivars().has_runs.set(false);
9016 label.set_links(false);
9017 }
9018 }
9019 LabelPatch::Color(c) => unsafe {
9020 tf.setTextColor(c.map(nscolor).as_deref())
9021 },
9022 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9023 LabelPatch::Runs(text, runs) => {
9024 let base = unsafe { tf.font() };
9028 let s = match base.as_deref() {
9029 Some(f) => {
9030 attributed_label(text, f, None, Default::default(), runs)
9031 }
9032 None => attributed_label(
9033 text,
9034 &nsfont(day_spec::FontSpec::default()),
9035 None,
9036 Default::default(),
9037 runs,
9038 ),
9039 };
9040 unsafe { tf.setAttributedStringValue(&s) };
9041 set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9044 if let Some(label) = h.downcast_ref::<DayLabel>() {
9045 label.ivars().has_runs.set(!runs.is_empty());
9046 label.set_links(runs.iter().any(|r| r.link.is_some()));
9047 }
9048 }
9049 }
9050 }
9051 }
9052 kinds::BUTTON => {
9053 if let (Some(p), Ok(btn)) = (
9054 patch.downcast_ref::<ButtonPatch>(),
9055 h.clone().downcast::<NSButton>(),
9056 ) {
9057 match p {
9058 ButtonPatch::Content(c) => {
9059 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
9060 }
9061 ButtonPatch::Title(t) => {
9062 let style = BUTTON_STYLES
9063 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9064 .unwrap_or_default();
9065 set_button_title(&btn, t, style);
9066 }
9067 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9068 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9069 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9070 }
9071 }
9072 }
9073 kinds::TOGGLE => {
9074 if let (Some(p), Ok(sw)) = (
9075 patch.downcast_ref::<TogglePatch>(),
9076 h.clone().downcast::<NSSwitch>(),
9077 ) {
9078 match p {
9079 TogglePatch::On(on) => {
9080 let want = if *on { 1 } else { 0 };
9081 if unsafe { sw.state() } != want {
9082 unsafe { sw.setState(want) };
9083 }
9084 }
9085 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9086 }
9087 }
9088 }
9089 kinds::SLIDER => {
9090 if let (Some(p), Ok(sl)) = (
9091 patch.downcast_ref::<SliderPatch>(),
9092 h.clone().downcast::<NSSlider>(),
9093 ) {
9094 match p {
9095 SliderPatch::Value(v) => {
9096 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9097 unsafe { sl.setDoubleValue(*v) };
9098 }
9099 }
9100 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9101 }
9102 }
9103 }
9104 kinds::PROGRESS => {
9105 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9106 {
9107 crate::controls::spinner::update(self, h, p);
9108 return;
9109 }
9110
9111 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9112 patch.downcast_ref::<ProgressPatch>(),
9113 h.clone().downcast::<NSProgressIndicator>(),
9114 ) {
9115 unsafe {
9116 match v {
9117 Some(val) => {
9118 if pi.isIndeterminate() {
9119 pi.stopAnimation(None);
9120 pi.setIndeterminate(false);
9121 pi.setStyle(NSProgressIndicatorStyle::Bar);
9122 pi.setMinValue(0.0);
9123 pi.setMaxValue(1.0);
9124 }
9125 if (pi.doubleValue() - val).abs() > 0.0001 {
9126 pi.setDoubleValue(*val);
9127 }
9128 }
9129 None => {
9130 pi.setIndeterminate(true);
9131 pi.setStyle(NSProgressIndicatorStyle::Spinning);
9132 pi.startAnimation(None);
9133 }
9134 }
9135 }
9136 }
9137 }
9138 kinds::NAV_MENU => {
9139 if let Some(NavMenuPatch::Items {
9140 items,
9141 icons,
9142 badges,
9143 badge_icons,
9144 badge_tints,
9145 sections,
9146 tints,
9147 menus,
9148 movable,
9149 sorted,
9150 selected,
9151 rows_changed,
9152 ..
9153 }) = patch.downcast_ref::<NavMenuPatch>()
9154 {
9155 NAV_MENUS.with(|m| {
9156 let m = m.borrow();
9157 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9158 return;
9159 };
9160 *data.ivars().movable.borrow_mut() = movable.clone();
9161 *data.ivars().sorted.borrow_mut() = sorted.clone();
9162 data.set_items(
9163 items,
9164 icons,
9165 badges,
9166 badge_icons,
9167 badge_tints,
9168 sections,
9169 tints,
9170 menus,
9171 );
9172 data.ivars().suppress.set(true);
9173 if let Some(rows) = rows_changed {
9176 let set = objc2_foundation::NSMutableIndexSet::new();
9177 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9178 unsafe { set.addIndex(row) };
9179 }
9180 unsafe {
9181 outline.reloadDataForRowIndexes_columnIndexes(
9182 &set,
9183 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9184 )
9185 };
9186 data.ivars().suppress.set(false);
9187 return;
9188 }
9189 unsafe {
9190 outline.reloadData();
9191 match selected.and_then(|i| data.row_of_item(i)) {
9192 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9193 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9194 false,
9195 ),
9196 None => outline.deselectAll(None),
9197 }
9198 }
9199 data.ivars().suppress.set(false);
9200 });
9201 adopt_menu_for_tabs(self.mtm(), h);
9203 } else if let Some(NavMenuPatch::IconProgress(progress)) =
9204 patch.downcast_ref::<NavMenuPatch>()
9205 {
9206 NAV_MENUS.with(|menus| {
9207 let menus = menus.borrow();
9208 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9209 return;
9210 };
9211 let previous = data.ivars().icon_progress.replace(progress.clone());
9212 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9213 let Some(index) = item else {
9214 continue;
9215 };
9216 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9217 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9218 continue;
9219 }
9220 if let Some(view) = unsafe {
9221 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9222 } && let Some(cell) =
9223 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9224 && let Some(icon) = unsafe { cell.imageView() }
9225 {
9226 nav_progress::update(&icon, value);
9227 }
9228 }
9229 });
9230 } else if let Some(NavMenuPatch::Selected(sel)) =
9231 patch.downcast_ref::<NavMenuPatch>()
9232 {
9233 NAV_MENUS.with(|m| {
9234 let m = m.borrow();
9235 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9236 return;
9237 };
9238 data.ivars().suppress.set(true);
9239 unsafe {
9240 match sel.and_then(|i| data.row_of_item(i)) {
9241 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9242 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9243 false,
9244 ),
9245 None => outline.deselectAll(None),
9246 }
9247 }
9248 data.ivars().suppress.set(false);
9249 });
9250 }
9251 }
9252 kinds::INSPECTOR => {
9253 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9254 INSPECTOR_STATE.with(|m| {
9255 if let Some(state) = m.borrow().get(&ptr_of(h)) {
9256 state.panel_item.setCollapsed(!*v);
9259 }
9260 });
9261 }
9262 }
9263 kinds::SPLIT => {
9264 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9265 SPLIT_STATE.with(|m| {
9266 let m = m.borrow();
9267 let Some(state) = m.get(&ptr_of(h)) else {
9268 return;
9269 };
9270 let iv = state.delegate.ivars();
9271 match p {
9272 SplitPatch::Fraction(f) => {
9273 iv.share.set(f.clamp(0.0, 1.0));
9274 if iv.positioned.get() {
9275 split_place(&state.split, iv);
9276 }
9277 }
9278 SplitPatch::Axis(axis) => unsafe {
9279 state
9280 .split
9281 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9282 state.split.adjustSubviews();
9283 if iv.positioned.get() {
9284 split_place(&state.split, iv);
9285 }
9286 },
9287 }
9288 });
9289 }
9290 }
9291 kinds::NAV => {
9292 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9293 nav_present(self.mtm(), h, *next);
9294 return;
9295 }
9296 if let Some(p) = patch.downcast_ref::<NavPatch>() {
9297 NAV_STATE.with(|m| {
9298 let mut m = m.borrow_mut();
9299 let Some(state) = m.get_mut(&ptr_of(h)) else {
9300 return;
9301 };
9302 match p {
9303 NavPatch::Pushed { title, .. } => {
9304 let last = state.pages.len().saturating_sub(1);
9306 state.selected = last;
9307 for (i, page) in state.pages.iter().enumerate() {
9308 page.setHidden(i != last);
9309 }
9310 if let Some(hdr) = state.header.as_mut() {
9311 hdr.titles.push(title.clone());
9312 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9313 }
9314 }
9315 NavPatch::Popped => {
9316 let n = state.pages.len();
9319 if let Some(top) = state.pages.last() {
9320 top.setHidden(true);
9321 }
9322 if n >= 2 {
9323 state.pages[n - 2].setHidden(false);
9324 }
9325 state.selected = n.saturating_sub(2);
9326 if let Some(hdr) = state.header.as_mut() {
9327 if hdr.titles.len() > 1 {
9328 hdr.titles.pop();
9329 }
9330 let after: Vec<Retained<NSView>> = state
9333 .pages
9334 .iter()
9335 .take(n.saturating_sub(1))
9336 .cloned()
9337 .collect();
9338 sync_nav_header(hdr, &state.detail_wrap, &after);
9339 }
9340 }
9341 NavPatch::Title(t) => {
9342 if let Some(hdr) = state.header.as_mut() {
9343 if let Some(last) = hdr.titles.last_mut() {
9344 *last = t.clone();
9345 }
9346 unsafe {
9347 hdr.title.setStringValue(&NSString::from_str(t));
9348 }
9349 }
9350 }
9351 NavPatch::GuardTop(_) => {}
9355 NavPatch::Reorder(order) => {
9356 let old = state.pages.clone();
9357 state.pages =
9358 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9359 if let Some(tabs) = &state.tabs {
9360 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9361 unsafe {
9362 let items = tabs.view.tabViewItems();
9363 for item in items.iter() {
9364 tabs.view.removeTabViewItem(&item);
9365 }
9366 for i in order {
9367 if let Some(item) = items.iter().nth(*i) {
9368 tabs.view.addTabViewItem(&item);
9369 }
9370 }
9371 }
9372 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9373 }
9374 }
9375 NavPatch::Presentation(_) => {}
9377 NavPatch::Select(i) => {
9381 state.selected = *i;
9382 match state.tabs.as_ref() {
9383 Some(tabs) => {
9385 let n = unsafe { tabs.view.numberOfTabViewItems() };
9386 if (*i as isize) < n {
9387 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9388 unsafe {
9389 tabs.view.selectTabViewItemAtIndex(*i as isize)
9390 };
9391 TAB_PICK_SUPPRESS.with(|s| s.set(false));
9392 }
9393 }
9394 None => {
9395 for (n, page) in state.pages.iter().enumerate() {
9396 page.setHidden(n != *i);
9397 }
9398 }
9399 }
9400 }
9401 NavPatch::ListVisible(v) => {
9407 state.list_visible = *v;
9408 if let Some(item) = state.list_item.as_ref() {
9409 item.setCollapsed(!*v);
9410 let split = unsafe { state._split_vc.splitView() };
9411 unsafe { split.layoutSubtreeIfNeeded() };
9412 if let Some(w) = take_list_placement(state) {
9417 unsafe {
9418 split.setPosition_ofDividerAtIndex(
9419 day_spec::NAV_SIDEBAR_WIDTH + w,
9420 1,
9421 );
9422 }
9423 }
9424 if *v
9431 && let Some(wrap) = state.list_wrap.as_ref()
9432 && let Some(page) = state.list_page.as_ref()
9433 {
9434 unsafe {
9435 wrap.layoutSubtreeIfNeeded();
9436 page.setFrame(wrap.bounds());
9437 }
9438 }
9439 }
9440 }
9441 NavPatch::ListInStack(_) => {}
9445 }
9446 });
9447 }
9448 }
9449 kinds::COVER => {
9455 if let (Some(p), Ok(page)) = (
9456 patch.downcast_ref::<CoverPatch>(),
9457 h.clone().downcast::<DayNavPage>(),
9458 ) {
9459 let node = page.ivars().node;
9460 match p {
9461 CoverPatch::Present { background, .. } => {
9462 if page.ivars().sheet.get() {
9463 if let Some(parent) =
9464 primary_content().and_then(|v| unsafe { v.window() })
9465 {
9466 let bounds = parent.frame().size;
9467 let max = if page.ivars().large.get() {
9468 day_spec::props::LARGE_SHEET_MAX
9469 } else {
9470 day_spec::props::SHEET_MAX
9471 };
9472 let height = if page.ivars().half.get() {
9473 (bounds.height * 0.5).clamp(160.0, max.height)
9474 } else {
9475 (bounds.height - 80.0).clamp(300.0, max.height)
9476 };
9477 let size = NSSize::new(
9478 (bounds.width - 40.0).clamp(320.0, max.width),
9479 height,
9480 );
9481 let window = unsafe {
9482 NSWindow::initWithContentRect_styleMask_backing_defer(
9483 NSWindow::alloc(MainThreadMarker::new().unwrap()),
9484 NSRect::new(NSPoint::new(0.0, 0.0), size),
9485 NSWindowStyleMask::Titled,
9486 NSBackingStoreType::Buffered,
9487 false,
9488 )
9489 };
9490 unsafe {
9491 window.setReleasedWhenClosed(false);
9492 page.removeFromSuperview();
9493 page.setHidden(false);
9494 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9495 window.setContentView(Some(&page));
9496 }
9497 let key = ptr_of(h);
9498 SHEET_NODES.with(|t| {
9499 t.insert(Retained::as_ptr(&window) as usize, node)
9500 });
9501 install_sheet_escape_monitor();
9502 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9503 dispatch2::DispatchQueue::main().exec_async(move || {
9504 ffi_guard::contain((), || {
9505 let window =
9506 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9507 if let (Some(window), Some(parent)) = (
9508 window,
9509 primary_content()
9510 .and_then(|v| unsafe { v.window() }),
9511 ) {
9512 unsafe {
9513 parent.beginSheet_completionHandler(
9514 &window, None,
9515 );
9516 }
9517 }
9518 });
9519 });
9520 emit(
9521 node,
9522 Event::FrameChanged(Size::new(size.width, size.height)),
9523 );
9524 }
9525 return;
9526 }
9527 unsafe {
9531 page.setWantsLayer(true);
9532 if let Some(layer) = page.layer() {
9533 let color = match background {
9534 Some(bg) => nscolor(*bg),
9535 None => NSColor::windowBackgroundColor(),
9536 };
9537 layer.setBackgroundColor(Some(&color.CGColor()));
9538 }
9539 }
9540 if let Some(content) = primary_content() {
9543 if let Some(window) = unsafe { content.window() } {
9544 toolbar::cover_presented(ptr_of(h), &window);
9545 }
9546 let top = title_bar_inset(&content);
9551 let full = content.frame().size;
9552 page.ivars().top_inset.set(top);
9553 unsafe {
9554 page.removeFromSuperview();
9555 content.addSubview(&page);
9556 page.setFrame(NSRect::new(
9557 NSPoint::new(0.0, -top),
9558 NSSize::new(full.width, full.height),
9559 ));
9560 page.setBoundsOrigin(NSPoint::new(0.0, -top));
9561 page.setAutoresizingMask(
9562 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9563 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9564 );
9565 page.setHidden(false);
9566 }
9567 emit(
9568 node,
9569 Event::FrameChanged(Size::new(
9570 full.width,
9571 (full.height - top).max(0.0),
9572 )),
9573 );
9574 }
9575 }
9576 CoverPatch::DismissDisabled(_) => {}
9577 CoverPatch::Dismiss => {
9578 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9579 toolbar::cover_dismissed(ptr_of(h));
9580 unsafe {
9581 page.setHidden(true);
9582 page.removeFromSuperview();
9583 }
9584 emit(node, Event::CoverHidden);
9585 }
9586 }
9587 }
9588 }
9589 kinds::PICKER => picker::update_any(self, h, patch),
9590 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9591 kinds::TEXT_FIELD => {
9592 if let (Some(p), Ok(tf)) = (
9593 patch.downcast_ref::<TextFieldPatch>(),
9594 h.clone().downcast::<NSTextField>(),
9595 ) {
9596 match p {
9597 TextFieldPatch::Text { text, from_native } => {
9598 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9600 unsafe { tf.setStringValue(&NSString::from_str(text)) };
9601 }
9602 }
9603 TextFieldPatch::Placeholder(t) => unsafe {
9604 tf.setPlaceholderString(Some(&NSString::from_str(t)))
9605 },
9606 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9607 }
9608 }
9609 }
9610 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9611 Some(ListPatch::Splice(deltas)) => {
9612 if let Some((table, data)) = list_entry(ptr_of(h)) {
9618 use objc2_app_kit::NSTableViewAnimationOptions;
9619 for d in deltas {
9620 unsafe {
9621 table.beginUpdates();
9622 match d {
9623 day_spec::props::RowDelta::Insert(i) => table
9624 .insertRowsAtIndexes_withAnimation(
9625 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9626 NSTableViewAnimationOptions::SlideDown,
9627 ),
9628 day_spec::props::RowDelta::Remove(i) => table
9629 .removeRowsAtIndexes_withAnimation(
9630 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9631 NSTableViewAnimationOptions::SlideUp,
9632 ),
9633 day_spec::props::RowDelta::Move(from, to) => {
9634 table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9635 }
9636 }
9637 table.endUpdates();
9638 }
9639 }
9640 if let Some(source) = data.ivars().source.borrow().as_ref() {
9644 let n = (source.len)();
9645 *data.ivars().tokens.borrow_mut() =
9646 (0..n).map(|i| (source.token_at)(i)).collect();
9647 }
9648 }
9649 post_realize_visible_rows(ptr_of(h));
9650 }
9651 Some(ListPatch::Reload) => {
9652 if let Some((table, data)) = list_entry(ptr_of(h)) {
9653 let selected = unsafe { table.selectedRowIndexes() };
9657 let tokens: Vec<u64> = data
9658 .ivars()
9659 .tokens
9660 .borrow()
9661 .iter()
9662 .enumerate()
9663 .filter(|(row, _)| selected.containsIndex(*row))
9664 .map(|(_, token)| *token)
9665 .collect();
9666 data.ivars().suppress.set(true);
9667 if let Some(moves) = data.permutation_moves(&table) {
9674 unsafe {
9675 table.beginUpdates();
9676 for (from, to) in moves {
9677 table.moveRowAtIndex_toIndex(from as isize, to as isize);
9678 }
9679 table.endUpdates();
9680 }
9681 } else {
9682 unsafe { table.reloadData() };
9683 }
9684 let restored = objc2_foundation::NSMutableIndexSet::new();
9685 for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9686 if tokens.contains(token) {
9687 restored.addIndex(row);
9688 }
9689 }
9690 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9691 data.ivars().suppress.set(false);
9692 }
9693 post_realize_visible_rows(ptr_of(h));
9699 }
9700 Some(ListPatch::ScrollToRow(row)) => {
9701 let (key, row) = (ptr_of(h), *row);
9704 <AppKit as Platform>::post(Box::new(move || {
9705 if let Some((table, _)) = list_entry(key) {
9706 let rows = unsafe { table.numberOfRows() };
9707 if rows > 0 {
9708 unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9709 }
9710 }
9711 }));
9712 post_realize_visible_rows(ptr_of(h));
9713 }
9714 Some(ListPatch::ScrollToEnd) => {
9715 let key = ptr_of(h);
9720 <AppKit as Platform>::post(Box::new(move || {
9721 if let Some((table, _)) = list_entry(key) {
9722 let rows = unsafe { table.numberOfRows() };
9723 if rows > 0 {
9724 unsafe { table.scrollRowToVisible(rows - 1) };
9725 }
9726 }
9727 }));
9728 post_realize_visible_rows(ptr_of(h));
9730 }
9731 Some(ListPatch::Selected(rows)) => {
9732 if let Some((table, data)) = list_entry(ptr_of(h)) {
9735 data.ivars().suppress.set(true);
9736 unsafe {
9737 if rows.is_empty() {
9738 table.deselectAll(None);
9739 } else {
9740 let set = objc2_foundation::NSMutableIndexSet::new();
9741 let count = table.numberOfRows().max(0) as usize;
9742 for r in rows.iter().copied().filter(|r| *r < count) {
9743 set.addIndex(r);
9744 }
9745 table.selectRowIndexes_byExtendingSelection(&set, false);
9746 }
9747 }
9748 data.ivars().suppress.set(false);
9749 }
9750 }
9751 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9752 if let Some((table, data)) = list_entry(ptr_of(h)) {
9753 data.row_resized(&table, *cell, *height);
9754 }
9755 }
9756 Some(ListPatch::Editing(_)) | None => {}
9759 },
9760 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9761 Some(TreePatch::Reload) => {
9762 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9767 unsafe { outline.reloadData() };
9768 }
9769 post_realize_visible_tree_rows(ptr_of(h));
9770 }
9771 Some(TreePatch::Expand(token, on)) => {
9772 let (key, token, on) = (ptr_of(h), *token, *on);
9777 <AppKit as Platform>::post(Box::new(move || {
9778 if let Some((outline, data)) = tree_entry(key) {
9779 let item = data.intern(token);
9780 data.ivars().suppress.set(true);
9783 unsafe {
9784 if on {
9785 outline.expandItem(Some(&item));
9786 } else {
9787 outline.collapseItem(Some(&item));
9788 }
9789 }
9790 data.ivars().suppress.set(false);
9791 }
9792 day_core::pump_events();
9793 }));
9794 post_realize_visible_tree_rows(ptr_of(h));
9795 }
9796 Some(TreePatch::Selected(tokens)) => {
9797 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9798 data.ivars().suppress.set(true);
9799 unsafe {
9800 if tokens.is_empty() {
9801 outline.deselectAll(None);
9802 } else {
9803 let set = objc2_foundation::NSMutableIndexSet::new();
9804 for t in tokens {
9805 let row = outline.rowForItem(Some(&data.intern(*t)));
9808 if row >= 0 {
9809 set.addIndex(row as usize);
9810 }
9811 }
9812 outline.selectRowIndexes_byExtendingSelection(&set, false);
9813 }
9814 }
9815 data.ivars().suppress.set(false);
9816 }
9817 }
9818 Some(TreePatch::Reveal(token)) => {
9819 let (key, token) = (ptr_of(h), *token);
9822 <AppKit as Platform>::post(Box::new(move || {
9823 if let Some((outline, data)) = tree_entry(key) {
9824 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9825 if row >= 0 {
9826 unsafe { outline.scrollRowToVisible(row) };
9827 }
9828 }
9829 }));
9830 post_realize_visible_tree_rows(ptr_of(h));
9831 }
9832 None => {}
9833 },
9834 _ => {
9835 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9836 update(self, h, patch);
9837 }
9838 }
9839 }
9840 }
9841
9842 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9844 let f = self.registry.get(kind).and_then(|r| r.release);
9847 if let Some(f) = f {
9848 f(self, h);
9849 }
9850 }
9851 fn release(&mut self, h: Handle) {
9852 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9853 self.secondary.retain(|w| {
9857 if ptr_of(&w.content) == ptr_of(&h) {
9858 w.window.close();
9859 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9863 false
9864 } else {
9865 true
9866 }
9867 });
9868 TARGETS.with(|m| {
9869 m.borrow_mut().remove(&ptr_of(&h));
9870 });
9871 LIST_STATE.with(|m| {
9872 m.borrow_mut().remove(&ptr_of(&h));
9873 });
9874 TREE_STATE.with(|m| {
9875 m.borrow_mut().remove(&ptr_of(&h));
9876 });
9877 GESTURES.with(|m| {
9878 m.borrow_mut().remove(&ptr_of(&h));
9879 });
9880 NAV_STATE.with(|m| {
9881 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9882 unsafe {
9890 nav._split_vc.setNextResponder(None);
9891 let split = nav._split_vc.splitView();
9892 if split.nextResponder().is_some_and(|r| {
9893 core::ptr::eq::<objc2::runtime::AnyObject>(
9894 r.as_ref(),
9895 nav._split_vc.as_ref(),
9896 )
9897 }) {
9898 split.setNextResponder(None);
9899 }
9900 }
9901 }
9902 });
9903 NAV_PAGES.with(|set| {
9904 set.borrow_mut().remove(&ptr_of(&h));
9905 });
9906 SPLIT_STATE.with(|m| {
9907 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9908 state.split.setDelegate(None);
9909 }
9910 });
9911 INSPECTOR_STATE.with(|m| {
9912 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9913 unsafe {
9916 insp._split_vc.setNextResponder(None);
9917 let split = insp._split_vc.splitView();
9918 if split.nextResponder().is_some_and(|r| {
9919 core::ptr::eq::<objc2::runtime::AnyObject>(
9920 r.as_ref(),
9921 insp._split_vc.as_ref(),
9922 )
9923 }) {
9924 split.setNextResponder(None);
9925 }
9926 }
9927 }
9928 });
9929 NAV_MENUS.with(|m| {
9930 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9931 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9936 }
9937 });
9938 day_spec::sidetable::sweep(ptr_of(&h));
9944 unsafe { h.removeFromSuperview() };
9945 }
9946
9947 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9948 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9952 unsafe { content_of(parent).addSubview(child) };
9953 adopt_menu_for_tabs(self.mtm(), child);
9954 return;
9955 }
9956 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9959 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9960 let handled = NAV_STATE.with(|m| {
9961 let mut m = m.borrow_mut();
9962 let Some(state) = m.get_mut(&ptr_of(parent)) else {
9963 return false;
9964 };
9965 if page_pane == Some(day_spec::props::Pane::List)
9968 && let Some(wrap) = state.list_wrap.as_ref()
9969 {
9970 state.list_page = Some(child.clone());
9971 unsafe {
9972 child.setFrame(wrap.bounds());
9973 child.setAutoresizingMask(
9974 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9975 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9976 );
9977 wrap.addSubview(child);
9978 }
9979 return true;
9980 }
9981 if is_sidebar_page {
9982 state.sidebar_page = Some(child.clone());
9983 }
9984 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9990 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9995 state.pages.push(child.clone());
9996 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9997 unsafe {
9998 child.setAutoresizingMask(
9999 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10000 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10001 );
10002 item.setView(Some(child));
10003 tabs.view.addTabViewItem(&item);
10004 }
10005 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10006 sync_tab_labels(tabs, &titles, state.selected);
10007 }
10008 return true;
10009 }
10010 let (wrap, frame) = if to_pane {
10011 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10012 } else {
10013 state.pages.push(child.clone());
10014 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10015 (
10016 &state.detail_wrap,
10017 nav_page_frame(&state.detail_wrap, visible),
10018 )
10019 };
10020 unsafe {
10021 child.setFrame(frame);
10022 child.setAutoresizingMask(
10023 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10024 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10025 );
10026 wrap.addSubview(child);
10027 }
10028 true
10029 });
10030 if handled {
10031 return;
10032 }
10033 let split_pane = SPLIT_STATE.with(|m| {
10036 let m = m.borrow();
10037 let Some(state) = m.get(&ptr_of(parent)) else {
10038 return false;
10039 };
10040 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10041 let wrap = if second {
10042 &state.second_wrap
10043 } else {
10044 &state.first_wrap
10045 };
10046 unsafe {
10047 child.setFrame(wrap.bounds());
10048 child.setAutoresizingMask(
10049 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10050 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10051 );
10052 wrap.addSubview(child);
10053 }
10054 true
10055 });
10056 if split_pane {
10057 return;
10058 }
10059 let inspected = INSPECTOR_STATE.with(|m| {
10062 let m = m.borrow();
10063 let Some(state) = m.get(&ptr_of(parent)) else {
10064 return false;
10065 };
10066 let panel = INSPECTOR_PANES
10067 .with(|t| t.get(ptr_of(child)))
10068 .unwrap_or(false);
10069 let wrap = if panel {
10070 &state.panel_wrap
10071 } else {
10072 &state.content_wrap
10073 };
10074 unsafe {
10075 child.setFrame(wrap.bounds());
10076 child.setAutoresizingMask(
10077 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10078 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10079 );
10080 wrap.addSubview(child);
10081 }
10082 true
10083 });
10084 if !inspected {
10085 unsafe { content_of(parent).addSubview(child) };
10088 }
10089 }
10090
10091 fn remove(&mut self, parent: &Handle, child: &Handle) {
10092 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10093 let mtm = self.mtm();
10094 NAV_STATE.with(|m| {
10095 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10096 if let Some(tabs) = state.tabs.as_ref() {
10098 unsafe {
10099 let n = tabs.view.numberOfTabViewItems();
10100 for i in 0..n {
10101 let item = tabs.view.tabViewItemAtIndex(i);
10102 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10103 tabs.view.removeTabViewItem(&item);
10104 break;
10105 }
10106 }
10107 }
10108 }
10109 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10110 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10111 state.sidebar_page = None;
10112 }
10113 }
10114 });
10115 unsafe { child.removeFromSuperview() };
10116 }
10117
10118 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10119 unsafe { content_of(parent).addSubview(child) };
10120 }
10121
10122 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10123 match kind {
10124 kinds::LABEL => {
10125 if let Some(tf) = h.downcast_ref::<NSTextField>() {
10126 let w = p.width.unwrap_or(1.0e6);
10127 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10129 let mut height = s.height.ceil();
10130 if tf.maximumNumberOfLines() == 1 {
10133 thread_local! {
10134 static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10135 }
10136 if let Some(font) = unsafe { tf.font() } {
10137 height = height.min(
10138 METRICS
10139 .with(|metrics| metrics.defaultLineHeightForFont(&font))
10140 .ceil(),
10141 );
10142 }
10143 }
10144 return Size::new(s.width.ceil().min(w), height);
10145 }
10146 Size::ZERO
10147 }
10148 kinds::BUTTON | kinds::TOGGLE => {
10149 let s = unsafe { h.fittingSize() };
10150 Size::new(s.width.ceil(), s.height.ceil())
10151 }
10152 kinds::SLIDER => {
10153 let s = unsafe { h.fittingSize() };
10154 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10155 }
10156 kinds::PICKER => picker::measure_any(self, h, p),
10157 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10158 kinds::TEXT_FIELD => {
10159 let s = unsafe { h.fittingSize() };
10160 Size::new(
10161 p.width.unwrap_or(s.width.max(160.0)),
10162 s.height.max(22.0).ceil(),
10163 )
10164 }
10165 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10166 kinds::LIST_ITEM => {
10169 let s = h.fittingSize();
10170 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10171 }
10172 kinds::PROGRESS => {
10173 let indeterminate = h
10175 .clone()
10176 .downcast::<NSProgressIndicator>()
10177 .map(|pi| unsafe { pi.isIndeterminate() })
10178 .unwrap_or(false);
10179 if indeterminate {
10180 let large = h
10181 .downcast_ref::<NSProgressIndicator>()
10182 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10183 let side = if large { 32.0 } else { 20.0 };
10184 Size::new(side, side)
10185 } else {
10186 Size::new(p.width.unwrap_or(180.0), 20.0)
10187 }
10188 }
10189 kinds::NAV_MENU => {
10190 let rows = NAV_MENUS.with(|m| {
10191 m.borrow()
10192 .get(&ptr_of(h))
10193 .map(|(_, d)| d.ivars().items.borrow().len())
10194 .unwrap_or(0)
10195 });
10196 Size::new(
10197 p.width.unwrap_or(220.0),
10198 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10199 )
10200 }
10201 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10203 _ => {
10204 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10205 measure(self, h, p)
10206 } else {
10207 let s = unsafe { h.fittingSize() };
10208 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10209 }
10210 }
10211 }
10212 }
10213
10214 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10215 unsafe {
10216 h.setWantsLayer(true);
10217 }
10218 let v = h.clone();
10219 with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10220 }
10221
10222 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10223 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10226 let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10227 let v = h.clone();
10228 with_appkit_anim(anim, move || {
10229 if let Some(base) = base {
10230 apply_geometry(&v, base, t);
10231 }
10232 });
10233 }
10234
10235 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10236 if let Some(label) = h.downcast_ref::<DayLabel>() {
10237 label.ivars().selectable.set(selectable);
10238 label.set_links(label.ivars().has_links.get());
10239 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10240 unsafe { tf.setSelectable(selectable) };
10241 }
10242 None
10243 }
10244
10245 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10246 let node = text_field_node(h)?;
10247 let old = h.downcast_ref::<NSTextField>()?;
10248 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10251 .then(|| self.swap_text_field(h, old, node, traits.secure));
10252 let tf = swapped.as_deref().unwrap_or(old);
10253 unsafe {
10254 tf.setEditable(!traits.read_only);
10257 tf.setSelectable(true);
10258 }
10259 let content_type = match traits.purpose {
10263 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10264 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10265 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10266 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10267 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10268 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10269 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10270 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10271 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10272 };
10273 unsafe {
10274 tf.setContentType(content_type);
10275 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10278 }
10279 swapped.map(view_of)
10282 }
10283
10284 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10285 let key = Retained::as_ptr(h) as usize;
10286 if cursor == Cursor::Default {
10287 if let Some((owner, area)) = self.cursors.remove(&key) {
10289 unsafe { h.removeTrackingArea(&area) };
10290 if owner.ivars().hiding.replace(false) {
10291 NSCursor::unhide();
10292 }
10293 }
10294 return;
10295 }
10296 let hidden = cursor == Cursor::None;
10297 let shape = if hidden { None } else { ns_cursor(&cursor) };
10298 let mtm = self.mtm;
10299 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10300 let owner = DayCursorOwner::new(mtm);
10301 let opts = NSTrackingAreaOptions::CursorUpdate
10304 | NSTrackingAreaOptions::MouseEnteredAndExited
10305 | NSTrackingAreaOptions::ActiveInKeyWindow
10306 | NSTrackingAreaOptions::InVisibleRect;
10307 let any: &objc2::runtime::AnyObject = &owner;
10308 let area = unsafe {
10309 NSTrackingArea::initWithRect_options_owner_userInfo(
10310 NSTrackingArea::alloc(),
10311 NSRect::ZERO,
10312 opts,
10313 Some(any),
10314 None,
10315 )
10316 };
10317 unsafe { h.addTrackingArea(&area) };
10318 (owner, area)
10319 });
10320 let changed = {
10321 let iv = owner.ivars();
10322 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10323 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10324 (None, None) => true,
10325 _ => false,
10326 };
10327 *iv.cursor.borrow_mut() = shape;
10328 let was_hidden = iv.hidden.replace(hidden);
10329 !same || was_hidden != hidden
10330 };
10331 if changed && let Some(w) = h.window() {
10334 unsafe { w.invalidateCursorRectsForView(h) };
10335 }
10336 }
10337
10338 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10352 if !day_spec::kind_has_baseline(kind) {
10353 return None;
10354 }
10355 let current = unsafe { h.frame() };
10358 if (current.size.height - size.height).abs() > 0.5 {
10359 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10360 }
10361 let insets = unsafe { h.alignmentRectInsets() };
10362 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10363 let font = h
10364 .downcast_ref::<NSControl>()
10365 .and_then(|c| unsafe { c.font() });
10366 let offset = match font {
10367 Some(_) if kind == kinds::TEXT_AREA => reported,
10370 Some(f) => {
10371 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10372 let line = ascender - descender;
10373 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10374 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10375 }
10376 None => reported,
10377 };
10378 (offset > 0.0 && offset < size.height).then_some(offset)
10380 }
10381
10382 fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10383 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10385 return;
10386 }
10387 let r = NSRect::new(
10390 NSPoint::new(frame.origin.x, frame.origin.y),
10391 NSSize::new(frame.size.width, frame.size.height),
10392 );
10393 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10398 let strip = unsafe { split.superview() }
10402 .and_then(|sup| {
10403 let content = unsafe { sup.window() }?.contentView()?;
10404 let mut ancestor = Some(sup.clone());
10408 while let Some(view) = ancestor {
10409 if std::ptr::eq(&*view, &*content) {
10410 break;
10411 }
10412 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10413 return None; }
10415 ancestor = unsafe { view.superview() };
10416 }
10417 let point = unsafe {
10418 sup.convertPoint_toView(
10419 NSPoint::new(frame.origin.x, frame.origin.y),
10420 Some(&content),
10421 )
10422 };
10423 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10424 })
10425 .unwrap_or(0.0);
10426 let r = NSRect::new(
10427 NSPoint::new(r.origin.x, r.origin.y - strip),
10428 NSSize::new(r.size.width, r.size.height + strip),
10429 );
10430 let wraps = NAV_STATE.with(|m| {
10431 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10432 (s.title_strip != strip).then(|| {
10433 s.title_strip = strip;
10434 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10435 w.extend(s.list_wrap.clone());
10436 w
10437 })
10438 })
10439 });
10440 let first = NAV_STATE.with(|m| {
10441 m.borrow_mut()
10442 .get_mut(&ptr_of(h))
10443 .map(|s| {
10444 if !s.presentation.is_split() {
10445 return (false, None);
10446 }
10447 let sidebar = !std::mem::replace(&mut s.positioned, true);
10448 (sidebar, take_list_placement(s))
10453 })
10454 .unwrap_or((false, None))
10455 });
10456 unsafe {
10457 split.setFrame(r);
10458 split.layoutSubtreeIfNeeded();
10459 }
10460 for wrap in wraps.iter().flatten() {
10463 place_below_strip(wrap, strip);
10464 }
10465 unsafe {
10466 if first.0 {
10467 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10468 }
10469 if let Some(w) = first.1 {
10474 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10475 }
10476 }
10477 } else {
10478 BASE_FRAMES.with(|m| {
10479 m.insert(
10480 ptr_of(h),
10481 [
10482 frame.origin.x,
10483 frame.origin.y,
10484 frame.size.width,
10485 frame.size.height,
10486 ],
10487 )
10488 });
10489 match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10491 Some(t) => apply_geometry(
10492 h,
10493 [
10494 frame.origin.x,
10495 frame.origin.y,
10496 frame.size.width,
10497 frame.size.height,
10498 ],
10499 t,
10500 ),
10501 None => unsafe { h.setFrame(r) },
10502 }
10503 }
10504 }
10505
10506 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10507 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10508 && let Some(doc) = unsafe { sv.documentView() }
10509 {
10510 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10511 }
10512 }
10513
10514 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10516 day_spec::RowMetrics {
10517 insets: day_spec::Insets {
10518 top: 4.0,
10519 leading: 8.0,
10520 bottom: 4.0,
10521 trailing: 8.0,
10522 },
10523 min_height: 28.0,
10524 }
10525 }
10526
10527 fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10528 if let Some(sv) = h.downcast_ref::<NSScrollView>()
10529 && let Some(doc) = unsafe { sv.documentView() }
10530 {
10531 unsafe {
10532 doc.scrollRectToVisible(NSRect::new(
10533 NSPoint::new(target.origin.x, target.origin.y),
10534 NSSize::new(target.size.width, target.size.height),
10535 ))
10536 };
10537 }
10538 }
10539
10540 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10541 let Some(window) = h.window() else { return };
10542 let list = list_entry(ptr_of(h));
10544 let responder: &NSResponder = match &list {
10545 Some((table, _)) => table,
10546 None => h,
10547 };
10548 let responder_ptr = responder as *const NSResponder as usize;
10549 if focused {
10550 window.makeFirstResponder(Some(responder));
10551 return;
10552 }
10553 let owns = window
10556 .firstResponder()
10557 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10558 || owns_first_responder(&window, h);
10559 if owns {
10560 window.makeFirstResponder(None);
10561 }
10562 }
10563
10564 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10565 if focusable {
10568 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10569 } else {
10570 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10571 }
10572 }
10573
10574 fn set_event_sink(&mut self, sink: EventSink) {
10575 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10576 }
10577
10578 fn set_edit_state(&mut self, state: &day_spec::EditState) {
10579 EDIT_STATE.with(|s| s.set(*state));
10580 }
10581
10582 fn modifiers(&mut self) -> day_spec::Modifiers {
10583 let f = NSEvent::modifierFlags_class();
10584 day_spec::Modifiers {
10585 shift: f.contains(NSEventModifierFlags::Shift),
10586 primary: f.contains(NSEventModifierFlags::Command),
10587 alt: f.contains(NSEventModifierFlags::Option),
10588 }
10589 }
10590
10591 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10592 let front = undo_front(self.mtm);
10593 *front.ivars().state.borrow_mut() = state.clone();
10594 }
10595
10596 fn attach_list(&mut self, host: &Handle, source: ListSource) {
10597 let key = ptr_of(host);
10598 if let Some((table, data)) = list_entry(key) {
10599 data.ivars().source.replace(Some(source));
10600 unsafe { table.reloadData() };
10602 }
10603 post_realize_visible_rows(key);
10608 }
10609
10610 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10611 let key = ptr_of(host);
10612 if let Some((outline, data)) = tree_entry(key) {
10613 data.ivars().source.replace(Some(source));
10614 unsafe { outline.reloadData() };
10616 }
10617 <AppKit as Platform>::post(Box::new(move || {
10620 if let Some((outline, _)) = tree_entry(key) {
10621 unsafe { outline.layoutSubtreeIfNeeded() };
10622 }
10623 }));
10624 }
10625
10626 fn adopt(&mut self, raw: RawHandle) -> Handle {
10627 let ptr = raw as *mut NSView;
10631 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10632 }
10633
10634 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10635 self.edit_toolbar(h, ops)
10636 }
10637
10638 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10639 self.patch_toolbar(h, patch);
10640 }
10641
10642 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10643 let mtm = self.mtm;
10644 if self.menu_escape_monitor.is_none() {
10645 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10646 ffi_guard::contain(event.as_ptr(), || {
10647 let event_ref = unsafe { event.as_ref() };
10648 let app = NSApplication::sharedApplication(mtm);
10649 if app.modalWindow().is_none()
10652 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10653 && unsafe { event_ref.charactersIgnoringModifiers() }
10654 .is_some_and(|s| s.to_string() == "\u{1b}")
10655 && app
10656 .mainMenu()
10657 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10658 {
10659 std::ptr::null_mut()
10660 } else {
10661 event.as_ptr()
10662 }
10663 })
10664 });
10665 self.menu_escape_monitor = unsafe {
10666 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10667 objc2_app_kit::NSEventMask::KeyDown,
10668 &block,
10669 )
10670 }
10671 .map(MenuEscapeMonitor);
10672 }
10673 let app = NSApplication::sharedApplication(mtm);
10674 let menubar = NSMenu::new(mtm);
10675 let mut items = items.to_vec();
10678 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10679 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10680 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10681 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10682 let services =
10683 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10684 let items =
10689 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10690 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10691 for item in &items {
10693 match item {
10694 day_spec::MenuItem::Submenu { label, items, role } => {
10695 let sub = build_ns_menu(mtm, label, items);
10696 let it = NSMenuItem::new(mtm);
10697 if *role == Some(day_spec::MenuBarRole::Help)
10701 || *label == day_localization::t(day_localization::key::day_help)
10702 {
10703 help_menu = Some((label.clone(), sub));
10704 continue;
10705 }
10706 it.setTitle(&NSString::from_str(label));
10707 it.setSubmenu(Some(&sub));
10708 menubar.addItem(&it);
10709 }
10710 other => {
10711 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10713 let it = NSMenuItem::new(mtm);
10714 it.setSubmenu(Some(&sub));
10715 menubar.addItem(&it);
10716 }
10717 }
10718 }
10719 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10722 install_windows_menu(mtm, &app, &menubar);
10723 }
10724 if let Some((label, help)) = help_menu {
10725 let it = NSMenuItem::new(mtm);
10726 it.setTitle(&NSString::from_str(&label));
10727 it.setSubmenu(Some(&help));
10728 menubar.addItem(&it);
10729 unsafe { app.setHelpMenu(Some(&help)) };
10732 }
10733 app.setMainMenu(Some(&menubar));
10734 unsafe { app.setServicesMenu(Some(&services)) };
10735 }
10736
10737 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10738 let Some(view) = h.downcast_ref::<NSView>() else {
10739 return;
10740 };
10741 if items.is_empty() {
10742 unsafe { view.setMenu(None) };
10743 return;
10744 }
10745 let menu = build_ns_menu(self.mtm, "", items);
10746 unsafe { view.setMenu(Some(&menu)) };
10752 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10753 for sub in v.subviews() {
10754 unsafe { sub.setMenu(Some(menu)) };
10755 apply_to_subviews(&sub, menu);
10756 }
10757 }
10758 apply_to_subviews(view, &menu);
10759 }
10760
10761 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10762 transfer::source(h, source);
10763 }
10764 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10765 transfer::target(h, target);
10766 }
10767 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10768 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10771 }
10772
10773 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10774 let key = ptr_of(h);
10775 if kind == day_spec::GestureKind::Pan {
10779 PAN_NODES.with(|t| t.insert(key, node));
10780 install_container_pan_monitor();
10781 return;
10782 }
10783 if kind == day_spec::GestureKind::Hover {
10787 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10791 HOVER_NODES.with(|t| t.insert(key, node));
10792 if first {
10793 install_tracking_area(h);
10794 }
10795 return;
10796 }
10797 let already = GESTURES.with(|m| {
10799 m.borrow()
10800 .get(&key)
10801 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10802 });
10803 if already {
10804 return;
10805 }
10806 let mtm = self.mtm;
10807 let target = DayGesture::new(mtm, node, kind);
10808 let recognizer: Retained<NSGestureRecognizer> = unsafe {
10809 match kind {
10810 day_spec::GestureKind::Drag => {
10811 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10812 NSPanGestureRecognizer::alloc(mtm),
10813 Some(&target),
10814 Some(sel!(fire:)),
10815 ))
10816 }
10817 day_spec::GestureKind::Pinch => Retained::into_super(
10818 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10819 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10820 Some(&target),
10821 Some(sel!(fire:)),
10822 ),
10823 ),
10824 _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10825 NSClickGestureRecognizer::alloc(mtm),
10826 Some(&target),
10827 Some(sel!(fire:)),
10828 )),
10829 }
10830 };
10831 unsafe { h.addGestureRecognizer(&recognizer) };
10832 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10833 }
10834
10835 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10836 unsafe {
10837 if let Some(id) = &a11y.identifier {
10838 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10839 }
10840 if let Some(label) = &a11y.label {
10841 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10842 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10843 } else {
10844 APP_LABELED.with(|t| t.remove(ptr_of(h)));
10845 }
10846 if let Some(hint) = &a11y.hint {
10847 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10848 }
10849 if let Some(value) = &a11y.value {
10850 let ns = NSString::from_str(value);
10851 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10852 }
10853 if let Some(role) = ns_role(a11y.role) {
10856 h.setAccessibilityRole(Some(role));
10857 }
10858 if a11y.role == day_spec::Role::Tab {
10859 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10860 }
10861 if let Some(on) = a11y.selected {
10862 h.setAccessibilitySelected(on);
10863 }
10864 if a11y.hidden {
10870 h.setAccessibilityElement(false);
10871 h.setAccessibilityChildren(Some(&NSArray::new()));
10872 }
10873 }
10874 }
10875
10876 fn announce(&mut self, text: &str, urgent: bool) {
10880 use objc2_app_kit::{
10881 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10882 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10883 NSAccessibilityPriorityLevel,
10884 };
10885 let app = NSApplication::sharedApplication(self.mtm());
10886 let window = primary_content().and_then(|content| content.window());
10887 let element: &objc2::runtime::AnyObject = match &window {
10888 Some(window) => window,
10889 None => &app,
10890 };
10891 let priority = if urgent {
10893 NSAccessibilityPriorityLevel::High
10894 } else {
10895 NSAccessibilityPriorityLevel::Medium
10896 };
10897 let announcement = NSString::from_str(text);
10898 let priority = NSNumber::new_isize(priority.0);
10899 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10900 unsafe {
10903 let user_info = NSDictionary::from_slices::<NSString>(
10904 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10905 &values,
10906 );
10907 NSAccessibilityPostNotificationWithUserInfo(
10908 element,
10909 NSAccessibilityAnnouncementRequestedNotification,
10910 Some(&user_info),
10911 );
10912 }
10913 }
10914
10915 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10916 unsafe {
10917 let role = h
10918 .accessibilityRole()
10919 .map(|r| day_role_from_ns(&r.to_string()))
10920 .unwrap_or(day_spec::Role::None);
10921 let picker = picker::read_native(h);
10924 day_spec::NativeSnapshot {
10925 found: true,
10926 role,
10927 label: h.accessibilityLabel().map(|s| s.to_string()),
10928 value: h
10929 .accessibilityValue()
10930 .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10931 identifier: h
10932 .accessibilityIdentifier()
10933 .map(|s| s.to_string())
10934 .filter(|s| !s.is_empty()),
10935 text: match &picker {
10936 Some((text, _)) => text.clone(),
10937 None => native_text(h),
10938 },
10939 number: native_number(h),
10940 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10941 match sw.state() {
10942 s if s == NSControlStateValueOn => Some(true),
10943 s if s == NSControlStateValueOff => Some(false),
10944 _ => None,
10946 }
10947 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10948 BUTTON_SELECTED
10951 .with(|m| m.borrow().contains_key(&ptr_of(h)))
10952 .then(|| btn.state() == NSControlStateValueOn)
10953 } else {
10954 None
10955 },
10956 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10959 (Some((_, on)), _) => *on,
10960 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10961 (None, Some(c)) => Some(c.isEnabled()),
10962 (None, None) => None,
10963 },
10964 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10966 frame: native_frame(h),
10967 }
10968 }
10969 }
10970
10971 fn request_frame(
10972 &mut self,
10973 host: &Handle,
10974 cb: day_spec::FrameCallback,
10975 ) -> day_spec::CancelFrame {
10976 frame::request(host, cb)
10977 }
10978
10979 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10980 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10981 unsafe { h.setNeedsDisplay(true) };
10982 }
10983 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10984 NAV_STATE.with(|m| {
10985 let m = m.borrow();
10986 let Some(st) = m.get(&ptr_of(host)) else {
10987 return false;
10988 };
10989 if !matches!(
10992 st.presentation,
10993 NavPresentation::Split | NavPresentation::Rail
10994 ) {
10995 return false;
10996 }
10997 let item = &st.sidebar_item;
10998 let collapsed = unsafe { item.isCollapsed() };
11004 unsafe { item.setCollapsed(!collapsed) };
11005 true
11006 })
11007 }
11008
11009 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11010 let content = self.content.as_ref().ok_or("no window content")?;
11011 snapshot_view(content)
11012 }
11013
11014 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11020 use objc2::AllocAnyThread as _;
11021 let data = NSData::with_bytes(bytes);
11022 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11023 else {
11024 emit(
11025 WINDOW_NODE,
11026 Event::ImageDecoded {
11027 req,
11028 result: Err(day_spec::ImageError::Decode),
11029 },
11030 );
11031 return;
11032 };
11033 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11034 let info = day_spec::BitmapInfo {
11035 pixels: Size::new(w, h),
11036 scale: 1.0,
11039 format: day_spec::ImageFormat::sniff(bytes),
11040 has_alpha: unsafe { rep.hasAlpha() },
11041 };
11042 let image = unsafe {
11046 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11047 };
11048 unsafe { image.addRepresentation(&rep) };
11049 BITMAPS.with(|m| {
11050 m.borrow_mut().insert(
11051 id.0,
11052 AppKitBitmap {
11053 image,
11054 rep: Some(rep),
11055 info,
11056 },
11057 )
11058 });
11059 emit(
11060 WINDOW_NODE,
11061 Event::ImageDecoded {
11062 req,
11063 result: Ok(info),
11064 },
11065 );
11066 }
11067
11068 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11069 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11070 }
11071
11072 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11079 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11080 let mut out = day_spec::ImageProperties::default();
11081 let size = unsafe { rep.size() };
11082 if size.width > 0.0 {
11083 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11084 if (dpi - 72.0).abs() > 0.5 {
11087 out.dpi = Some(dpi);
11088 }
11089 }
11090 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11094 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11095 for key in keys.iter() {
11096 let value: Option<Retained<objc2::runtime::AnyObject>> =
11097 unsafe { msg_send![&*exif, objectForKey: &*key] };
11098 let Some(value) = value else { continue };
11099 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11100 let (k, v) = (key.to_string(), text.to_string());
11101 match k.as_str() {
11102 "Orientation" => out.orientation = v.parse().ok(),
11103 "DateTimeOriginal" => out.created = Some(v.clone()),
11104 _ => {}
11105 }
11106 out.extra.push((k, v));
11109 }
11110 }
11111 Some(out)
11112 }
11113
11114 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11118 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11119 vec![Png, Jpeg, Tiff, Bmp, Gif]
11120 }
11121
11122 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11123 let result = encode_bitmap(id, spec);
11124 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11125 }
11126
11127 fn release_image(&mut self, id: day_spec::BitmapId) {
11128 release_bitmap(id);
11129 }
11130
11131 fn render_bitmap(
11135 &mut self,
11136 req: u64,
11137 id: day_spec::BitmapId,
11138 ops: &[DrawOp],
11139 size: Size,
11140 scale: f64,
11141 ) {
11142 let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
11143 let info = bitmap.info;
11144 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11145 info
11146 });
11147 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11148 }
11149
11150 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11151 let result = render_pdf_bytes(pages, info);
11152 emit(WINDOW_NODE, Event::PdfRendered { req, result });
11153 }
11154
11155 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11159 use day_spec::FontWeight as W;
11160 let mtm =
11161 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11162 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11163 let mut out = Vec::new();
11164 for family in unsafe { manager.availableFontFamilies() }.iter() {
11165 let name = family.to_string();
11166 if name.starts_with('.') {
11167 continue;
11168 }
11169 let mut faces = Vec::new();
11170 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11171 for member in members.iter() {
11172 if member.count() < 4 {
11173 continue;
11174 }
11175 let style = member
11176 .objectAtIndex(1)
11177 .downcast_ref::<NSString>()
11178 .map(|s| s.to_string())
11179 .unwrap_or_default();
11180 let weight = member
11181 .objectAtIndex(2)
11182 .downcast_ref::<objc2_foundation::NSNumber>()
11183 .map(|n| n.integerValue())
11184 .unwrap_or(5);
11185 let traits = member
11186 .objectAtIndex(3)
11187 .downcast_ref::<objc2_foundation::NSNumber>()
11188 .map(|n| n.integerValue())
11189 .unwrap_or(0);
11190 let weight = match weight {
11191 ..=2 => W::UltraLight,
11192 3 => W::Thin,
11193 4 => W::Light,
11194 5 => W::Regular,
11195 6 => W::Medium,
11196 7 | 8 => W::Semibold,
11197 9 => W::Bold,
11198 10 | 11 => W::Heavy,
11199 _ => W::Black,
11200 };
11201 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
11203 name: if style.is_empty() {
11204 day_spec::FontFace::synthesized_name(weight, italic)
11205 } else {
11206 style
11207 },
11208 weight,
11209 italic,
11210 });
11211 }
11212 }
11213 out.push(day_spec::FontFamilyInfo {
11214 family: name,
11215 faces,
11216 });
11217 }
11218 out
11219 }
11220
11221 fn measure_text(
11224 &mut self,
11225 text: &str,
11226 size: f64,
11227 font: &day_spec::CanvasFont,
11228 ) -> Option<day_spec::TextMetrics> {
11229 let nsfont = canvas_nsfont(size, font);
11230 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11231 let ns = NSString::from_str(text);
11232 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11233 let unbounded = NSSize::new(f64::MAX, f64::MAX);
11237 let ink: NSRect = unsafe {
11238 msg_send![
11239 &ns,
11240 boundingRectWithSize: unbounded,
11241 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11242 attributes: &*attrs,
11243 ]
11244 };
11245 Some(day_spec::TextMetrics::from_baseline(
11246 sz.width,
11247 nsfont.ascender(),
11248 sz.height - nsfont.ascender(),
11249 nsfont.capHeight(),
11250 day_spec::Rect::new(
11251 ink.origin.x,
11252 -(ink.origin.y + ink.size.height),
11253 ink.size.width,
11254 ink.size.height,
11255 ),
11256 ))
11257 }
11258
11259 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11260 let content = self.content.as_ref().ok_or("no window content")?;
11261 snapshot_view_chrome(content)
11262 }
11263
11264 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11265 snapshot_view(host)
11266 }
11267
11268 fn open_window(
11269 &mut self,
11270 id: NodeId,
11271 options: &WindowOptions,
11272 kind: day_spec::WindowKind,
11273 ) -> day_spec::WindowOpenReply<Handle> {
11274 let prefs = kind.is_panel();
11275 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11276 if prefs {
11277 window.center();
11280 unsafe { window.setExcludedFromWindowsMenu(true) };
11281 } else {
11282 let from = match self.cascade {
11290 Some(p) => p,
11291 None => self
11292 .window
11293 .as_ref()
11294 .map(|w| {
11295 let f = w.frame();
11296 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
11297 unsafe { w.cascadeTopLeftFromPoint(top_left) }
11300 })
11301 .unwrap_or(NSPoint::new(0.0, 0.0)),
11302 };
11303 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
11304 }
11305 window_chrome::place(&window, options.placement);
11306 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11311 center_on_screen_of(&window, self.window.as_deref());
11312 }
11313 let _ = pin_below_title_bar(&window);
11316 if !options.start_hidden {
11317 window.makeKeyAndOrderFront(None);
11318 }
11319 mark_tree_needs_display(&content);
11322 self.secondary.push(SecondaryWin {
11323 window,
11324 delegate,
11325 content: content.clone(),
11326 });
11327 day_spec::WindowOpenReply::Open(content)
11328 }
11329
11330 fn native_window_tabs(&self) -> bool {
11331 true
11332 }
11333 fn group_windows(&mut self, hosts: &[Handle]) {
11334 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11335 let Some(first) = windows.first() else {
11336 return;
11337 };
11338 unsafe {
11339 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11340 }
11341 for window in windows.iter().skip(1) {
11343 unsafe {
11344 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11345 }
11346 }
11347 if let Some(group) = first.tabGroup() {
11348 if !group.isTabBarVisible() {
11349 unsafe {
11350 first.toggleTabBar(None);
11351 }
11352 }
11353 for (i, window) in windows.iter().enumerate() {
11354 group.insertWindow_atIndex(window, i as isize);
11355 }
11356 }
11357 for window in &windows {
11360 if let Some(size) = pin_below_title_bar(window) {
11361 let node = window
11362 .delegate()
11363 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11364 .and_then(|d| d.ivars().node)
11365 .unwrap_or(WINDOW_NODE);
11366 emit(node, Event::WindowResized(size));
11367 }
11368 }
11369 }
11370 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11371 let Some(window) = self.ns_window_for(host) else {
11372 return Vec::new();
11373 };
11374 let windows = window.tabGroup().map(|g| g.windows());
11375 let Some(windows) = windows else {
11376 return Vec::new();
11377 };
11378 windows
11379 .iter()
11380 .filter_map(|window| {
11381 self.secondary
11382 .iter()
11383 .find(|w| std::ptr::eq(&*w.window, &*window))
11384 .and_then(|w| w.delegate.ivars().node)
11385 })
11386 .collect()
11387 }
11388
11389 fn close_window(&mut self, host: &Handle) {
11390 if let Some(w) = self
11393 .secondary
11394 .iter()
11395 .find(|w| ptr_of(&w.content) == ptr_of(host))
11396 {
11397 w.window.close();
11398 }
11399 }
11400
11401 fn focus_window(&mut self, host: &Handle) {
11402 if let Some(w) = self
11403 .secondary
11404 .iter()
11405 .find(|w| ptr_of(&w.content) == ptr_of(host))
11406 {
11407 w.window.makeKeyAndOrderFront(None);
11408 }
11409 }
11410
11411 fn fit_window(&mut self, host: &Handle, size: Size) {
11412 let Some(w) = self
11413 .secondary
11414 .iter()
11415 .find(|w| ptr_of(&w.content) == ptr_of(host))
11416 else {
11417 return;
11418 };
11419 unsafe {
11420 w.window
11424 .setContentSize(NSSize::new(size.width, size.height));
11425 let mask = w.window.styleMask();
11429 w.window
11430 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11431 w.window.center();
11432 }
11433 center_on_screen_of(&w.window, self.window.as_deref());
11434 }
11435
11436 fn set_window_title(&mut self, host: &Handle, title: &str) {
11437 if let Some(w) = self
11438 .secondary
11439 .iter()
11440 .find(|w| ptr_of(&w.content) == ptr_of(host))
11441 {
11442 w.window.setTitle(&NSString::from_str(title));
11443 return;
11444 }
11445 if self
11449 .content
11450 .as_ref()
11451 .is_some_and(|c| ptr_of(c) == ptr_of(host))
11452 && let Some(w) = self.window.as_ref()
11453 {
11454 w.setTitle(&NSString::from_str(title));
11455 }
11456 }
11457
11458 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11459 use day_spec::WindowChange as C;
11460 let Some(window) = self.ns_window_for(host) else {
11461 return;
11462 };
11463 match change {
11464 C::State(state) => set_ns_window_state(&window, *state),
11465 C::ContentProtected(on) => window.setSharingType(if *on {
11467 objc2_app_kit::NSWindowSharingType::None
11468 } else {
11469 objc2_app_kit::NSWindowSharingType::ReadOnly
11470 }),
11471 other => window_chrome::apply_property(&window, other),
11472 }
11473 }
11474
11475 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11476 self.ns_window_for(host)
11477 .map(|w| window_chrome::frame_of(&w))
11478 }
11479
11480 fn monitors(&self) -> Vec<day_spec::Monitor> {
11481 window_chrome::monitors(self.mtm)
11482 }
11483
11484 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11487
11488 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11489 dock::set_app_items(self.mtm, items);
11490 }
11491
11492 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11493 window_chrome::set_drag_region(h, drag);
11494 }
11495
11496 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11497 status_item::set_items(self.mtm, items);
11498 }
11499
11500 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11501 status_item::set_progress(self.mtm, progress);
11502 }
11503
11504 fn set_dock_visible(&mut self, visible: bool) {
11505 status_item::set_dock_visible(self.mtm, visible);
11506 }
11507
11508 fn set_keep_running(&mut self, keep: bool) {
11509 status_item::set_keep_running(keep);
11510 }
11511
11512 fn quit_app(&mut self) {
11513 let app = NSApplication::sharedApplication(self.mtm);
11514 unsafe { app.terminate(None) };
11515 }
11516
11517 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11518 use present::PresentSpec;
11519 let mtm = self.mtm;
11520 let app = NSApplication::sharedApplication(mtm);
11524 let key = app.keyWindow().filter(|k| {
11525 let mut owner = k.clone();
11526 while let Some(parent) = owner.sheetParent() {
11527 owner = parent;
11528 }
11529 self.window
11530 .as_deref()
11531 .is_some_and(|w| std::ptr::eq(w, &*owner))
11532 || self
11533 .secondary
11534 .iter()
11535 .any(|s| std::ptr::eq(&*s.window, &*owner))
11536 });
11537 let Some(mut window) = key.or_else(|| self.window.clone()) else {
11538 emit(
11539 WINDOW_NODE,
11540 Event::PresentResult {
11541 req,
11542 result: present::PresentResult::Dismissed,
11543 },
11544 );
11545 return;
11546 };
11547 while let Some(sheet) = window.attachedSheet() {
11549 window = sheet;
11550 }
11551 match spec {
11553 PresentSpec::OpenFile {
11554 filters, multiple, ..
11555 } => {
11556 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11557 unsafe {
11558 panel.setCanChooseFiles(true);
11559 panel.setCanChooseDirectories(false);
11560 panel.setAllowsMultipleSelection(*multiple);
11561 panel.setMessage(Some(&NSString::from_str(spec.title())));
11562 }
11563 apply_allowed_file_types(&panel, filters);
11564 let p = panel.clone();
11565 let handler: block2::RcBlock<dyn Fn(isize)> =
11568 block2::RcBlock::new(move |resp: isize| {
11569 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11570 });
11571 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11572 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11573 return;
11574 }
11575 PresentSpec::OpenFolder { .. } => {
11577 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11578 unsafe {
11579 panel.setCanChooseFiles(false);
11580 panel.setCanChooseDirectories(true);
11581 panel.setCanCreateDirectories(true);
11582 panel.setAllowsMultipleSelection(false);
11583 panel.setMessage(Some(&NSString::from_str(spec.title())));
11584 }
11585 let p = panel.clone();
11586 let handler: block2::RcBlock<dyn Fn(isize)> =
11587 block2::RcBlock::new(move |resp: isize| {
11588 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11589 });
11590 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11591 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11592 return;
11593 }
11594 PresentSpec::SaveFile { suggested_name, .. } => {
11595 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11596 unsafe {
11597 panel.setMessage(Some(&NSString::from_str(spec.title())));
11598 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11599 }
11600 apply_allowed_file_types(&panel, spec.filters());
11601 let p = panel.clone();
11602 let handler: block2::RcBlock<dyn Fn(isize)> =
11603 block2::RcBlock::new(move |resp: isize| {
11604 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11606 });
11607 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11608 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11609 return;
11610 }
11611 _ => {}
11612 }
11613 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11614 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11615 if let Some(msg) = spec.message() {
11616 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11617 }
11618 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11620 PresentSpec::Dialog { buttons, .. } => {
11621 if buttons
11622 .iter()
11623 .any(|b| b.role == present::ButtonRole::Destructive)
11624 {
11625 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11626 }
11627 for b in buttons {
11628 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11629 }
11630 block2::RcBlock::new(move |resp: isize| {
11631 ffi_guard::contain((), || {
11632 let idx = resp - 1000;
11634 emit(
11635 WINDOW_NODE,
11636 Event::PresentResult {
11637 req,
11638 result: present::PresentResult::Button(idx as i64),
11639 },
11640 );
11641 PRESENT_ALERTS.with(|m| {
11642 m.borrow_mut().remove(&req);
11643 });
11644 })
11645 })
11646 }
11647 PresentSpec::Prompt {
11648 placeholder,
11649 initial,
11650 ok,
11651 cancel,
11652 ..
11653 } => {
11654 let tf = unsafe { NSTextField::new(mtm) };
11655 unsafe {
11656 tf.setFrame(NSRect::new(
11657 NSPoint::new(0.0, 0.0),
11658 NSSize::new(260.0, 24.0),
11659 ));
11660 tf.setEditable(true);
11661 tf.setBezeled(true);
11662 tf.setStringValue(&NSString::from_str(initial));
11663 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11664 alert.setAccessoryView(Some(&tf));
11665 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
11668 block2::RcBlock::new(move |resp: isize| {
11669 ffi_guard::contain((), || {
11670 let result = if resp == 1000 {
11671 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11672 } else {
11673 present::PresentResult::Dismissed
11674 };
11675 emit(WINDOW_NODE, Event::PresentResult { req, result });
11676 PRESENT_ALERTS.with(|m| {
11677 m.borrow_mut().remove(&req);
11678 });
11679 })
11680 })
11681 }
11682 PresentSpec::OpenFile { .. }
11684 | PresentSpec::OpenFolder { .. }
11685 | PresentSpec::SaveFile { .. } => unreachable!(),
11686 };
11687 unsafe {
11688 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11689 }
11690 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11691 }
11692
11693 fn dismiss(&mut self, req: u64) {
11694 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11697 if let Some(alert) = alert {
11698 let sheet = alert.window();
11699 if let Some(parent) = sheet.sheetParent() {
11700 unsafe { parent.endSheet(&sheet) };
11701 }
11702 }
11703 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11705 if let Some(panel) = panel
11706 && let Some(parent) = panel.sheetParent()
11707 {
11708 unsafe { parent.endSheet(&panel) };
11709 }
11710 }
11711
11712 fn application_handlers(
11713 &mut self,
11714 query: &day_spec::applications::HandlerQuery,
11715 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11716 {
11717 applications::handlers(query)
11718 }
11719
11720 fn open_url_with_application(
11721 &mut self,
11722 url: &str,
11723 application: &str,
11724 completion: day_spec::applications::OpenApplicationCompletion,
11725 ) {
11726 applications::open(url, application, completion);
11727 }
11728
11729 fn share_support(&self) -> day_spec::Support {
11730 day_spec::Support::Native
11731 }
11732 fn share_url(&mut self, url: &str, _title: &str) -> bool {
11733 use objc2::{msg_send, runtime::AnyObject};
11734 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11735 let Some(mtm) = objc2::MainThreadMarker::new() else {
11736 return false;
11737 };
11738 let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11739 return false;
11740 };
11741 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11742 let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11743 return false;
11744 };
11745 unsafe {
11746 let items = NSArray::from_retained_slice(&[url]);
11747 let picker: objc2::rc::Allocated<AnyObject> =
11748 msg_send![objc2::class!(NSSharingServicePicker), alloc];
11749 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11750 let bounds = view.bounds();
11751 let y = if view.isFlipped() {
11752 30.0
11753 } else {
11754 bounds.size.height - 30.0
11755 };
11756 let rect = NSRect::new(
11757 NSPoint::new(bounds.size.width - 30.0, y),
11758 NSSize::new(1.0, 1.0),
11759 );
11760 let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11761 self.sharing = Some(picker);
11762 }
11763 true
11764 }
11765 fn open_url(&mut self, url: &str) {
11766 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11769 if let Some(nsurl) = nsurl {
11770 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11771 }
11772 }
11773}
11774
11775#[allow(deprecated)]
11778fn apply_allowed_file_types(
11779 panel: &objc2_app_kit::NSSavePanel,
11780 filters: &[day_spec::present::FileFilter],
11781) {
11782 let exts: Vec<Retained<NSString>> = filters
11783 .iter()
11784 .flat_map(|f| f.extensions.iter())
11785 .map(|e| NSString::from_str(e))
11786 .collect();
11787 if !exts.is_empty() {
11788 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11789 let arr = objc2_foundation::NSArray::from_slice(&refs);
11790 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11791 }
11792}
11793
11794fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11798 let mut paths = Vec::new();
11799 if resp == 1 {
11800 for url in unsafe { panel.URLs() }.iter() {
11801 if let Some(p) = unsafe { url.path() } {
11802 paths.push(p.to_string());
11803 }
11804 }
11805 }
11806 let result = if paths.is_empty() {
11807 present::PresentResult::Dismissed
11808 } else {
11809 present::PresentResult::Files(paths)
11810 };
11811 emit(WINDOW_NODE, Event::PresentResult { req, result });
11812 PRESENT_PANELS.with(|m| {
11813 m.borrow_mut().remove(&req);
11814 });
11815}
11816
11817fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11819 let result = if resp == 1 {
11820 unsafe { panel.URL() }
11821 .and_then(|url| unsafe { url.path() })
11822 .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11823 .unwrap_or(present::PresentResult::Dismissed)
11824 } else {
11825 present::PresentResult::Dismissed
11826 };
11827 emit(WINDOW_NODE, Event::PresentResult { req, result });
11828 PRESENT_PANELS.with(|m| {
11829 m.borrow_mut().remove(&req);
11830 });
11831}
11832
11833impl Platform for AppKit {
11834 const TARGET: &'static str = "macos-appkit";
11835 const TOOLKIT: &'static str = "appkit";
11836
11837 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11838 let mtm = self.mtm;
11839 self.app_name = options
11843 .app_name
11844 .clone()
11845 .unwrap_or_else(|| options.title.clone());
11846 unsafe {
11855 objc2_foundation::NSProcessInfo::processInfo()
11856 .setProcessName(&NSString::from_str(&self.app_name));
11857 let bundle = objc2_foundation::NSBundle::mainBundle();
11858 let info: Option<Retained<objc2_foundation::NSDictionary>> =
11859 msg_send![&bundle, infoDictionary];
11860 if let Some(info) = info {
11861 let key = NSString::from_str("CFBundleName");
11862 let value = NSString::from_str(&self.app_name);
11863 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11867 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11868 }
11869 }
11870 }
11871 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11876 unsafe {
11877 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11878 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11879 .into_super()
11880 .into_super()
11881 .into_super();
11882 let dict = NSDictionary::from_retained_objects(
11883 &[
11884 &*NSString::from_str("AppleTextDirection"),
11885 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11886 ],
11887 &[yes.clone(), yes],
11888 );
11889 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11890 }
11891 }
11892 let app = NSApplication::sharedApplication(mtm);
11893 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11896 || unsafe {
11897 let bundle = objc2_foundation::NSBundle::mainBundle();
11898 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11899 &bundle,
11900 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11901 ];
11902 value.is_some_and(|v| {
11903 let on: bool = msg_send![&v, boolValue];
11904 on
11905 })
11906 };
11907 app.setActivationPolicy(if menu_bar_app {
11908 NSApplicationActivationPolicy::Accessory
11909 } else {
11910 NSApplicationActivationPolicy::Regular
11911 });
11912 let document_delegate = documents::delegate(mtm);
11913 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11914 if let Ok(theme) = std::env::var("DAY_THEME") {
11917 let name = match theme.as_str() {
11918 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11919 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11920 _ => None,
11921 };
11922 if let Some(name) = name {
11923 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11924 unsafe { app.setAppearance(appearance.as_deref()) };
11925 }
11926 }
11927 register_bundled_fonts();
11929
11930 let app_name = self.app_name.clone();
11934 install_main_menu(mtm, &app, &app_name);
11935 install_lifecycle_observers();
11937 install_appearance_observer();
11938 install_reduce_motion_observer();
11939
11940 let (window, delegate, content) = self.make_window(&options, false, None);
11941 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11945 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11946 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11947 _ => None,
11948 };
11949 if let Some(name) = appearance_name
11950 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11951 {
11952 window.setAppearance(Some(&appearance));
11953 }
11954 std::mem::forget(delegate);
11957
11958 self.window = Some(window.clone());
11959 self.content = Some(content.clone());
11960 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11961
11962 let layout = pin_below_title_bar(&window)
11964 .unwrap_or(Size::new(options.size.width, options.size.height));
11965 ready(self, content, layout);
11966
11967 if day_core::windows::new_window_action_id() == 0
11971 && options.tabbing == day_spec::WindowTabbing::Automatic
11972 {
11973 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11974 }
11975 if !day_core::has_app_menu() {
11980 install_main_menu(mtm, &app, &app_name);
11981 }
11982
11983 let deterministic =
11991 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11992 let autosave = NSString::from_str("day.main");
11993 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11994 window.center();
11995 window_chrome::place(&window, options.placement);
11997 }
11998 if let Some(screen) = capture_screen(mtm) {
12002 let (visible, frame) = (screen.visibleFrame(), window.frame());
12003 window.setFrameOrigin(NSPoint::new(
12004 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12005 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12006 ));
12007 }
12008 if !deterministic {
12009 unsafe { window.setFrameAutosaveName(&autosave) };
12010 }
12011 if !options.start_hidden {
12012 window.makeKeyAndOrderFront(None);
12013 app.activate();
12014 }
12015 if let Some(content) = window.contentView() {
12020 mark_tree_needs_display(&content);
12021 }
12022 if std::env::var_os("DAY_DUMP").is_some() {
12023 std::thread::spawn(|| {
12024 std::thread::sleep(std::time::Duration::from_millis(2000));
12025 Self::post(Box::new(|| {
12026 if let Some(content) = primary_content() {
12028 let desc: Retained<NSString> =
12029 unsafe { msg_send![&*content, _subtreeDescription] };
12030 log::warn!("{desc}");
12031 }
12032 }));
12033 });
12034 }
12035 app.run();
12036 }
12037
12038 fn post(f: Box<dyn FnOnce() + Send>) {
12039 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12042 }
12043
12044 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12045 let when =
12049 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12050 .unwrap_or(dispatch2::DispatchTime::FOREVER);
12051 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12052 ffi_guard::contain((), f);
12053 }) {
12054 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12055 }
12056 }
12057
12058 fn locale_hints(&self) -> Vec<String> {
12059 objc2_foundation::NSLocale::preferredLanguages()
12062 .iter()
12063 .map(|s| s.to_string())
12064 .collect()
12065 }
12066}
12067
12068unsafe extern "C" {
12073 fn CGWindowListCreateImage(
12074 bounds: objc2_core_foundation::CGRect,
12075 list_option: u32,
12076 window_id: u32,
12077 image_option: u32,
12078 ) -> *mut objc2_core_graphics::CGImage;
12079}
12080
12081const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12084const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12087
12088fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12095 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12096 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12097 objc2_app_kit::NSColorRenderingIntent::Default,
12098 );
12099 let rep = srgb.as_deref().unwrap_or(rep);
12100 let data = unsafe {
12101 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12102 }
12103 .ok_or("png encode failed")?;
12104 Ok(data.to_vec())
12105}
12106
12107fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12120 let window = content.window().ok_or("view is not in a window")?;
12121 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12124 return snapshot_via_window_server(&sheet, chrome);
12125 }
12126 let number = window.windowNumber();
12127 if number <= 0 {
12128 return Err(format!("window {number} is not on screen"));
12129 }
12130 unsafe { content.layoutSubtreeIfNeeded() };
12137 window.displayIfNeeded();
12138 CATransaction::flush();
12139 let null_rect = objc2_core_foundation::CGRect::new(
12141 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12142 objc2_core_foundation::CGSize::new(0.0, 0.0),
12143 );
12144 let shot = unsafe {
12145 CGWindowListCreateImage(
12146 null_rect,
12147 CG_WINDOW_LIST_INCLUDING_WINDOW,
12148 number as u32,
12149 CG_WINDOW_IMAGE_IGNORE_FRAMING,
12150 )
12151 };
12152 if shot.is_null() {
12153 return Err("the window server has no image for this window".into());
12154 }
12155 let shot = unsafe {
12158 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12159 };
12160
12161 if chrome {
12164 let rep = unsafe {
12165 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12166 objc2_app_kit::NSBitmapImageRep::alloc(),
12167 &shot,
12168 )
12169 };
12170 return png_of_rep(&rep);
12171 }
12172
12173 let frame = window.frame();
12177 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12178 return Err("zero-size window".into());
12179 }
12180 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12181 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12184 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12185 let crop = objc2_core_foundation::CGRect::new(
12186 objc2_core_foundation::CGPoint::new(
12187 (in_window.origin.x * scale).round(),
12188 (from_top * scale).round(),
12189 ),
12190 objc2_core_foundation::CGSize::new(
12191 (in_window.size.width * scale).round(),
12192 (in_window.size.height * scale).round(),
12193 ),
12194 );
12195 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12196 .ok_or("crop to the content view failed")?;
12197 let rep = unsafe {
12198 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12199 objc2_app_kit::NSBitmapImageRep::alloc(),
12200 &cropped,
12201 )
12202 };
12203 png_of_rep(&rep)
12204}
12205
12206fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12216 let [x, y, w, h] = base;
12217 let (sw, sh) = (w * t.sx, h * t.sy);
12218 let frame = NSRect::new(
12219 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12220 NSSize::new(sw, sh),
12221 );
12222 unsafe {
12223 v.setFrameCenterRotation(0.0);
12226 v.setFrame(frame);
12227 v.setBoundsSize(NSSize::new(w, h));
12228 if t.rotate_deg != 0.0 {
12229 v.setFrameCenterRotation(t.rotate_deg);
12230 }
12231 }
12232}
12233
12234fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12235 let modal = content
12236 .window()
12237 .and_then(|w| w.attachedSheet())
12238 .and_then(|s| s.contentView());
12239 let content = modal.as_deref().unwrap_or(content);
12240 match snapshot_via_window_server(content, false) {
12241 Ok(bytes) => Ok(bytes),
12242 Err(_) => snapshot_view_cache(content),
12243 }
12244}
12245
12246fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12254 let modal = content
12255 .window()
12256 .and_then(|w| w.attachedSheet())
12257 .and_then(|s| s.contentView());
12258 let content = modal.as_deref().unwrap_or(content);
12259 match snapshot_via_window_server(content, true) {
12260 Ok(bytes) => Ok(bytes),
12261 Err(_) => snapshot_view_cache(content),
12262 }
12263}
12264
12265fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12269 let bounds = content.bounds();
12270 let rep =
12271 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12272 let ctx =
12276 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12277 NSGraphicsContext::saveGraphicsState_class();
12278 NSGraphicsContext::setCurrentContext(Some(&ctx));
12279 content
12280 .effectiveAppearance()
12281 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
12282 NSColor::windowBackgroundColor().setFill();
12283 objc2_app_kit::NSRectFill(bounds);
12284 }));
12285 NSGraphicsContext::restoreGraphicsState_class();
12286 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
12287 png_of_rep(&rep)
12288}
12289
12290fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
12296 let Some(screen) = primary.and_then(|w| w.screen()) else {
12297 return;
12298 };
12299 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
12300 return;
12301 }
12302 let (visible, frame) = (screen.visibleFrame(), window.frame());
12303 window.setFrameOrigin(NSPoint::new(
12304 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12305 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
12306 ));
12307}
12308
12309fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12310 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12311 .ok()?
12312 .trim()
12313 .parse()
12314 .ok()?;
12315 let key = NSString::from_str("NSScreenNumber");
12316 objc2_app_kit::NSScreen::screens(mtm)
12317 .into_iter()
12318 .find(|screen| {
12319 let number: Option<Retained<objc2_foundation::NSNumber>> =
12320 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12321 number.is_some_and(|n| n.unsignedIntValue() == wanted)
12322 })
12323}
12324
12325fn mark_tree_needs_display(view: &NSView) {
12327 view.setNeedsDisplay(true);
12328 for sub in view.subviews() {
12329 mark_tree_needs_display(&sub);
12330 }
12331}
12332
12333pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12338 phase.is_universal()
12339}
12340
12341fn install_appearance_observer() {
12347 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12348 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12349 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12350 dispatch2::DispatchQueue::main()
12351 .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12352 });
12353 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12354 let token = unsafe {
12355 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12356 };
12357 std::mem::forget(token);
12358}
12359
12360fn install_reduce_motion_observer() {
12368 use objc2_foundation::NSNotification;
12369 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12370 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12371 dispatch2::DispatchQueue::main()
12372 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12373 });
12374 let token = unsafe {
12375 center.addObserverForName_object_queue_usingBlock(
12376 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12377 None,
12378 None,
12379 &block,
12380 )
12381 };
12382 std::mem::forget(token);
12383}
12384
12385fn install_lifecycle_observers() {
12388 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12389 let center = unsafe { NSNotificationCenter::defaultCenter() };
12390 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12391 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12392 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12393 });
12394 let token = unsafe {
12395 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12396 };
12397 std::mem::forget(token); };
12399 unsafe {
12400 observe(
12401 NSApplicationDidBecomeActiveNotification,
12402 day_spec::Lifecycle::DidBecomeActive,
12403 );
12404 observe(
12405 NSApplicationWillResignActiveNotification,
12406 day_spec::Lifecycle::WillResignActive,
12407 );
12408 observe(
12409 NSApplicationWillTerminateNotification,
12410 day_spec::Lifecycle::WillTerminate,
12411 );
12412 observe(
12416 NSApplicationWillTerminateNotification,
12417 day_spec::Lifecycle::DidExit,
12418 );
12419 }
12420}
12421
12422day_localization_ui::locales!();
12423
12424fn install_application_menu(
12427 mtm: MainThreadMarker,
12428 menubar: &NSMenu,
12429 title: &str,
12430 about: Option<day_spec::MenuItem>,
12431 updates: Option<day_spec::MenuItem>,
12432 prefs: Option<day_spec::MenuItem>,
12433 quit: Option<day_spec::MenuItem>,
12434) -> Retained<NSMenu> {
12435 let app = NSApplication::sharedApplication(mtm);
12436 use day_spec::{MenuItem as M, MenuRole as R};
12437 let standard = |role, label| M::Action {
12438 id: None,
12439 action: 0,
12440 label,
12441 shortcut: None,
12442 enabled: true,
12443 checked: None,
12444 role: Some(role),
12445 icon: None,
12446 };
12447 let mut about =
12448 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12449 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12450 for (item, title) in [
12451 (&mut about, res::str::about_app(title).format()),
12452 (&mut quit, res::str::quit_app(title).format()),
12453 ] {
12454 if let M::Action { label, .. } = item {
12455 *label = title;
12456 }
12457 }
12458 if let M::Action { action, .. } = &mut about
12461 && *action == 0
12462 {
12463 *action = day_core::windows::about_action_id();
12464 }
12465 let updates_id = day_core::windows::check_for_updates_action_id();
12468 let updates = updates.or_else(|| {
12469 (updates_id != 0).then(|| {
12470 standard(
12471 R::CheckForUpdates,
12472 day_localization::t(day_localization::key::day_check_for_updates),
12473 )
12474 })
12475 });
12476 let mut head = vec![about];
12477 if let Some(mut updates) = updates {
12478 if let M::Action { action, .. } = &mut updates
12479 && *action == 0
12480 {
12481 *action = updates_id;
12482 }
12483 head.push(updates);
12484 }
12485 head.push(M::Separator);
12486 let menu = build_ns_menu(mtm, title, &head);
12487 if let Some(mut prefs) = prefs {
12488 if let M::Action { label, .. } = &mut prefs {
12489 *label = res::str::settings().format();
12490 }
12491 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12492 for item in section.itemArray() {
12493 section.removeItem(&item);
12494 menu.addItem(&item);
12495 }
12496 }
12497 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12500 if let Some(parent) = unsafe { services.supermenu() } {
12501 let index = parent.indexOfItemWithSubmenu(Some(&services));
12502 if index >= 0 {
12503 parent.itemAtIndex(index).unwrap().setSubmenu(None);
12504 }
12505 }
12506 let services_item = NSMenuItem::new(mtm);
12507 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12508 services_item.setSubmenu(Some(&services));
12509 menu.addItem(&services_item);
12510 menu.addItem(&NSMenuItem::separatorItem(mtm));
12511 for (label, selector, shortcut) in [
12512 (
12513 res::str::hide_app(title).format(),
12514 sel!(hide:),
12515 Some(day_spec::Shortcut::primary("h")),
12516 ),
12517 (
12518 res::str::hide_others().format(),
12519 sel!(hideOtherApplications:),
12520 Some(day_spec::Shortcut::primary("h").alt()),
12521 ),
12522 (
12523 res::str::show_all().format(),
12524 sel!(unhideAllApplications:),
12525 None,
12526 ),
12527 ] {
12528 let item = unsafe {
12529 NSMenuItem::initWithTitle_action_keyEquivalent(
12530 NSMenuItem::alloc(mtm),
12531 &NSString::from_str(&label),
12532 Some(selector),
12533 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12534 )
12535 };
12536 if let Some(shortcut) = shortcut {
12537 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12538 }
12539 unsafe { item.setTarget(Some(&app)) };
12541 menu.addItem(&item);
12542 }
12543 menu.addItem(&NSMenuItem::separatorItem(mtm));
12544 let section = build_ns_menu(mtm, title, &[quit]);
12545 let quit = section.itemAtIndex(0).unwrap();
12546 section.removeItem(&quit);
12547 menu.addItem(&quit);
12548 let item = NSMenuItem::new(mtm);
12549 item.setSubmenu(Some(&menu));
12550 menubar.addItem(&item);
12551 services
12552}
12553
12554fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12557 let menubar = NSMenu::new(mtm);
12558
12559 let prefs_id = day_core::windows::preferences_action_id();
12560 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12561 id: None,
12562 action: prefs_id,
12563 label: res::str::settings().format(),
12564 shortcut: None,
12565 enabled: true,
12566 checked: None,
12567 role: Some(day_spec::MenuRole::Preferences),
12568 icon: None,
12569 });
12570 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12571
12572 let new_window_id = day_core::windows::new_window_action_id();
12577 if new_window_id != 0 {
12578 let file_item = NSMenuItem::new(mtm);
12579 let file_menu = unsafe {
12580 NSMenu::initWithTitle(
12581 NSMenu::alloc(mtm),
12582 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12583 )
12584 };
12585 let new_window = unsafe {
12586 NSMenuItem::initWithTitle_action_keyEquivalent(
12587 NSMenuItem::alloc(mtm),
12588 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12589 Some(sel!(fire:)),
12590 &NSString::from_str("n"),
12591 )
12592 };
12593 let target = menu_target(mtm);
12594 let tobj: &objc2::runtime::AnyObject = target.as_ref();
12595 unsafe { new_window.setTarget(Some(tobj)) };
12596 new_window.setTag(new_window_id as isize);
12597 file_menu.addItem(&new_window);
12598 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12599 let close = unsafe {
12601 NSMenuItem::initWithTitle_action_keyEquivalent(
12602 NSMenuItem::alloc(mtm),
12603 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12604 Some(sel!(performClose:)),
12605 &NSString::from_str("w"),
12606 )
12607 };
12608 file_menu.addItem(&close);
12609 file_item.setSubmenu(Some(&file_menu));
12610 menubar.addItem(&file_item);
12611 }
12612
12613 let edit_item = NSMenuItem::new(mtm);
12614 let edit_menu = unsafe {
12615 NSMenu::initWithTitle(
12616 NSMenu::alloc(mtm),
12617 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12618 )
12619 };
12620 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12621 let item = unsafe {
12622 NSMenuItem::initWithTitle_action_keyEquivalent(
12623 NSMenuItem::alloc(mtm),
12624 &NSString::from_str(&day_localization::t(key)),
12625 Some(action),
12626 &NSString::from_str(accel),
12627 )
12628 };
12629 edit_menu.addItem(&item);
12630 };
12631 add("day_undo", sel!(undo:), "z");
12632 add("day_redo", sel!(redo:), "Z");
12633 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12634 add("day_cut", sel!(cut:), "x");
12635 add("day_copy", sel!(copy:), "c");
12636 add("day_paste", sel!(paste:), "v");
12637 add("day_select_all", sel!(selectAll:), "a");
12638 edit_item.setSubmenu(Some(&edit_menu));
12639 menubar.addItem(&edit_item);
12640
12641 install_windows_menu(mtm, app, &menubar);
12642
12643 app.setMainMenu(Some(&menubar));
12644 unsafe { app.setServicesMenu(Some(&services)) };
12645}
12646
12647fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12652 let menu = unsafe {
12653 NSMenu::initWithTitle(
12654 NSMenu::alloc(mtm),
12655 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12656 )
12657 };
12658 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12659 let item = unsafe {
12660 NSMenuItem::initWithTitle_action_keyEquivalent(
12661 NSMenuItem::alloc(mtm),
12662 &NSString::from_str(&day_localization::t(key)),
12663 Some(action),
12664 &NSString::from_str(accel),
12665 )
12666 };
12667 menu.addItem(&item);
12668 };
12669 add("day_minimize", sel!(performMiniaturize:), "m");
12670 add("day_zoom", sel!(performZoom:), "");
12671 menu.addItem(&NSMenuItem::separatorItem(mtm));
12672 add("day_bring_all_front", sel!(arrangeInFront:), "");
12673 let item = NSMenuItem::new(mtm);
12674 item.setTitle(&NSString::from_str(&day_localization::t(
12675 day_localization::key::day_window,
12676 )));
12677 item.setSubmenu(Some(&menu));
12678 menubar.addItem(&item);
12679 unsafe { app.setWindowsMenu(Some(&menu)) };
12680}
12681
12682fn extract_app_role(
12685 items: &mut Vec<day_spec::MenuItem>,
12686 role: day_spec::MenuRole,
12687) -> Option<day_spec::MenuItem> {
12688 use day_spec::MenuItem as M;
12689 let mut found = None;
12690 let mut remaining = Vec::new();
12691 for mut item in items.drain(..) {
12692 match &mut item {
12693 M::Action { role: Some(r), .. } if *r == role => {
12694 found.get_or_insert(item);
12695 continue;
12696 }
12697 M::Submenu { items, .. } => {
12698 let nested = extract_app_role(items, role);
12699 if found.is_none() {
12700 found = nested;
12701 }
12702 if items.is_empty() {
12703 continue;
12704 }
12705 }
12706 M::Separator
12707 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12708 {
12709 continue;
12710 }
12711 _ => {}
12712 }
12713 remaining.push(item);
12714 }
12715 while matches!(remaining.last(), Some(M::Separator)) {
12716 remaining.pop();
12717 }
12718 *items = remaining;
12719 found
12720}
12721
12722fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12724 items.iter().any(|it| match it {
12725 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12726 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12727 day_spec::MenuItem::Separator => false,
12728 })
12729}
12730
12731define_class!(
12737 #[unsafe(super(NSObject))]
12738 #[thread_kind = MainThreadOnly]
12739 #[name = "DayMenuTarget"]
12740 #[ivars = ()]
12741 struct DayMenuTarget;
12742
12743 unsafe impl NSObjectProtocol for DayMenuTarget {}
12744
12745 impl DayMenuTarget {
12746 #[unsafe(method(fire:))]
12747 fn fire(&self, sender: &NSMenuItem) {
12748 ffi_guard::contain((), || {
12749 let id = sender.tag() as u64;
12750 if id != 0 {
12751 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12752 }
12753 })
12754 }
12755 }
12756);
12757
12758pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12767 let content = window.contentView()?;
12768 let full = content.frame().size;
12769 let layout = unsafe { window.contentLayoutRect() }.size;
12770 let top = (full.height - layout.height).max(0.0);
12771 if window_chrome::is_overlay(window) {
12775 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12776 window_chrome::report_title_bar_inset(window, top);
12777 return Some(Size::new(full.width, full.height));
12778 }
12779 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12780 Some(Size::new(full.width, (full.height - top).max(0.0)))
12781}
12782
12783fn native_text(h: &NSView) -> Option<String> {
12787 if h.downcast_ref::<NSSecureTextField>().is_some() {
12788 return None;
12789 }
12790 if let Some(tf) = h.downcast_ref::<NSTextField>() {
12791 return Some(tf.stringValue().to_string());
12793 }
12794 if let Some(btn) = h.downcast_ref::<NSButton>() {
12795 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12796 return None;
12797 }
12798 return Some(btn.title().to_string());
12799 }
12800 let sv = h.downcast_ref::<NSScrollView>()?;
12802 let doc = sv.documentView()?;
12803 let tv = doc.downcast_ref::<NSTextView>()?;
12804 Some(tv.string().to_string())
12805}
12806
12807fn native_number(h: &NSView) -> Option<f64> {
12810 if let Some(sl) = h.downcast_ref::<NSSlider>() {
12811 return Some(sl.doubleValue());
12812 }
12813 let pi = h.downcast_ref::<NSProgressIndicator>()?;
12814 (!pi.isIndeterminate()).then(|| pi.doubleValue())
12815}
12816
12817fn native_frame(h: &NSView) -> Option<Rect> {
12821 let content = h.window()?.contentView()?;
12822 let r = h.convertRect_toView(h.bounds(), Some(&content));
12823 let y = if content.isFlipped() {
12824 r.origin.y
12825 } else {
12826 let b = content.bounds();
12827 b.origin.y + b.size.height - (r.origin.y + r.size.height)
12828 };
12829 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12830}
12831
12832fn title_bar_inset(content: &NSView) -> f64 {
12834 (-content.bounds().origin.y).max(0.0)
12835}
12836
12837fn primary_content() -> Option<Retained<NSView>> {
12838 PRIMARY_CONTENT.with(|c| c.borrow().clone())
12839}
12840
12841fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12842 MENU_TARGET.with(|t| {
12843 t.borrow_mut()
12844 .get_or_insert_with(|| {
12845 let this = DayMenuTarget::alloc(mtm).set_ivars(());
12846 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12847 obj
12848 })
12849 .clone()
12850 })
12851}
12852
12853fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12854 use objc2_app_kit::NSEventModifierFlags as F;
12855 let mut m = F::empty();
12856 if s.primary {
12857 m |= F::Command;
12858 }
12859 if s.shift {
12860 m |= F::Shift;
12861 }
12862 if s.alt {
12863 m |= F::Option;
12864 }
12865 if s.control {
12866 m |= F::Control;
12867 }
12868 m
12869}
12870
12871fn ns_key_equivalent(key: &str) -> String {
12874 match key {
12875 "Return" | "Enter" => "\r".into(),
12876 "Tab" => "\t".into(),
12877 "Delete" | "Backspace" => "\u{8}".into(),
12878 "Escape" => "\u{1b}".into(),
12879 "Space" => " ".into(),
12880 k if k.chars().count() == 1 => k.to_lowercase(),
12881 _ => String::new(), }
12883}
12884
12885fn role_spec(
12888 role: day_spec::MenuRole,
12889) -> (
12890 &'static str,
12891 Option<objc2::runtime::Sel>,
12892 Option<day_spec::Shortcut>,
12893) {
12894 use day_spec::MenuRole as R;
12895 use day_spec::Shortcut as S;
12896 match role {
12897 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12898 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12899 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12900 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12901 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12902 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12903 R::Delete => ("Delete", Some(sel!(delete:)), None),
12904 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12905 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12906 R::Preferences => ("Settings…", None, Some(S::primary(","))),
12907 R::Minimize => (
12908 "Minimize",
12909 Some(sel!(performMiniaturize:)),
12910 Some(S::primary("m")),
12911 ),
12912 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12913 R::Fullscreen => (
12914 "Enter Full Screen",
12915 Some(sel!(toggleFullScreen:)),
12916 Some(S::primary("f").control()),
12917 ),
12918 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12921 R::CheckForUpdates => ("Check for Updates…", None, None),
12923 }
12924}
12925
12926pub(crate) fn build_ns_menu(
12927 mtm: MainThreadMarker,
12928 title: &str,
12929 items: &[day_spec::MenuItem],
12930) -> Retained<NSMenu> {
12931 use day_spec::MenuItem as MI;
12932 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12933 let target = menu_target(mtm);
12934 for item in items {
12935 match item {
12936 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12937 MI::Submenu { label, items, .. } => {
12938 let sub = build_ns_menu(mtm, label, items);
12939 let it = NSMenuItem::new(mtm);
12940 it.setTitle(&NSString::from_str(label));
12941 it.setSubmenu(Some(&sub));
12942 menu.addItem(&it);
12943 }
12944 MI::Action {
12945 action,
12946 label,
12947 shortcut,
12948 enabled,
12949 checked,
12950 role,
12951 icon,
12952 ..
12953 } => {
12954 let (mut lbl, sel, mut sc) = match role {
12956 Some(r) => {
12957 let (dl, ds, dsc) = role_spec(*r);
12958 (dl.to_string(), ds, dsc)
12959 }
12960 None => (String::new(), None, None),
12961 };
12962 if !label.is_empty() {
12963 lbl = label.clone();
12964 }
12965 if shortcut.is_some() {
12966 sc = shortcut.clone();
12967 }
12968 let responder_role = matches!(
12974 role,
12975 Some(
12976 day_spec::MenuRole::Undo
12977 | day_spec::MenuRole::Redo
12978 | day_spec::MenuRole::Cut
12979 | day_spec::MenuRole::Copy
12980 | day_spec::MenuRole::Paste
12981 | day_spec::MenuRole::SelectAll
12982 )
12983 );
12984 let custom = *action != 0 && !responder_role;
12985 let key = sc
12986 .as_ref()
12987 .map(|s| ns_key_equivalent(&s.key))
12988 .unwrap_or_default();
12989 let it = unsafe {
12990 NSMenuItem::initWithTitle_action_keyEquivalent(
12991 NSMenuItem::alloc(mtm),
12992 &NSString::from_str(&lbl),
12993 if custom { Some(sel!(fire:)) } else { sel },
12994 &NSString::from_str(&key),
12995 )
12996 };
12997 if let Some(s) = &sc {
12998 it.setKeyEquivalentModifierMask(ns_modifiers(s));
12999 it.setAllowsAutomaticKeyEquivalentLocalization(true);
13005 it.setAllowsAutomaticKeyEquivalentMirroring(true);
13006 }
13007 if custom {
13008 let tobj: &objc2::runtime::AnyObject = target.as_ref();
13009 unsafe { it.setTarget(Some(tobj)) };
13010 it.setTag(*action as isize);
13011 }
13012 it.setEnabled(*enabled);
13013 if let Some(on) = checked {
13016 it.setState(if *on {
13017 NSControlStateValueOn
13018 } else {
13019 NSControlStateValueOff
13020 });
13021 }
13022 if let Some(icon) = icon
13025 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13026 {
13027 img.setSize(NSSize::new(16.0, 16.0));
13028 it.setImage(Some(&img));
13029 }
13030 menu.addItem(&it);
13031 }
13032 }
13033 }
13034 menu
13035}
13036
13037fn release_bitmap(id: day_spec::BitmapId) {
13040 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13041}
13042
13043#[cfg(test)]
13044mod bitmap_teardown_tests {
13045 use super::*;
13046
13047 #[test]
13048 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13049 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13051 if std::env::var_os(CHILD).is_some() {
13052 struct LateRelease;
13053 impl Drop for LateRelease {
13054 fn drop(&mut self) {
13055 assert!(BITMAPS.try_with(|_| ()).is_err());
13056 release_bitmap(day_spec::BitmapId(1));
13058 }
13059 }
13060 std::thread_local! {
13061 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13062 }
13063 std::thread::spawn(|| {
13064 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13065 BITMAPS.with(|_| ()); })
13067 .join()
13068 .unwrap();
13069 return;
13070 }
13071 let output = std::process::Command::new(std::env::current_exe().unwrap())
13072 .args([
13073 "--exact",
13074 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13075 "--nocapture",
13076 ])
13077 .env(CHILD, "1")
13078 .output()
13079 .unwrap();
13080 assert!(
13081 output.status.success(),
13082 "{}",
13083 String::from_utf8_lossy(&output.stderr)
13084 );
13085 }
13086}