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 ROTATE_NODES: SideTable<NodeId> = SideTable::new();
162 static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
165 static KEY_NODES: SideTable<NodeId> = SideTable::new();
169 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
174 static MARKED: SideTable<String> = SideTable::new();
178 static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
181
182 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
184 RefCell::new(HashMap::new());
185
186 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
187 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
189 RefCell::new(std::collections::HashSet::new());
190 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
196
197 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
198 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
201
202 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
204 static SPLIT_PANES: SideTable<bool> = SideTable::new();
206
207 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
211
212 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
213 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
215
216 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
221 static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
225 const { RefCell::new(Vec::new()) };
226 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
229 static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
232
233 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
235
236 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
238 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
239 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
240 const { std::cell::RefCell::new(None) };
241
242 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
244 RefCell::new(HashMap::new());
245 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
247 RefCell::new(HashMap::new());
248
249 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
252 const { std::cell::RefCell::new(None) };
253 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
257 const { std::cell::RefCell::new(None) };
258
259}
260
261pub fn emit(id: NodeId, ev: Event) {
263 let sink = SINK.with(|s| s.borrow().clone());
264 if let Some(sink) = sink {
265 sink(id, ev);
266 }
267}
268
269fn ptr_of(v: &NSView) -> usize {
270 std::ptr::from_ref::<NSView>(v).cast::<()>() as usize
271}
272
273fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
278 ffi_guard::contain((), || {
279 let key = ptr_of(btn);
281 let Some(items) =
282 day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(key)).is_some())
283 else {
284 return;
285 };
286 let menu = build_ns_menu(btn.mtm(), "", &items);
287 let bounds = btn.bounds();
288 let y = if btn.isFlipped() {
289 bounds.size.height + 2.0
290 } else {
291 -2.0
292 };
293 unsafe {
294 btn.highlight(true);
295 menu.popUpMenuPositioningItem_atLocation_inView(
297 None,
298 objc2_foundation::NSPoint::new(0.0, y),
299 Some(btn),
300 );
301 btn.highlight(false);
302 }
303 });
304}
305
306#[derive(Clone, Copy)]
308struct ImageMode {
309 template: bool,
310 tinted: bool,
311}
312
313impl ImageMode {
314 fn renders_template(self) -> bool {
317 self.template || self.tinted
318 }
319}
320
321struct AppKitBitmap {
328 image: Retained<objc2_app_kit::NSImage>,
329 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
330 info: day_spec::BitmapInfo,
331}
332
333fn scaled_rep(
339 image: &objc2_app_kit::NSImage,
340 pixels: Size,
341 scale: f64,
342) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
343 use objc2::AllocAnyThread as _;
344 let w = (pixels.width * scale).round().max(1.0);
345 let h = (pixels.height * scale).round().max(1.0);
346 let rep = unsafe {
347 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
348 objc2_app_kit::NSBitmapImageRep::alloc(),
349 std::ptr::null_mut(),
350 w as isize,
351 h as isize,
352 8,
353 4,
354 true,
355 false,
356 objc2_app_kit::NSDeviceRGBColorSpace,
357 0,
358 0,
359 )
360 }?;
361 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
362 NSGraphicsContext::saveGraphicsState_class();
363 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
364 unsafe {
365 image.drawInRect_fromRect_operation_fraction(
366 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
367 NSRect::ZERO,
368 objc2_app_kit::NSCompositingOperation::SourceOver,
369 1.0,
370 );
371 }
372 NSGraphicsContext::restoreGraphicsState_class();
373 Some(rep)
374}
375
376fn encode_bitmap(
381 id: day_spec::BitmapId,
382 spec: &day_spec::EncodeSpec,
383) -> Result<Vec<u8>, day_spec::ImageError> {
384 use day_spec::ImageFormat as F;
385 use objc2_app_kit::NSBitmapImageFileType as T;
386 let file_type = match spec.format {
387 F::Png => T::PNG,
388 F::Jpeg => T::JPEG,
389 F::Tiff => T::TIFF,
390 F::Bmp => T::BMP,
391 F::Gif => T::GIF,
392 _ => return Err(day_spec::ImageError::Encode),
396 };
397 let held = BITMAPS.with(|m| {
398 m.borrow()
399 .get(&id.0)
400 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
401 });
402 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
403 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
404
405 let rep = match spec.fit {
408 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
409 let scale = (fit.width / info.pixels.width)
410 .min(fit.height / info.pixels.height)
411 .min(1.0);
412 if scale < 1.0 {
413 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
414 } else {
415 rep
416 }
417 }
418 _ => rep,
419 };
420
421 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
422 Some(q) => {
424 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
425 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
426 let value: &objc2::runtime::AnyObject = &number;
427 NSDictionary::from_slices::<NSString>(&[key], &[value])
428 }
429 None => NSDictionary::new(),
430 };
431 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
432 .ok_or(day_spec::ImageError::Encode)?;
433 Ok(data.to_vec())
434}
435
436fn paint_ops(ops: &[DrawOp]) {
440 let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
442 let Some(cg) = cg else {
443 for op in ops {
444 draw_op(op);
445 }
446 return;
447 };
448 cg_begin_replay(&cg);
449 for op in ops {
450 if !cg_fast_op(&cg, op) {
451 draw_op(op);
452 }
453 }
454}
455
456fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
465 use objc2_core_graphics::{CGContext, CGImage};
466 match op {
467 DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
468 let Some(even_odd) = cg_add_shape(cg, shape) else {
469 return false;
470 };
471 let c = [color.r, color.g, color.b, color.a];
472 unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
474 if even_odd {
475 CGContext::eo_fill_path(Some(cg));
476 } else {
477 CGContext::fill_path(Some(cg));
478 }
479 true
480 }
481 DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
482 if cg_add_shape(cg, shape).is_none() {
483 return false;
484 }
485 let c = [color.r, color.g, color.b, color.a];
486 unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
488 cg_stroke_style(cg, style);
489 CGContext::stroke_path(Some(cg));
490 true
491 }
492 DrawOp::Clip(shape) => {
493 let Some(even_odd) = cg_add_shape(cg, shape) else {
494 return false;
495 };
496 if even_odd {
497 CGContext::eo_clip(Some(cg));
498 } else {
499 CGContext::clip(Some(cg));
500 }
501 true
502 }
503 DrawOp::Image {
504 image,
505 rect,
506 opacity,
507 source,
508 } => {
509 let Some((cg_image, pixels)) = BITMAPS.with(|m| {
512 m.borrow().get(&image.0).and_then(|b| {
513 let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
515 Some((cg, b.info.pixels))
516 })
517 }) else {
518 return false;
519 };
520 let (cropped, dest) = match source {
524 None => (None, *rect),
525 Some(src) => {
526 let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
527 else {
528 return true;
529 };
530 let crop = CGImage::with_image_in_rect(
531 Some(&cg_image),
532 NSRect::new(
533 NSPoint::new(src.origin.x, src.origin.y),
534 NSSize::new(src.size.width, src.size.height),
535 ),
536 );
537 let Some(crop) = crop else {
538 return true;
539 };
540 (Some(crop), dest)
541 }
542 };
543 if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
544 return true;
545 }
546 CGContext::save_g_state(Some(cg));
549 CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
550 CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
551 CGContext::scale_ctm(Some(cg), 1.0, -1.0);
552 CGContext::draw_image(
553 Some(cg),
554 NSRect::new(
555 NSPoint::new(0.0, 0.0),
556 NSSize::new(dest.size.width, dest.size.height),
557 ),
558 Some(cropped.as_deref().unwrap_or(&cg_image)),
559 );
560 CGContext::restore_g_state(Some(cg));
561 true
562 }
563 _ => false,
564 }
565}
566
567fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
569 use objc2_core_graphics::{CGColorSpace, CGContext};
570 let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
572 CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
573 CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
574}
575
576fn cg_add_shape(cg: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
579 use day_spec::{PathSeg, Shape};
580 use objc2_core_graphics::CGContext;
581 CGContext::begin_path(Some(cg));
582 match shape {
583 Shape::Rect(r) => CGContext::add_rect(Some(cg), ns_rect(*r)),
584 Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(cg), ns_rect(*r)),
585 Shape::Line(a, b) => {
586 CGContext::move_to_point(Some(cg), a.x, a.y);
587 CGContext::add_line_to_point(Some(cg), b.x, b.y);
588 }
589 Shape::Polygon(pts) => {
590 let (first, rest) = pts.split_first()?;
591 if rest.is_empty() {
592 return None;
593 }
594 CGContext::move_to_point(Some(cg), first.x, first.y);
595 for p in rest {
596 CGContext::add_line_to_point(Some(cg), p.x, p.y);
597 }
598 CGContext::close_path(Some(cg));
599 }
600 Shape::Path(path) => {
601 if path.segs.is_empty() {
602 return None;
603 }
604 for seg in &path.segs {
605 match seg {
606 PathSeg::Move(a) => CGContext::move_to_point(Some(cg), a.x, a.y),
607 PathSeg::Line(a) => CGContext::add_line_to_point(Some(cg), a.x, a.y),
608 PathSeg::Quad(c, a) => {
609 CGContext::add_quad_curve_to_point(Some(cg), c.x, c.y, a.x, a.y);
610 }
611 PathSeg::Cubic(c1, c2, a) => {
612 CGContext::add_curve_to_point(Some(cg), c1.x, c1.y, c2.x, c2.y, a.x, a.y);
613 }
614 PathSeg::Close => CGContext::close_path(Some(cg)),
615 }
616 }
617 return Some(path.rule == day_spec::FillRule::EvenOdd);
618 }
619 Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
620 }
621 Some(false)
622}
623
624fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
628 use day_spec::{LineCap, LineJoin};
629 use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
630 CGContext::set_line_width(Some(cg), style.width);
631 CGContext::set_line_cap(
632 Some(cg),
633 match style.cap {
634 LineCap::Butt => CGLineCap::Butt,
635 LineCap::Round => CGLineCap::Round,
636 LineCap::Square => CGLineCap::Square,
637 },
638 );
639 CGContext::set_line_join(
640 Some(cg),
641 match style.join {
642 LineJoin::Miter => CGLineJoin::Miter,
643 LineJoin::Round => CGLineJoin::Round,
644 LineJoin::Bevel => CGLineJoin::Bevel,
645 },
646 );
647 CGContext::set_miter_limit(Some(cg), style.miter_limit);
648 if style.dash.is_empty() {
649 unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
651 } else {
652 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
653 unsafe {
655 CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len());
656 };
657 }
658}
659
660fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
668 use objc2_core_graphics::CGContext;
669 CGContext::save_g_state(Some(cg));
670 CGContext::translate_ctm(Some(cg), 0.0, height);
671 CGContext::scale_ctm(Some(cg), scale, -scale);
672 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
673 NSGraphicsContext::saveGraphicsState_class();
674 NSGraphicsContext::setCurrentContext(Some(&ns));
675 paint_ops(ops);
676 NSGraphicsContext::restoreGraphicsState_class();
677 CGContext::restore_g_state(Some(cg));
678}
679
680struct Sendable<T>(T);
682
683unsafe impl<T> Send for Sendable<T> {}
689
690struct OffscreenResources {
695 images: Vec<(u64, AppKitBitmap)>,
696 fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
697}
698
699impl OffscreenResources {
700 fn collect(ops: &[DrawOp]) -> Self {
703 let mut images: Vec<(u64, AppKitBitmap)> = Vec::new();
704 let mut fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)> = Vec::new();
705 for op in ops {
706 match op {
707 DrawOp::Image { image, .. } => {
708 if images.iter().any(|(id, _)| *id == image.0) {
709 continue;
710 }
711 let held = BITMAPS.with(|m| {
712 m.borrow().get(&image.0).map(|b| AppKitBitmap {
713 image: b.image.clone(),
714 rep: b.rep.clone(),
715 info: b.info,
716 })
717 });
718 if let Some(bitmap) = held {
719 images.push((image.0, bitmap));
720 }
721 }
722 DrawOp::Text { size, font, .. } => {
723 let key = (size.to_bits(), font.clone());
724 if fonts.iter().any(|(k, _)| *k == key) {
725 continue;
726 }
727 let resolved = canvas_nsfont(*size, font);
728 fonts.push((key, resolved));
729 }
730 _ => {}
731 }
732 }
733 Self { images, fonts }
734 }
735
736 fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
740 let mut added_images = Vec::with_capacity(self.images.len());
741 BITMAPS.with(|m| {
742 let mut m = m.borrow_mut();
743 for (id, bitmap) in self.images {
744 if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
745 slot.insert(bitmap);
746 added_images.push(id);
747 }
748 }
749 });
750 let added_fonts = self.fonts.len();
751 OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
752 let out = paint();
753 OFFSCREEN_FONTS.with(|t| {
754 let mut t = t.borrow_mut();
755 let keep = t.len().saturating_sub(added_fonts);
756 t.truncate(keep);
757 });
758 BITMAPS.with(|m| {
759 let mut m = m.borrow_mut();
760 for id in added_images {
761 m.remove(&id);
762 }
763 });
764 out
765 }
766}
767
768fn render_bitmap_cgimage(
779 ops: &[DrawOp],
780 size: Size,
781 scale: f64,
782) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, day_spec::ExportError>
783{
784 use objc2_core_graphics::{
785 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
786 };
787 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
788 let (pw, ph) = day_spec::export_pixels(size, scale);
789 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
791 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
792 let cg = unsafe {
795 CGBitmapContextCreate(
796 std::ptr::null_mut(),
797 pw as usize,
798 ph as usize,
799 8,
800 0,
801 Some(&space),
802 CGImageAlphaInfo::PremultipliedLast.0,
803 )
804 }
805 .ok_or_else(|| {
806 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
807 })?;
808 paint_flipped(&cg, f64::from(ph), scale, ops);
810 CGBitmapContextCreateImage(Some(&cg))
811 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
812}
813
814fn bitmap_from_cgimage(cg_image: &objc2_core_graphics::CGImage, scale: f64) -> AppKitBitmap {
818 use objc2::AllocAnyThread as _;
819 let rep = unsafe {
820 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
821 objc2_app_kit::NSBitmapImageRep::alloc(),
822 cg_image,
823 )
824 };
825 let (pw, ph) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
826 let points = NSSize::new(pw / scale, ph / scale);
829 unsafe { rep.setSize(points) };
830 let image =
831 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
832 unsafe { image.addRepresentation(&rep) };
833 AppKitBitmap {
834 image,
835 rep: Some(rep),
836 info: day_spec::BitmapInfo {
837 pixels: Size::new(pw, ph),
838 scale,
839 format: None,
840 has_alpha: true,
841 },
842 }
843}
844
845fn render_pdf_bytes(
850 pages: &[day_spec::PdfPage],
851 info: &day_spec::PdfInfo,
852) -> Result<Vec<u8>, day_spec::ExportError> {
853 use objc2_core_foundation::{
854 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
855 };
856 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
857 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
858 let media =
859 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
860 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
861 let data = CFMutableData::new(None, 0)
862 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
863 let consumer = CGDataConsumer::with_cf_data(Some(&data))
864 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
865
866 let mut keys: Vec<&CFString> = Vec::new();
867 let mut values: Vec<CFRetained<CFString>> = Vec::new();
868 let (title_key, author_key) = unsafe {
870 (
871 objc2_core_graphics::kCGPDFContextTitle,
872 objc2_core_graphics::kCGPDFContextAuthor,
873 )
874 };
875 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
876 if let Some(value) = value {
877 keys.push(key);
878 values.push(CFString::from_str(value));
879 }
880 }
881 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
882 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
883
884 let first_box = media(first.size);
885 let pdf =
888 unsafe { CGPDFContextCreate(Some(&consumer), &raw const first_box, Some(aux.as_opaque())) }
889 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
890 for page in pages {
891 let page_box = media(page.size);
892 unsafe { CGContext::begin_page(Some(&pdf), &raw const page_box) };
894 paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
895 CGContext::end_page(Some(&pdf));
896 }
897 CGPDFContextClose(Some(&pdf));
899 drop(pdf);
900 drop(consumer);
901 Ok(data.to_vec())
902}
903
904thread_local! {
905 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
908 std::cell::RefCell::new(std::collections::HashMap::new());
909}
910
911fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
924 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
925 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
926 const STRETCH: f32 = 1.0;
929 const HOLD: f32 = 750.0;
930 use objc2_app_kit::{
931 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
932 };
933 let label = |text: &str, size: f64, secondary: bool| {
934 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
935 unsafe {
936 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
937 if secondary {
938 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
939 }
940 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
941 }
942 tf
943 };
944 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
945 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
946 let stack = NSStackView::new(mtm);
947 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
948 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
949 stack.setAlignment(NSLayoutAttribute::CenterY);
950 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
951 stack.setSpacing(6.0);
952 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
954 top: 4.0,
955 left: 0.0,
956 bottom: 4.0,
957 right: 0.0,
958 });
959 let icon = unsafe { NSImageView::new(mtm) };
960 unsafe {
961 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
962 icon.widthAnchor()
963 .constraintEqualToConstant(16.0)
964 .setActive(true);
965 icon.heightAnchor()
966 .constraintEqualToConstant(16.0)
967 .setActive(true);
968 }
969 stack.addArrangedSubview(&icon);
970 let texts = NSStackView::new(mtm);
973 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
974 texts.setAlignment(NSLayoutAttribute::Width);
975 texts.setSpacing(1.0);
976 texts.setHuggingPriority_forOrientation(
979 HOLD,
980 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
981 );
982 let title = label("", size, false);
983 let subtitle = label("", small, true);
984 for line in [&title, &subtitle] {
986 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
987 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
988 }
989 texts.addArrangedSubview(&title);
990 texts.addArrangedSubview(&subtitle);
991 stack.addArrangedSubview(&texts);
992 let detail = label("", size, true);
993 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
994 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
995 stack.addArrangedSubview(&detail);
996 let check = unsafe { NSImageView::new(mtm) };
997 unsafe {
998 check.setImage(
999 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1000 &NSString::from_str("checkmark"),
1001 None,
1002 )
1003 .as_deref(),
1004 );
1005 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1006 }
1007 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1008 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1009 stack.addArrangedSubview(&check);
1010 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1011 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1012 dress_list_item(&view, p, mtm);
1013 view
1014}
1015
1016fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1018 use objc2_app_kit::{NSImageView, NSStackView};
1019 let Some(stack) = view.downcast_ref::<NSStackView>() else {
1020 return;
1021 };
1022 let parts = stack.arrangedSubviews();
1023 if parts.len() < 4 {
1024 return;
1025 }
1026 let icon = parts.objectAtIndex(0);
1027 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1028 let image = p
1029 .icon
1030 .as_ref()
1031 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1032 unsafe {
1033 iv.setImage(image.as_deref());
1034 iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
1035 }
1036 }
1037 icon.setHidden(p.icon.is_none());
1038 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1039 let lines = texts.arrangedSubviews();
1040 if lines.len() == 2 {
1041 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1042 tf.setStringValue(&NSString::from_str(&p.title));
1043 }
1044 let sub = lines.objectAtIndex(1);
1045 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1046 tf.setStringValue(&NSString::from_str(&p.subtitle));
1047 }
1048 sub.setHidden(p.subtitle.is_empty());
1049 }
1050 }
1051 let detail = parts.objectAtIndex(2);
1052 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1053 tf.setStringValue(&NSString::from_str(&p.detail));
1054 }
1055 detail.setHidden(p.detail.is_empty());
1056 parts.objectAtIndex(3).setHidden(!p.checked);
1057 let words = [&p.title, &p.subtitle, &p.detail]
1058 .into_iter()
1059 .filter(|w| !w.is_empty())
1060 .map(String::as_str)
1061 .collect::<Vec<_>>()
1062 .join(", ");
1063 unsafe {
1064 view.setAccessibilityElement(true);
1065 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1066 view.setAccessibilitySelected(p.checked);
1067 }
1068}
1069
1070fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1076 use objc2::AllocAnyThread as _;
1077 match source {
1078 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1083 .or_else(|| day_spec::resource::resolve_image_file(name))
1084 .and_then(|path| unsafe {
1085 objc2_app_kit::NSImage::initWithContentsOfFile(
1086 objc2_app_kit::NSImage::alloc(),
1087 &NSString::from_str(&path.to_string_lossy()),
1088 )
1089 }),
1090 day_spec::ImageSource::Bytes(bytes) => unsafe {
1093 objc2_app_kit::NSImage::initWithData(
1094 objc2_app_kit::NSImage::alloc(),
1095 &NSData::with_bytes(bytes),
1096 )
1097 },
1098 day_spec::ImageSource::Decoded(id) => {
1100 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1101 }
1102 }
1103}
1104
1105fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1108 use day_spec::Role;
1109 use objc2_app_kit::{
1110 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1111 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1112 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1113 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1114 };
1115 unsafe {
1116 Some(match role {
1117 Role::Button => NSAccessibilityButtonRole,
1118 Role::Toggle => NSAccessibilityCheckBoxRole,
1119 Role::Tab => NSAccessibilityRadioButtonRole,
1122 Role::TabList => NSAccessibilityTabGroupRole,
1123 Role::Slider => NSAccessibilitySliderRole,
1124 Role::TextInput => NSAccessibilityTextFieldRole,
1125 Role::Heading(_) => NSAccessibilityHeadingRole,
1130 Role::Image => NSAccessibilityImageRole,
1131 Role::Meter => NSAccessibilityLevelIndicatorRole,
1132 Role::Group => NSAccessibilityGroupRole,
1133 Role::Tree => NSAccessibilityOutlineRole,
1136 Role::TreeItem => NSAccessibilityRowRole,
1137 Role::None => return None,
1138 })
1139 }
1140}
1141
1142fn day_role_from_ns(ax: &str) -> day_spec::Role {
1144 use day_spec::Role;
1145 match ax {
1146 "AXButton" => Role::Button,
1147 "AXCheckBox" => Role::Toggle,
1148 "AXSlider" => Role::Slider,
1149 "AXTextField" => Role::TextInput,
1150 "AXStaticText" | "AXHeading" => Role::Heading(0),
1153 "AXOutline" => Role::Tree,
1154 "AXImage" => Role::Image,
1155 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1156 "AXGroup" => Role::Group,
1157 "AXRadioButton" => Role::Tab,
1158 "AXTabGroup" => Role::TabList,
1159 _ => Role::None,
1160 }
1161}
1162
1163struct TargetIvars {
1168 node: NodeId,
1169}
1170
1171define_class!(
1172 #[unsafe(super(NSObject))]
1173 #[thread_kind = MainThreadOnly]
1174 #[name = "DayTarget"]
1175 #[ivars = TargetIvars]
1176 struct DayTarget;
1177
1178 unsafe impl NSObjectProtocol for DayTarget {}
1179 unsafe impl NSTextFieldDelegate for DayTarget {}
1180
1181 unsafe impl NSTabViewDelegate for DayTarget {
1186 #[unsafe(method(tabView:didSelectTabViewItem:))]
1187 fn tab_view_did_select(
1188 &self,
1189 tab_view: &objc2_app_kit::NSTabView,
1190 item: Option<&objc2_app_kit::NSTabViewItem>,
1191 ) {
1192 ffi_guard::contain((), || {
1193 if TAB_PICK_SUPPRESS.with(std::cell::Cell::get) {
1194 return;
1195 }
1196 if let Some(item) = item {
1197 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1198 if idx >= 0 {
1199 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1200 }
1201 }
1202 });
1203 }
1204 }
1205
1206 impl DayTarget {
1207 #[unsafe(method(action:))]
1212 fn action(&self, sender: &NSControl) {
1213 ffi_guard::contain((), || {
1214 let node = self.ivars().node;
1215 if sender.downcast_ref::<NSSwitch>().is_some() {
1216 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1217 } else if sender.downcast_ref::<NSSlider>().is_some() {
1218 let value = unsafe { sender.doubleValue() };
1219 emit(node, Event::ValueChanged(value));
1221 if slider_value_settled() {
1227 emit(node, Event::ValueCommitted(value));
1228 }
1229 } else if let (Some(f), Some(btn)) = (
1230 BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1231 sender.downcast_ref::<NSButton>(),
1232 ) {
1233 pop_button_menu(btn, &f);
1235 } else {
1236 emit(node, Event::Pressed);
1237 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1240 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1241 unsafe {
1242 btn.setState(if on {
1243 NSControlStateValueOn
1244 } else {
1245 NSControlStateValueOff
1246 });
1247 };
1248 }
1249 }
1250 });
1251 }
1252
1253 #[unsafe(method(navBack:))]
1256 fn nav_back(&self, _sender: &NSControl) {
1257 ffi_guard::contain((), || {
1258 emit(
1259 self.ivars().node,
1260 Event::NavBack {
1261 already_popped: false,
1262 },
1263 );
1264 });
1265 }
1266 }
1267
1268 unsafe impl NSControlTextEditingDelegate for DayTarget {
1269 #[unsafe(method(controlTextDidChange:))]
1270 fn control_text_did_change(&self, notification: &NSNotification) {
1271 ffi_guard::contain((), || {
1272 let node = self.ivars().node;
1273 if let Some(obj) = unsafe { notification.object() }
1274 && let Ok(tf) = obj.downcast::<NSTextField>() {
1275 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1276 }
1277 });
1278 }
1279
1280 #[unsafe(method(control:textView:doCommandBySelector:))]
1286 fn control_do_command(
1287 &self,
1288 _control: &NSControl,
1289 _tv: &NSTextView,
1290 command: objc2::runtime::Sel,
1291 ) -> objc2::runtime::Bool {
1292 ffi_guard::contain(objc2::runtime::Bool::NO, || {
1293 let node = self.ivars().node;
1294 let key = if command == sel!(moveUp:) {
1295 "ArrowUp"
1296 } else if command == sel!(moveDown:) {
1297 "ArrowDown"
1298 } else if command == sel!(cancelOperation:) {
1299 "Escape"
1300 } else {
1301 return objc2::runtime::Bool::NO;
1302 };
1303 if !day_spec::keys::field_claims(node, key, 0) {
1304 return objc2::runtime::Bool::NO;
1305 }
1306 emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1307 objc2::runtime::Bool::YES
1308 })
1309 }
1310
1311 #[unsafe(method(controlTextDidEndEditing:))]
1315 fn control_text_did_end_editing(&self, notification: &NSNotification) {
1316 ffi_guard::contain((), || {
1317 let node = self.ivars().node;
1318 let movement = unsafe { notification.userInfo() }
1319 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1320 .and_then(|n| n.downcast::<NSNumber>().ok())
1321 .map_or(NSTextMovement::Other, |n| NSTextMovement(n.integerValue()));
1322 if movement == NSTextMovement::Return {
1323 emit(node, Event::Submitted);
1324 } else {
1325 emit(node, Event::FocusChanged(false));
1326 }
1327 });
1328 }
1329 }
1330);
1331
1332impl DayTarget {
1333 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1334 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1335 unsafe { msg_send![super(this), init] }
1336 }
1337}
1338
1339struct CursorIvars {
1344 cursor: RefCell<Option<Retained<NSCursor>>>,
1346 hidden: Cell<bool>,
1348 hiding: Cell<bool>,
1350}
1351
1352define_class!(
1358 #[unsafe(super(NSObject))]
1359 #[thread_kind = MainThreadOnly]
1360 #[name = "DayCursorOwner"]
1361 #[ivars = CursorIvars]
1362 struct DayCursorOwner;
1363
1364 unsafe impl NSObjectProtocol for DayCursorOwner {}
1365
1366 impl DayCursorOwner {
1367 #[unsafe(method(cursorUpdate:))]
1368 fn cursor_update(&self, _event: &NSEvent) {
1369 let iv = self.ivars();
1370 if iv.hidden.get() {
1371 if !iv.hiding.replace(true) {
1372 NSCursor::hide();
1373 }
1374 return;
1375 }
1376 if let Some(c) = iv.cursor.borrow().as_ref() {
1377 c.set();
1378 }
1379 }
1380
1381 #[unsafe(method(mouseExited:))]
1382 fn mouse_exited(&self, _event: &NSEvent) {
1383 if self.ivars().hiding.replace(false) {
1384 NSCursor::unhide();
1385 }
1386 }
1387 }
1388);
1389
1390impl DayCursorOwner {
1391 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1392 let this = Self::alloc(mtm).set_ivars(CursorIvars {
1393 cursor: RefCell::new(None),
1394 hidden: Cell::new(false),
1395 hiding: Cell::new(false),
1396 });
1397 unsafe { msg_send![super(this), init] }
1398 }
1399}
1400
1401#[allow(deprecated)]
1409#[expect(
1410 clippy::match_same_arms,
1411 reason = "each macOS 15 cursor keeps its older fallback arm directly below its probe"
1412)]
1413fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1414 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1415 Some(match c {
1416 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1417 Cursor::Pointer => NSCursor::pointingHandCursor(),
1418 Cursor::Text => NSCursor::IBeamCursor(),
1419 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1420 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1421 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1422 Cursor::Grabbing => NSCursor::closedHandCursor(),
1423 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1424 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1425 Cursor::Copy => NSCursor::dragCopyCursor(),
1426 Cursor::Alias => NSCursor::dragLinkCursor(),
1427 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1428 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1429 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1430 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1431 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1432 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1433 NSCursor::frameResizeCursorFromPosition_inDirections(
1434 NSCursorFrameResizePosition::TopRight,
1435 NSCursorFrameResizeDirections::All,
1436 )
1437 }
1438 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1439 NSCursor::frameResizeCursorFromPosition_inDirections(
1440 NSCursorFrameResizePosition::TopLeft,
1441 NSCursorFrameResizeDirections::All,
1442 )
1443 }
1444 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1445 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1446 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1447 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1448 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1449 Cursor::None => return None,
1450 Cursor::Native(name) => match &**name {
1451 "disappearingItem" => NSCursor::disappearingItemCursor(),
1452 "dragCopy" => NSCursor::dragCopyCursor(),
1453 "dragLink" => NSCursor::dragLinkCursor(),
1454 "contextualMenu" => NSCursor::contextualMenuCursor(),
1455 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1456 _ => return None,
1457 },
1458 })
1459}
1460
1461fn slider_value_settled() -> bool {
1468 let Some(mtm) = MainThreadMarker::new() else {
1469 return false;
1470 };
1471 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1472 return false;
1473 };
1474 matches!(
1475 unsafe { event.r#type() },
1476 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1477 )
1478}
1479
1480struct FieldIvars {
1485 node: NodeId,
1486}
1487
1488struct SharePickerIvars {
1491 actions: Vec<day_spec::share::ShareAction>,
1492}
1493
1494define_class!(
1495 #[unsafe(super(NSObject))]
1496 #[thread_kind = MainThreadOnly]
1497 #[name = "DaySharePickerDelegate"]
1498 #[ivars = SharePickerIvars]
1499 struct DaySharePickerDelegate;
1500
1501 unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1502
1503 impl DaySharePickerDelegate {
1504 #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1505 fn services(
1506 &self,
1507 _picker: &AnyObject,
1508 _items: &AnyObject,
1509 proposed: &objc2_foundation::NSArray<AnyObject>,
1510 ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1511 let mut services: Vec<Retained<AnyObject>> = Vec::new();
1512 for action in &self.ivars().actions {
1513 let id = action.id;
1514 let handler = block2::RcBlock::new(move || {
1515 ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1516 });
1517 let image = action.symbol.and_then(|s| {
1518 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1519 &NSString::from_str(day_spec::sf_symbol_name(s)),
1520 None,
1521 )
1522 });
1523 let service: Option<Retained<AnyObject>> = unsafe {
1526 let alloc: objc2::rc::Allocated<AnyObject> =
1527 msg_send![objc2::class!(NSSharingService), alloc];
1528 msg_send![
1529 alloc,
1530 initWithTitle: &*NSString::from_str(&action.title),
1531 image: image.as_deref(),
1532 alternateImage: None::<&AnyObject>,
1533 handler: &*handler
1534 ]
1535 };
1536 services.extend(service);
1537 }
1538 let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1541 all.extend(services);
1542 objc2_foundation::NSArray::from_retained_slice(&all)
1543 }
1544 }
1545);
1546
1547define_class!(
1548 #[unsafe(super(NSTextField))]
1549 #[thread_kind = MainThreadOnly]
1550 #[name = "DayTextField"]
1551 #[ivars = FieldIvars]
1552 struct DayTextField;
1553
1554 impl DayTextField {
1555 #[unsafe(method(becomeFirstResponder))]
1560 fn become_first_responder(&self) -> bool {
1561 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1562 if ok {
1563 field_gained_focus(self.ivars().node);
1564 }
1565 ok
1566 }
1567 }
1568);
1569
1570impl DayTextField {
1571 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1572 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1573 unsafe { msg_send![super(this), init] }
1574 }
1575}
1576
1577define_class!(
1582 #[unsafe(super(NSSecureTextField))]
1583 #[thread_kind = MainThreadOnly]
1584 #[name = "DaySecureTextField"]
1585 #[ivars = FieldIvars]
1586 struct DaySecureTextField;
1587
1588 impl DaySecureTextField {
1589 #[unsafe(method(becomeFirstResponder))]
1591 fn become_first_responder(&self) -> bool {
1592 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1593 if ok {
1594 field_gained_focus(self.ivars().node);
1595 }
1596 ok
1597 }
1598 }
1599);
1600
1601impl DaySecureTextField {
1602 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1603 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1604 unsafe { msg_send![super(this), init] }
1605 }
1606}
1607
1608thread_local! {
1609 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1612}
1613
1614fn field_gained_focus(node: NodeId) {
1617 if FIELD_SWAP.with(std::cell::Cell::get) {
1618 return;
1619 }
1620 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1623}
1624
1625fn text_field_node(v: &NSView) -> Option<NodeId> {
1628 v.downcast_ref::<DayTextField>()
1629 .map(|f| f.ivars().node)
1630 .or_else(|| {
1631 v.downcast_ref::<DaySecureTextField>()
1632 .map(|f| f.ivars().node)
1633 })
1634}
1635
1636fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1640 let target = DayTarget::new(mtm, node);
1641 let tf: Retained<NSTextField> = if secure {
1644 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1645 } else {
1646 Retained::into_super(DayTextField::new(mtm, node))
1647 };
1648 unsafe {
1649 tf.setEditable(true);
1650 tf.setBezeled(true);
1651 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1652 }
1653 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1654 tf
1655}
1656
1657fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1661 window.firstResponder().is_some_and(|fr| {
1662 if Retained::as_ptr(&fr).cast::<()>() as usize == ptr_of(h) {
1663 return true;
1664 }
1665 fr.downcast::<NSText>().is_ok_and(|text| {
1666 unsafe { text.delegate() }
1667 .is_some_and(|d| Retained::as_ptr(&d).cast::<()>() as usize == ptr_of(h))
1668 })
1669 })
1670}
1671
1672fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1677 unsafe extern "C" {
1678 fn dlsym(
1679 handle: *mut std::ffi::c_void,
1680 symbol: *const std::ffi::c_char,
1681 ) -> *mut std::ffi::c_void;
1682 }
1683 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1685 unsafe {
1689 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1690 if slot.is_null() {
1691 None
1692 } else {
1693 (*slot).as_ref()
1694 }
1695 }
1696}
1697
1698fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1700 if let Some(v) = table.take(old) {
1701 table.insert(new, v);
1702 }
1703}
1704
1705struct LabelIvars {
1710 node: NodeId,
1711 has_links: Cell<bool>,
1712 has_runs: Cell<bool>,
1713 selectable: Cell<bool>,
1714}
1715
1716define_class!(
1717 #[unsafe(super(NSTextField))]
1718 #[thread_kind = MainThreadOnly]
1719 #[name = "DayLabel"]
1720 #[ivars = LabelIvars]
1721 struct DayLabel;
1722
1723 impl DayLabel {
1724 #[unsafe(method_id(menuForEvent:))]
1725 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1726 ffi_guard::contain(None, || {
1727 if !self.isSelectable()
1728 && let Some(menu) = inherited_context_menu(self, event)
1729 {
1730 return menu;
1731 }
1732 unsafe { msg_send![super(self), menuForEvent: event] }
1733 })
1734 }
1735
1736 #[unsafe(method(drawRect:))]
1737 fn draw_rect(&self, dirty: NSRect) {
1738 let mut ancestor = unsafe { self.superview() };
1742 let mut selection_color = None;
1743 if !self.ivars().has_runs.get() {
1744 while let Some(view) = ancestor {
1745 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1746 if unsafe { row.isSelected() } {
1747 selection_color = Some(unsafe {
1748 if row.isEmphasized() {
1749 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1750 } else {
1751 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1752 }
1753 });
1754 }
1755 break;
1756 }
1757 ancestor = unsafe { view.superview() };
1758 }
1759 }
1760 let cell = unsafe { self.cell() }
1761 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1762 if let (Some(color), Some(cell)) = (selection_color, cell) {
1763 let original = unsafe { cell.textColor() };
1764 unsafe {
1767 cell.setTextColor(Some(&color));
1768 let _: () = msg_send![super(self), drawRect: dirty];
1769 cell.setTextColor(original.as_deref());
1770 }
1771 } else {
1772 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1773 }
1774 }
1775 }
1776
1777 unsafe impl NSObjectProtocol for DayLabel {}
1778 unsafe impl NSTextDelegate for DayLabel {}
1779
1780 unsafe impl NSTextViewDelegate for DayLabel {
1781 #[unsafe(method(textView:clickedOnLink:atIndex:))]
1782 fn clicked_on_link(
1783 &self,
1784 _tv: &NSTextView,
1785 link: &objc2::runtime::AnyObject,
1786 _index: usize,
1787 ) -> bool {
1788 ffi_guard::contain(true, || {
1789 let url: Retained<NSString> = unsafe { msg_send![link, description] };
1791 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1792 true })
1794 }
1795 }
1796);
1797
1798impl DayLabel {
1799 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1800 let this = Self::alloc(mtm).set_ivars(LabelIvars {
1801 node,
1802 has_links: Cell::new(false),
1803 has_runs: Cell::new(false),
1804 selectable: Cell::new(false),
1805 });
1806 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1807 unsafe {
1808 this.setStringValue(&NSString::from_str(text));
1809 this.setEditable(false);
1810 this.setSelectable(false);
1811 this.setBordered(false);
1812 this.setBezeled(false);
1813 this.setDrawsBackground(false);
1814 }
1815 this
1816 }
1817
1818 fn set_links(&self, has_links: bool) {
1819 self.ivars().has_links.set(has_links);
1820 unsafe {
1821 self.setSelectable(has_links || self.ivars().selectable.get());
1822 self.setAllowsEditingTextAttributes(has_links);
1823 }
1824 }
1825}
1826
1827struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1828impl Drop for PanMonitor {
1829 fn drop(&mut self) {
1830 unsafe { NSEvent::removeMonitor(&self.0) };
1831 }
1832}
1833
1834fn install_sheet_escape_monitor() {
1839 SHEET_ESCAPE_MONITOR.with(|slot| {
1840 if slot.borrow().is_some() {
1841 return;
1842 }
1843 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1844 let event = unsafe { raw.as_ref() };
1845 ffi_guard::contain(raw.as_ptr(), || {
1846 let Some(mtm) = MainThreadMarker::new() else {
1847 return raw.as_ptr();
1848 };
1849 let escape = unsafe { event.charactersIgnoringModifiers() }
1850 .is_some_and(|s| s.to_string() == "\u{1b}");
1851 let Some(window) = event.window(mtm).filter(|_| escape) else {
1852 return raw.as_ptr();
1853 };
1854 let app = NSApplication::sharedApplication(mtm);
1855 if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1856 return raw.as_ptr();
1857 }
1858 match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1859 Some(node) => {
1860 emit(
1861 node,
1862 Event::NavBack {
1863 already_popped: false,
1864 },
1865 );
1866 std::ptr::null_mut()
1867 }
1868 None => raw.as_ptr(),
1869 }
1870 })
1871 });
1872 let monitor = unsafe {
1873 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1874 objc2_app_kit::NSEventMask::KeyDown,
1875 &block,
1876 )
1877 };
1878 *slot.borrow_mut() = monitor.map(PanMonitor);
1879 });
1880}
1881
1882fn install_container_pan_monitor() {
1885 PAN_MONITOR.with(|slot| {
1886 if slot.borrow().is_some() {
1887 return;
1888 }
1889 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1890 let event = unsafe { raw.as_ref() };
1891 ffi_guard::contain(raw.as_ptr(), || {
1892 let dx = unsafe { event.scrollingDeltaX() };
1893 let dy = unsafe { event.scrollingDeltaY() };
1894 if dx.abs() <= dy.abs() {
1895 return raw.as_ptr();
1896 }
1897 let Some(mtm) = MainThreadMarker::new() else {
1898 return raw.as_ptr();
1899 };
1900 let Some(window) = event.window(mtm) else {
1901 return raw.as_ptr();
1902 };
1903 let Some(content) = window.contentView() else {
1904 return raw.as_ptr();
1905 };
1906 let point =
1907 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1908 let mut view = content.hitTest(point);
1909 while let Some(v) = view {
1910 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1911 if v.downcast_ref::<DayCanvas>().is_some() {
1912 return raw.as_ptr();
1913 }
1914 let raw_phase = unsafe { event.phase() };
1915 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1916 day_spec::DragPhase::Began
1917 } else if raw_phase.intersects(
1918 objc2_app_kit::NSEventPhase::Ended
1919 | objc2_app_kit::NSEventPhase::Cancelled,
1920 ) {
1921 day_spec::DragPhase::Ended
1922 } else {
1923 day_spec::DragPhase::Changed
1924 };
1925 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1926 emit(
1927 node,
1928 Event::Pan {
1929 phase,
1930 delta: Point::new(dx, dy),
1931 location: Point::new(p.x, p.y),
1932 },
1933 );
1934 return std::ptr::null_mut();
1935 }
1936 view = unsafe { v.superview() };
1937 }
1938 raw.as_ptr()
1939 })
1940 });
1941 *slot.borrow_mut() = unsafe {
1942 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1943 objc2_app_kit::NSEventMask::ScrollWheel,
1944 &block,
1945 )
1946 }
1947 .map(PanMonitor);
1948 });
1949}
1950
1951type Surface = (f64, f64, f64, f64, f64);
1957
1958#[derive(Default)]
1959struct FlippedIvars {
1960 surface: Cell<Option<Surface>>,
1961 section_card: Cell<Option<f64>>,
1964 pane_backdrop: Cell<bool>,
1971}
1972
1973define_class!(
1974 #[unsafe(super(NSView))]
1975 #[thread_kind = MainThreadOnly]
1976 #[name = "DayFlipped"]
1977 #[ivars = FlippedIvars]
1978 struct DayFlipped;
1979
1980 impl DayFlipped {
1981 #[unsafe(method_id(menuForEvent:))]
1982 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1983 ffi_guard::contain(None, || {
1984 inherited_context_menu(self, event)
1985 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1986 })
1987 }
1988
1989 #[unsafe(method(isFlipped))]
1990 fn is_flipped(&self) -> bool {
1991 true
1992 }
1993
1994 #[unsafe(method(acceptsFirstResponder))]
1998 fn accepts_first_responder(&self) -> bool {
1999 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2000 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2001 }
2002
2003 #[unsafe(method(mouseDown:))]
2007 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2008 if transfer::pressed(self, event) { return; }
2009 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2010 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2011 && let Some(window) = self.window()
2012 {
2013 window.makeFirstResponder(Some(self));
2014 }
2015 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2016 }
2017
2018 #[unsafe(method(becomeFirstResponder))]
2019 fn become_first_responder(&self) -> bool {
2020 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2021 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2022 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2023 }
2024 true
2025 }
2026
2027 #[unsafe(method(resignFirstResponder))]
2028 fn resign_first_responder(&self) -> bool {
2029 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2030 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2031 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2032 }
2033 true
2034 }
2035
2036 #[unsafe(method(keyDown:))]
2040 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2041 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2042 let handled = ffi_guard::contain(false, || {
2043 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2044 return false;
2045 };
2046 let Some(key) = key_name(event) else {
2047 return false;
2048 };
2049 if !day_spec::keys::handled(node) {
2050 return false;
2051 }
2052 emit(
2053 node,
2054 Event::Key(day_spec::KeyEvent::named(
2055 key,
2056 key_modifiers(event.modifierFlags()),
2057 )),
2058 );
2059 true
2060 });
2061 if !handled {
2062 let _: () = unsafe { msg_send![super(self), keyDown: event] };
2063 }
2064 }
2065
2066 #[unsafe(method(rightMouseDown:))]
2070 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2071 if let Some(menu) = self.menuForEvent(event) {
2072 unsafe {
2073 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self);
2074 };
2075 } else {
2076 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2077 }
2078 }
2079
2080 #[unsafe(method(drawRect:))]
2081 fn draw_rect(&self, _dirty: NSRect) {
2082 let paint = || {
2083 if self.ivars().pane_backdrop.get() {
2084 let bounds = self.bounds();
2085 unsafe {
2086 NSColor::windowBackgroundColor().setFill();
2089 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2090 }
2091 }
2092 if let Some(radius) = self.ivars().section_card.get() {
2093 let bounds = self.bounds();
2094 unsafe {
2095 let cls = objc2::class!(NSColor);
2098 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2099 let color: objc2::rc::Retained<NSColor> = if has {
2100 msg_send![cls, quaternarySystemFillColor]
2101 } else {
2102 msg_send![cls, controlBackgroundColor]
2103 };
2104 color.setFill();
2105 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2106 bounds, radius, radius,
2107 );
2108 path.fill();
2109 }
2110 }
2111 if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
2112 let bounds = self.bounds();
2113 unsafe {
2114 NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
2115 let path = if radius > 0.0 {
2116 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2117 bounds, radius, radius,
2118 )
2119 } else {
2120 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
2121 };
2122 path.fill();
2123 }
2124 }
2125 };
2126 unsafe {
2135 let names = objc2_foundation::NSArray::from_slice(&[
2136 objc2_app_kit::NSAppearanceNameAqua,
2137 objc2_app_kit::NSAppearanceNameDarkAqua,
2138 ]);
2139 let standard = self
2140 .effectiveAppearance()
2141 .bestMatchFromAppearancesWithNames(&names)
2142 .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
2143 match standard {
2144 Some(appearance) => {
2145 let block = block2::StackBlock::new(paint);
2146 appearance.performAsCurrentDrawingAppearance(&block);
2147 }
2148 None => paint(),
2149 }
2150 }
2151 }
2152 }
2153 unsafe impl NSObjectProtocol for DayFlipped {}
2154 unsafe impl NSDraggingSource for DayFlipped {
2155 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2156 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2157 }
2158 impl DayFlipped {
2159 #[unsafe(method(mouseDragged:))]
2160 fn transfer_dragged(&self, event: &NSEvent) {
2161 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
2162 }
2163 #[unsafe(method(draggingEntered:))]
2164 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2165 #[unsafe(method(draggingUpdated:))]
2166 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2167 #[unsafe(method(performDragOperation:))]
2168 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
2169 }
2170
2171);
2172
2173impl DayFlipped {
2174 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2175 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
2176 unsafe { msg_send![super(this), init] }
2177 }
2178
2179 fn set_section_card(&self, corner_radius: f64) {
2185 self.ivars().section_card.set(Some(corner_radius));
2186 unsafe {
2187 let _: () = msg_send![self, setNeedsDisplay: true];
2188 }
2189 }
2190
2191 fn set_pane_backdrop(&self) {
2193 self.ivars().pane_backdrop.set(true);
2194 unsafe {
2195 let _: () = msg_send![self, setNeedsDisplay: true];
2196 }
2197 }
2198
2199 fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
2200 self.ivars()
2201 .surface
2202 .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
2203 unsafe {
2204 let _: () = msg_send![self, setNeedsDisplay: true];
2205 if clips || corner_radius > 0.0 {
2206 let _: () = msg_send![self, setWantsLayer: true];
2207 let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
2208 if !layer.is_null() {
2209 let _: () = msg_send![layer, setCornerRadius: corner_radius];
2210 let _: () = msg_send![layer, setMasksToBounds: true];
2211 }
2212 }
2213 }
2214 }
2215}
2216
2217struct CanvasIvars;
2222
2223define_class!(
2224 #[unsafe(super(NSView))]
2225 #[thread_kind = MainThreadOnly]
2226 #[name = "DayCanvas"]
2227 #[ivars = CanvasIvars]
2228 struct DayCanvas;
2229
2230 impl DayCanvas {
2231 #[unsafe(method(isFlipped))]
2232 fn is_flipped(&self) -> bool {
2233 true
2234 }
2235
2236 #[unsafe(method_id(menuForEvent:))]
2240 fn menu_for_event(
2241 &self,
2242 event: &objc2_app_kit::NSEvent,
2243 ) -> Option<Retained<NSMenu>> {
2244 let f = CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<Self>(self) as usize));
2245 let Some(f) = f else {
2246 return unsafe { msg_send![super(self), menuForEvent: event] };
2247 };
2248 ffi_guard::contain(None, || {
2250 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2251 let items = f(day_spec::Point::new(p.x, p.y));
2252 if items.is_empty() {
2253 return None;
2254 }
2255 Some(build_ns_menu(self.mtm(), "", &items))
2256 })
2257 }
2258
2259 #[unsafe(method(acceptsFirstResponder))]
2264 fn accepts_first_responder(&self) -> bool {
2265 true
2266 }
2267
2268 #[unsafe(method(mouseDown:))]
2272 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2273 if let Some(window) = self.window() {
2274 window.makeFirstResponder(Some(self));
2275 }
2276 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2277 }
2278
2279 #[unsafe(method(becomeFirstResponder))]
2282 fn become_first_responder(&self) -> bool {
2283 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2284 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2285 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2286 }
2287 true
2288 }
2289
2290 #[unsafe(method(resignFirstResponder))]
2291 fn resign_first_responder(&self) -> bool {
2292 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2293 if MARKED.with(|t| t.remove(ptr)).is_some()
2296 && let Some(context) = self.inputContext()
2297 {
2298 context.discardMarkedText();
2299 }
2300 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2301 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2302 }
2303 true
2304 }
2305
2306 #[unsafe(method(keyDown:))]
2312 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2313 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2314 let handled = ffi_guard::contain(false, || {
2315 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2316 return false;
2317 };
2318 if !day_spec::keys::handled(node) {
2322 return false;
2323 }
2324 if day_spec::keys::text(node) {
2325 return full_route_key_down(self, node, event);
2326 }
2327 let Some(key) = key_name(event) else {
2328 return false;
2329 };
2330 emit(
2331 node,
2332 Event::Key(day_spec::KeyEvent::named(
2333 key,
2334 key_modifiers(event.modifierFlags()),
2335 )),
2336 );
2337 true
2338 });
2339 if !handled {
2340 let _: () = unsafe { msg_send![super(self), keyDown: event] };
2341 }
2342 }
2343
2344 #[unsafe(method_id(inputContext))]
2349 fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
2350 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2351 let takes_keyboard = KEY_NODES
2352 .with(|t| t.get(ptr))
2353 .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
2354 if takes_keyboard {
2355 unsafe { msg_send![super(self), inputContext] }
2356 } else {
2357 None
2358 }
2359 }
2360
2361 #[unsafe(method(drawRect:))]
2362 fn draw_rect(&self, _dirty: NSRect) {
2363 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2364 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
2365 paint_ops(&ops);
2366 }
2367
2368 #[unsafe(method(mouseEntered:))]
2371 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
2372 self.report_hover(event, day_spec::DragPhase::Began);
2373 }
2374
2375 #[unsafe(method(mouseMoved:))]
2376 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
2377 self.report_hover(event, day_spec::DragPhase::Changed);
2378 }
2379
2380 #[unsafe(method(mouseExited:))]
2381 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
2382 self.report_hover(event, day_spec::DragPhase::Ended);
2383 }
2384
2385 #[unsafe(method(rotateWithEvent:))]
2390 fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
2391 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2392 let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
2393 let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
2394 return;
2395 };
2396 ffi_guard::contain((), || {
2397 let tick = -f64::from(event.rotation()).to_radians();
2398 let raw = event.phase();
2399 let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2400 ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
2401 (day_spec::DragPhase::Began, tick)
2402 } else if raw.intersects(
2403 objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
2404 ) {
2405 let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
2406 (day_spec::DragPhase::Ended, total)
2407 } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
2408 let total = ROTATE_ANGLE
2409 .with(|t| {
2410 t.with(ptr, |a| {
2411 *a += tick;
2412 *a
2413 })
2414 })
2415 .unwrap_or(tick);
2416 (day_spec::DragPhase::Changed, total)
2417 } else {
2418 (day_spec::DragPhase::Changed, tick)
2419 };
2420 let win = event.locationInWindow();
2421 let loc = self.convertPoint_fromView(win, None);
2422 emit(
2423 node,
2424 Event::Rotate {
2425 phase,
2426 rotation,
2427 location: Point::new(loc.x, loc.y),
2428 },
2429 );
2430 });
2431 }
2432
2433 #[unsafe(method(scrollWheel:))]
2434 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
2435 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2436 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
2437 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
2438 return;
2439 };
2440 ffi_guard::contain((), || {
2441 let raw = unsafe { event.phase() };
2444 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2445 day_spec::DragPhase::Began
2446 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
2447 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
2448 {
2449 day_spec::DragPhase::Ended
2450 } else {
2451 day_spec::DragPhase::Changed
2452 };
2453 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
2454 event.scrollingDeltaY()
2455 });
2456 let win = unsafe { event.locationInWindow() };
2457 let loc = self.convertPoint_fromView(win, None);
2458 emit(
2459 node,
2460 Event::Pan {
2461 phase,
2462 delta,
2463 location: Point::new(loc.x, loc.y),
2464 },
2465 );
2466 });
2467 }
2468 }
2469
2470 unsafe impl NSObjectProtocol for DayCanvas {}
2471
2472 unsafe impl NSTextInputClient for DayCanvas {
2476 #[unsafe(method(insertText:replacementRange:))]
2477 unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
2478 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2479 MARKED.with(|t| t.remove(ptr));
2480 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2481 return;
2482 };
2483 let text = text_of_input_string(string);
2484 if text.is_empty() {
2485 return;
2486 }
2487 ffi_guard::contain((), || {
2488 let interpreting = INTERPRETING.with(|i| i.borrow().clone());
2489 let event = match interpreting {
2490 Some((key, mods)) if text.chars().count() == 1 => {
2492 day_spec::KeyEvent::typed_by(key, text, mods)
2493 }
2494 Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
2495 None => day_spec::KeyEvent::typed_text(text, 0),
2497 };
2498 emit(node, Event::Key(event));
2499 });
2500 }
2501
2502 #[unsafe(method(doCommandBySelector:))]
2507 unsafe fn do_command_by_selector(&self, _selector: Sel) {}
2508
2509 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
2510 unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2511 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2512 let text = text_of_input_string(string);
2513 if text.is_empty() {
2514 MARKED.with(|t| t.remove(ptr));
2515 } else {
2516 MARKED.with(|t| t.insert(ptr, text));
2517 }
2518 }
2519
2520 #[unsafe(method(unmarkText))]
2521 fn unmark_text(&self) {
2522 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2523 MARKED.with(|t| t.remove(ptr));
2524 }
2525
2526 #[unsafe(method(selectedRange))]
2527 fn selected_range(&self) -> NSRange {
2528 NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2529 }
2530
2531 #[unsafe(method(markedRange))]
2532 fn marked_range(&self) -> NSRange {
2533 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2534 match MARKED.with(|t| t.get(ptr)) {
2535 Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2536 None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2537 }
2538 }
2539
2540 #[unsafe(method(hasMarkedText))]
2541 fn has_marked_text(&self) -> bool {
2542 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2543 MARKED.with(|t| t.contains(ptr))
2544 }
2545
2546 #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2547 unsafe fn attributed_substring(
2548 &self,
2549 _range: NSRange,
2550 _actual: objc2_foundation::NSRangePointer,
2551 ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2552 None
2553 }
2554
2555 #[unsafe(method_id(validAttributesForMarkedText))]
2556 fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2557 NSArray::new()
2558 }
2559
2560 #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2563 unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2564 let bounds = self.bounds();
2565 let in_window = self.convertRect_toView(bounds, None);
2566 match self.window() {
2567 Some(window) => window.convertRectToScreen(in_window),
2568 None => in_window,
2569 }
2570 }
2571
2572 #[unsafe(method(characterIndexForPoint:))]
2573 fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2574 objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2575 }
2576 }
2577);
2578
2579impl DayCanvas {
2580 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2581 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2582 unsafe { msg_send![super(this), init] }
2583 }
2584
2585 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2593 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2594 let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2595 return;
2596 };
2597 ffi_guard::contain((), || {
2598 let win = unsafe { event.locationInWindow() };
2599 let loc = self.convertPoint_fromView(win, None);
2600 let b = self.bounds();
2601 let inside = loc.x >= b.origin.x
2602 && loc.x <= b.origin.x + b.size.width
2603 && loc.y >= b.origin.y
2604 && loc.y <= b.origin.y + b.size.height;
2605 if !inside && phase != day_spec::DragPhase::Ended {
2608 return;
2609 }
2610 emit(
2611 node,
2612 Event::Hover {
2613 phase,
2614 location: Point::new(loc.x, loc.y),
2615 },
2616 );
2617 });
2618 }
2619}
2620
2621fn install_tracking_area(h: &NSView) {
2625 let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2626 | NSTrackingAreaOptions::MouseMoved
2627 | NSTrackingAreaOptions::ActiveInKeyWindow
2628 | NSTrackingAreaOptions::InVisibleRect;
2629 let any: &objc2::runtime::AnyObject = h;
2630 let area = unsafe {
2631 NSTrackingArea::initWithRect_options_owner_userInfo(
2632 NSTrackingArea::alloc(),
2633 NSRect::ZERO,
2634 opts,
2635 Some(any),
2636 None,
2637 )
2638 };
2639 unsafe { h.addTrackingArea(&area) };
2640}
2641
2642struct GestureIvars {
2647 node: NodeId,
2648 kind: day_spec::GestureKind,
2649}
2650
2651define_class!(
2652 #[unsafe(super(NSObject))]
2653 #[thread_kind = MainThreadOnly]
2654 #[name = "DayGesture"]
2655 #[ivars = GestureIvars]
2656 struct DayGesture;
2657
2658 unsafe impl NSObjectProtocol for DayGesture {}
2659
2660 impl DayGesture {
2661 #[unsafe(method(fire:))]
2662 fn fire(&self, g: &NSGestureRecognizer) {
2663 ffi_guard::contain((), || {
2664 let node = self.ivars().node;
2665 let view = g.view();
2666 let loc = g.locationInView(view.as_deref());
2667 let at = Point::new(loc.x, loc.y);
2668 let phase = match g.state() {
2669 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2670 NSGestureRecognizerState::Ended
2671 | NSGestureRecognizerState::Cancelled
2672 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2673 _ => day_spec::DragPhase::Changed,
2674 };
2675 let obj: &objc2::runtime::AnyObject = g.as_ref();
2676 match self.ivars().kind {
2677 day_spec::GestureKind::Drag => {
2678 let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2679 let t = unsafe { pan.translationInView(view.as_deref()) };
2680 Point::new(t.x, t.y)
2681 } else {
2682 Point::ZERO
2683 };
2684 emit(node, Event::Drag { phase, location: at, translation });
2685 }
2686 day_spec::GestureKind::Pinch => {
2687 let scale = if let Some(m) =
2690 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2691 {
2692 1.0 + unsafe { m.magnification() }
2693 } else {
2694 1.0
2695 };
2696 emit(node, Event::Pinch { phase, scale, location: at });
2697 }
2698 _ => emit(node, Event::Tap(at)),
2699 }
2700 });
2701 }
2702 }
2703);
2704
2705impl DayGesture {
2706 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2707 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2708 unsafe { msg_send![super(this), init] }
2709 }
2710}
2711
2712struct NavHeader {
2721 bar: Retained<NSView>,
2722 title: Retained<NSTextField>,
2723 titles: Vec<String>,
2725 _target: Retained<DayTarget>,
2726}
2727
2728const NAV_HEADER_H: f64 = 34.0;
2730
2731use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2735
2736fn take_list_placement(state: &mut NavState) -> Option<f64> {
2740 if !state.list_visible || state.list_positioned {
2741 return None;
2742 }
2743 state.list_positioned = true;
2744 state.list_width
2745}
2746
2747const NAV_TABVIEW_INSET: f64 = 12.0;
2750const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2751
2752struct TabHost {
2764 view: Retained<objc2_app_kit::NSTabView>,
2765 target: Option<Retained<DayTarget>>,
2768}
2769
2770thread_local! {
2771 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2774}
2775
2776fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2780 unsafe {
2781 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2782 for (i, title) in titles.iter().enumerate().take(n) {
2783 tabs.view
2784 .tabViewItemAtIndex(i as isize)
2785 .setLabel(&NSString::from_str(title));
2786 }
2787 if n > 0 {
2788 TAB_PICK_SUPPRESS.with(|s| s.set(true));
2789 tabs.view
2790 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2791 TAB_PICK_SUPPRESS.with(|s| s.set(false));
2792 }
2793 }
2794}
2795
2796fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2800 let Some((titles, node)) = NAV_MENUS.with(|m| {
2801 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2802 let ivars = d.ivars();
2803 (
2804 ivars
2805 .items
2806 .borrow()
2807 .iter()
2808 .map(std::string::ToString::to_string)
2809 .collect::<Vec<String>>(),
2810 ivars.node,
2811 )
2812 })
2813 }) else {
2814 return;
2815 };
2816 let mut up = unsafe { menu.superview() };
2817 while let Some(v) = up {
2818 let reached = NAV_STATE.with(|m| {
2819 let mut m = m.borrow_mut();
2820 let Some(s) = m.get_mut(&ptr_of(&v)) else {
2821 return false;
2822 };
2823 let selected = s.selected;
2824 if let Some(tabs) = s.tabs.as_mut() {
2825 if tabs.target.is_none() {
2826 let target = DayTarget::new(mtm, node);
2827 unsafe {
2828 tabs.view
2829 .setDelegate(Some(ProtocolObject::from_ref(&*target)));
2830 };
2831 tabs.target = Some(target);
2832 }
2833 sync_tab_labels(tabs, &titles, selected);
2834 }
2835 true
2836 });
2837 if reached {
2838 return;
2839 }
2840 up = unsafe { v.superview() };
2841 }
2842}
2843
2844struct NavState {
2845 sidebar_wrap: Retained<NSView>,
2846 detail_wrap: Retained<NSView>,
2847 split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2852 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2856 list_wrap: Option<Retained<NSView>>,
2862 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2863 list_width: Option<f64>,
2866 list_visible: bool,
2870 list_positioned: bool,
2876 pages: Vec<Retained<NSView>>,
2879 sidebar_page: Option<Retained<NSView>>,
2882 list_page: Option<Retained<NSView>>,
2885 positioned: bool,
2886 presentation: NavPresentation,
2890 selected: usize,
2893 tabs: Option<TabHost>,
2897 header: Option<NavHeader>,
2899 root_title: String,
2902 node: NodeId,
2904 title_strip: f64,
2908}
2909
2910fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2922 let pane = view_of(&DayFlipped::new(mtm));
2923 unsafe {
2924 wrap.setFrame(pane.bounds());
2925 wrap.setAutoresizingMask(
2926 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2927 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2928 );
2929 pane.addSubview(wrap);
2930 }
2931 pane
2932}
2933
2934fn place_below_strip(wrap: &NSView, strip: f64) {
2936 let Some(pane) = (unsafe { wrap.superview() }) else {
2937 return;
2938 };
2939 let b = pane.bounds();
2940 unsafe {
2941 wrap.setFrame(NSRect::new(
2942 NSPoint::new(0.0, strip),
2943 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2944 ));
2945 };
2946}
2947
2948fn build_nav_header(
2956 mtm: MainThreadMarker,
2957 id: NodeId,
2958 detail_wrap: &NSView,
2959 root_title: &str,
2960) -> NavHeader {
2961 let bar = view_of(&DayFlipped::new(mtm));
2962 let target = DayTarget::new(mtm, id);
2963 let back = unsafe {
2964 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2967 .expect("NSGoBackTemplate");
2968 let tobj: &objc2::runtime::AnyObject = target.as_ref();
2969 objc2_app_kit::NSButton::buttonWithImage_target_action(
2970 &img,
2971 Some(tobj),
2972 Some(sel!(navBack:)),
2973 mtm,
2974 )
2975 };
2976 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2977 unsafe {
2978 back.setFrame(NSRect::new(
2979 NSPoint::new(6.0, 4.0),
2980 NSSize::new(30.0, NAV_HEADER_H - 8.0),
2981 ));
2982 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2983 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2984 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2985 title.setFrame(NSRect::new(
2986 NSPoint::new(44.0, 9.0),
2987 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2988 ));
2989 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2990 bar.setFrame(NSRect::new(
2991 NSPoint::new(0.0, 0.0),
2992 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2993 ));
2994 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2995 bar.addSubview(&back);
2996 bar.addSubview(&title);
2997 bar.setHidden(true);
2998 detail_wrap.addSubview(&bar);
2999 }
3000 NavHeader {
3001 bar,
3002 title,
3003 titles: vec![root_title.to_string()],
3004 _target: target,
3005 }
3006}
3007
3008fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
3012 let b = wrap.bounds();
3013 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
3014 NSRect::new(
3015 NSPoint::new(0.0, top),
3016 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
3017 )
3018}
3019
3020fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
3027 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
3028 if out.is_some() {
3029 return;
3030 }
3031 let found = NAV_MENUS.with(|m| {
3032 m.borrow()
3033 .get(&(std::ptr::from_ref::<NSView>(v) as usize))
3034 .map(|(_, d)| {
3035 let ivars = d.ivars();
3036 (
3037 ivars
3038 .items
3039 .borrow()
3040 .iter()
3041 .map(std::string::ToString::to_string)
3042 .collect(),
3043 ivars.node,
3044 )
3045 })
3046 });
3047 if found.is_some() {
3048 *out = found;
3049 return;
3050 }
3051 for sub in &unsafe { v.subviews() } {
3052 walk(&sub, out);
3053 }
3054 }
3055 let mut out = None;
3056 walk(page, &mut out);
3057 out
3058}
3059
3060fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
3063 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
3064 unsafe {
3065 item.setCanCollapse(shown);
3066 item.setCollapsed(!shown);
3067 match pres {
3068 NavPresentation::Split | NavPresentation::Rail => {
3074 item.setAllowsFullHeightLayout(true);
3075 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3076 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3077 }
3078 NavPresentation::Stack | NavPresentation::Tabs => {
3081 item.setMinimumThickness(0.0);
3082 item.setMaximumThickness(0.0);
3083 }
3084 }
3085 }
3086}
3087
3088pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
3094 NAV_STATE.with(|m| {
3095 m.borrow()
3096 .values()
3097 .find(|st| {
3098 st.list_item.is_some()
3099 && st
3100 .sidebar_wrap
3101 .window()
3102 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
3103 })
3104 .map(|st| unsafe { st.split_vc.splitView() })
3105 })
3106}
3107
3108fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
3109 let visible = pages.len() >= 2;
3110 hdr.bar.setHidden(!visible);
3111 unsafe {
3112 hdr.title.setStringValue(&NSString::from_str(
3113 hdr.titles.last().map_or("", String::as_str),
3114 ));
3115 }
3116 let frame = nav_page_frame(wrap, visible);
3117 for page in pages {
3118 unsafe { page.setFrame(frame) };
3119 }
3120}
3121
3122fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
3137 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
3138 NAV_STATE.with(|m| {
3139 let st = m.borrow();
3140 let s = st.get(&ptr_of(host))?;
3141 Some((
3142 s.sidebar_page.clone(),
3143 s.detail_wrap.clone(),
3144 s.sidebar_wrap.clone(),
3145 s.sidebar_item.clone(),
3146 s.presentation,
3147 s.root_title.clone(),
3148 s.node,
3149 s.selected,
3150 ))
3151 })
3152 else {
3153 return;
3154 };
3155 if was == next {
3156 return;
3157 }
3158 apply_sidebar_item(&sidebar_item, next);
3159 NAV_STATE.with(|m| {
3164 if let Some(s) = m.borrow().get(&ptr_of(host)) {
3165 unsafe { s.split_vc.splitView().layoutSubtreeIfNeeded() };
3166 }
3167 });
3168 let stacked = next == NavPresentation::Stack;
3171 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
3172 if stacked && header.is_none() {
3173 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
3174 }
3175 if let Some(hdr) = header.as_ref() {
3176 hdr.bar.setHidden(true);
3177 }
3178 let mut pages = NAV_STATE.with(|m| {
3184 m.borrow()
3185 .get(&ptr_of(host))
3186 .map_or_default(|s| s.pages.clone())
3187 });
3188 let shown_page = pages.get(sel).cloned();
3189 if let Some(page) = sidebar_page {
3192 pages.retain(|p| ptr_of(p) != ptr_of(&page));
3193 unsafe {
3194 if stacked {
3195 detail_wrap.addSubview(&page);
3196 pages.insert(0, page.clone());
3197 } else {
3198 page.setFrame(sidebar_wrap.bounds());
3199 sidebar_wrap.addSubview(&page);
3200 }
3201 }
3202 page.setHidden(false);
3204 }
3205 let shown = shown_page
3206 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
3207 .unwrap_or_else(|| pages.len().saturating_sub(1));
3208 for (i, page) in pages.iter().enumerate() {
3209 page.setHidden(i != shown);
3210 }
3211 NAV_STATE.with(|m| {
3212 let mut m = m.borrow_mut();
3213 if let Some(s) = m.get_mut(&ptr_of(host)) {
3214 s.presentation = next;
3215 s.pages = pages;
3216 s.selected = shown;
3217 s.header = header;
3218 if let Some(hdr) = s.header.as_ref() {
3219 if stacked {
3221 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
3222 } else {
3223 hdr.bar.setHidden(true);
3224 }
3225 }
3226 if !stacked {
3227 let frame = nav_page_frame(&s.detail_wrap, false);
3230 for page in &s.pages {
3231 unsafe { page.setFrame(frame) };
3232 }
3233 }
3234 }
3235 });
3236}
3237
3238struct CoverSheet(Retained<NSWindow>);
3247impl Drop for CoverSheet {
3248 fn drop(&mut self) {
3249 let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
3251 let raw = Retained::into_raw(self.0.clone()) as usize;
3254 dispatch2::DispatchQueue::main().exec_async(move || {
3255 ffi_guard::contain((), || unsafe {
3256 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
3257 if let Some(parent) = window.sheetParent() {
3258 parent.endSheet(&window);
3259 }
3260 window.orderOut(None);
3261 window.setContentView(None);
3262 });
3263 });
3264 }
3265}
3266struct NavPageIvars {
3267 node: NodeId,
3268 top_inset: Cell<f64>,
3272 sheet: Cell<bool>,
3273 half: Cell<bool>,
3275 large: Cell<bool>,
3278}
3279
3280define_class!(
3281 #[unsafe(super(NSView))]
3282 #[thread_kind = MainThreadOnly]
3283 #[name = "DayNavPage"]
3284 #[ivars = NavPageIvars]
3285 struct DayNavPage;
3286
3287 impl DayNavPage {
3288 #[unsafe(method(isFlipped))]
3289 fn is_flipped(&self) -> bool {
3290 true
3291 }
3292
3293 #[unsafe(method(setFrameSize:))]
3294 fn set_frame_size(&self, size: NSSize) {
3295 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3296 ffi_guard::contain((), || {
3299 let inset = self.ivars().top_inset.get();
3300 emit(
3301 self.ivars().node,
3302 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
3303 );
3304 });
3305 }
3306 }
3307);
3308
3309impl DayNavPage {
3310 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
3311 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
3312 node,
3313 top_inset: Cell::new(0.0),
3314 sheet: Cell::new(false),
3315 half: Cell::new(false),
3316 large: Cell::new(false),
3317 });
3318 unsafe { msg_send![super(this), init] }
3319 }
3320}
3321
3322struct InspectorState {
3331 content_wrap: Handle,
3332 panel_wrap: Handle,
3333 split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3335 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
3336}
3337
3338struct SplitState {
3346 split: Retained<objc2_app_kit::NSSplitView>,
3347 first_wrap: Handle,
3348 second_wrap: Handle,
3349 delegate: Retained<DaySplitDelegate>,
3350}
3351
3352struct SplitDelegateIvars {
3353 node: NodeId,
3354 min_pane: f64,
3355 share: Cell<f64>,
3358 positioned: Cell<bool>,
3360 suppress: Cell<bool>,
3362}
3363
3364define_class!(
3365 #[unsafe(super(NSObject))]
3366 #[thread_kind = MainThreadOnly]
3367 #[name = "DaySplitDelegate"]
3368 #[ivars = SplitDelegateIvars]
3369 struct DaySplitDelegate;
3370
3371 unsafe impl NSObjectProtocol for DaySplitDelegate {}
3372
3373 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
3374 #[unsafe(method(splitViewDidResizeSubviews:))]
3375 fn did_resize(&self, notification: &NSNotification) {
3376 ffi_guard::contain((), || {
3377 let Some(obj) = notification.object() else {
3378 return;
3379 };
3380 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
3381 return;
3382 };
3383 let iv = self.ivars();
3384 let usable = split_usable(&sv);
3385 if usable <= 0.0 {
3386 return;
3387 }
3388 if !iv.positioned.replace(true) {
3390 split_place(&sv, iv);
3391 return;
3392 }
3393 if iv.suppress.get() {
3394 return;
3395 }
3396 let Some(first) = sv.subviews().iter().next() else {
3397 return;
3398 };
3399 let f = first.frame();
3400 let a = if sv.isVertical() {
3401 f.size.width
3402 } else {
3403 f.size.height
3404 };
3405 let share = (a / usable).clamp(0.0, 1.0);
3406 if (share - iv.share.get()).abs() > 1e-4 {
3407 iv.share.set(share);
3408 emit(iv.node, Event::ValueChanged(share));
3409 }
3410 });
3411 }
3412
3413 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
3414 fn constrain_min(
3415 &self,
3416 _sv: &objc2_app_kit::NSSplitView,
3417 proposed: f64,
3418 _index: isize,
3419 ) -> f64 {
3420 proposed.max(self.ivars().min_pane)
3421 }
3422
3423 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
3424 fn constrain_max(
3425 &self,
3426 sv: &objc2_app_kit::NSSplitView,
3427 proposed: f64,
3428 _index: isize,
3429 ) -> f64 {
3430 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
3431 }
3432 }
3433);
3434
3435impl DaySplitDelegate {
3436 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
3437 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
3438 node,
3439 min_pane,
3440 share: Cell::new(share.clamp(0.0, 1.0)),
3441 positioned: Cell::new(false),
3442 suppress: Cell::new(false),
3443 });
3444 unsafe { msg_send![super(this), init] }
3445 }
3446}
3447
3448fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
3450 let frame = sv.frame();
3451 let len = if sv.isVertical() {
3452 frame.size.width
3453 } else {
3454 frame.size.height
3455 };
3456 (len - sv.dividerThickness()).max(0.0)
3457}
3458
3459fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
3461 let usable = split_usable(sv);
3462 if usable <= 0.0 {
3463 return;
3464 }
3465 iv.suppress.set(true);
3466 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
3467 iv.suppress.set(false);
3468}
3469
3470struct NavMenuIvars {
3477 node: NodeId,
3478 items: RefCell<Vec<Retained<NSString>>>,
3479 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3483 icon_fills: RefCell<Vec<f64>>,
3486 tints: RefCell<Vec<Option<day_spec::Color>>>,
3489 badges: RefCell<Vec<Option<Retained<NSString>>>>,
3491 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
3494 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3495 badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
3497 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
3500 movable: RefCell<Vec<bool>>,
3502 regroup: std::cell::Cell<bool>,
3504 sorted: RefCell<Vec<bool>>,
3506 rows: RefCell<Vec<Option<usize>>>,
3510 row_objects: RefCell<Vec<Retained<NSString>>>,
3512 row_ids: RefCell<Vec<Retained<NSNumber>>>,
3517 suppress: std::cell::Cell<bool>,
3519}
3520
3521struct NavCellIvars {
3522 accessory: RefCell<Option<Retained<NSView>>>,
3525 count: RefCell<Option<Retained<NSTextField>>>,
3527 icon_fill: std::cell::Cell<f64>,
3529}
3530
3531define_class!(
3532 #[unsafe(super(objc2_app_kit::NSTableCellView))]
3537 #[thread_kind = MainThreadOnly]
3538 #[name = "DayNavCell"]
3539 #[ivars = NavCellIvars]
3540 struct DayNavCell;
3541
3542 unsafe impl NSObjectProtocol for DayNavCell {}
3543
3544 impl DayNavCell {
3545 #[unsafe(method(layout))]
3546 fn layout(&self) {
3547 let _: () = unsafe { msg_send![super(self), layout] };
3548 ffi_guard::contain((), || self.fit_accessories());
3549 }
3550 }
3551);
3552
3553impl DayNavCell {
3554 fn new(mtm: MainThreadMarker) -> Retained<Self> {
3555 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3556 accessory: RefCell::new(None),
3557 count: RefCell::new(None),
3558 icon_fill: std::cell::Cell::new(1.0),
3559 });
3560 unsafe { msg_send![super(this), init] }
3561 }
3562
3563 fn fit_accessories(&self) {
3568 let label = unsafe { self.textField() };
3569 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3570 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3571 (f.pointSize() - 2.0).max(9.0)
3572 });
3573 #[expect(
3574 clippy::float_cmp,
3575 reason = "unchanged-value check against the exact size set below"
3576 )]
3577 let resize = unsafe { count.font() }.is_none_or(|f| f.pointSize() != size);
3578 if resize {
3579 unsafe {
3580 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3581 size,
3582 objc2_app_kit::NSFontWeightRegular,
3583 )));
3584 }
3585 self.layoutSubtreeIfNeeded();
3586 }
3587 }
3588 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3589 let mut frame = label.frame();
3590 let end = accessory.frame().origin.x - 6.0;
3591 if frame.origin.x + frame.size.width > end {
3592 frame.size.width = (end - frame.origin.x).max(0.0);
3593 label.setFrame(frame);
3594 }
3595 }
3596 if let Some(icon) = unsafe { self.imageView() } {
3597 fit_nav_icon(&icon, self.ivars().icon_fill.get());
3598 nav_progress::fit(&icon);
3599 }
3600 }
3601}
3602
3603thread_local! {
3604 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3606}
3607
3608fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3617 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3618 return;
3619 };
3620 let slot = icon.frame();
3621 let key = config.hash() as u64;
3624 let side = NAV_GLYPH_SIDES
3625 .with(|m| m.borrow().get(&key).copied())
3626 .or_else(|| {
3627 let symbol =
3628 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3629 &NSString::from_str("gearshape"),
3630 None,
3631 )?;
3632 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3633 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3634 Some(side)
3635 });
3636 let Some(side) = side
3639 .filter(|s| *s > 0.0)
3640 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3641 else {
3642 return;
3643 };
3644 if slot.size.width <= side && slot.size.height <= side {
3645 return;
3646 }
3647 icon.setFrame(NSRect::new(
3648 NSPoint::new(
3649 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3650 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3651 ),
3652 NSSize::new(side, side),
3653 ));
3654}
3655
3656define_class!(
3657 #[unsafe(super(objc2_app_kit::NSTableRowView))]
3658 #[thread_kind = MainThreadOnly]
3659 #[name = "DayNavRowView"]
3660 struct DayNavRowView;
3661
3662 unsafe impl NSObjectProtocol for DayNavRowView {}
3663
3664 impl DayNavRowView {
3665 #[unsafe(method(isEmphasized))]
3671 fn is_emphasized(&self) -> bool {
3672 true
3673 }
3674 }
3675);
3676
3677define_class!(
3678 #[unsafe(super(objc2_app_kit::NSOutlineView))]
3679 #[thread_kind = MainThreadOnly]
3680 #[name = "DayNavOutlineView"]
3681 struct DayNavOutlineView;
3682
3683 unsafe impl NSObjectProtocol for DayNavOutlineView {}
3684
3685 impl DayNavOutlineView {
3686 #[unsafe(method_id(menuForEvent:))]
3690 fn menu_for_event(
3691 &self,
3692 event: &objc2_app_kit::NSEvent,
3693 ) -> Option<Retained<NSMenu>> {
3694 ffi_guard::contain(None, || {
3695 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3696 let row = unsafe { self.rowAtPoint(point) };
3697 let data = NAV_OUTLINE_MENUS.with(|t| t.get(std::ptr::from_ref(self) as usize));
3698 match data {
3700 None => None,
3701 Some(d) => {
3702 let items = d
3703 .item_of_row(row)
3704 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3705 .unwrap_or_default();
3706 if items.is_empty() {
3707 None
3708 } else {
3709 Some(build_ns_menu(d.mtm(), "", &items))
3710 }
3711 }
3712 }
3713 })
3714 }
3715 }
3716);
3717
3718define_class!(
3719 #[unsafe(super(NSObject))]
3720 #[thread_kind = MainThreadOnly]
3721 #[name = "DayNavMenuData"]
3722 #[ivars = NavMenuIvars]
3723 struct DayNavMenuData;
3724
3725 unsafe impl NSObjectProtocol for DayNavMenuData {}
3726
3727 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3728 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3729 fn number_of_children(
3730 &self,
3731 _ov: &objc2_app_kit::NSOutlineView,
3732 item: Option<&objc2::runtime::AnyObject>,
3733 ) -> isize {
3734 if item.is_none() {
3735 self.ivars().row_objects.borrow().len() as isize
3736 } else {
3737 0
3738 }
3739 }
3740
3741 #[unsafe(method_id(outlineView:child:ofItem:))]
3742 fn child_of_item(
3743 &self,
3744 _ov: &objc2_app_kit::NSOutlineView,
3745 index: isize,
3746 _item: Option<&objc2::runtime::AnyObject>,
3747 ) -> Retained<objc2::runtime::AnyObject> {
3748 let ids = self.ivars().row_ids.borrow();
3749 let id = ids
3753 .get(index as usize)
3754 .cloned()
3755 .unwrap_or_else(|| NSNumber::new_isize(-1));
3756 unsafe { objc2::rc::Retained::cast_unchecked(id) }
3757 }
3758
3759 #[unsafe(method(outlineView:isItemExpandable:))]
3760 fn is_expandable(
3761 &self,
3762 _ov: &objc2_app_kit::NSOutlineView,
3763 _item: &objc2::runtime::AnyObject,
3764 ) -> bool {
3765 false
3766 }
3767
3768 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3775 fn pasteboard_writer_for_item(
3776 &self,
3777 _ov: &objc2_app_kit::NSOutlineView,
3778 item: &objc2::runtime::AnyObject,
3779 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3780 let make = || {
3781 let row = Self::outline_row(item);
3782 let index = self.item_of_row(row)?;
3783 if !self.is_movable(index) {
3784 return None;
3785 }
3786 let pbitem = objc2_app_kit::NSPasteboardItem::new();
3787 unsafe {
3788 pbitem.setString_forType(
3789 &NSString::from_str(&row.to_string()),
3790 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3791 );
3792 }
3793 Some(ProtocolObject::from_retained(pbitem))
3794 };
3795 ffi_guard::contain(None, make)
3796 }
3797
3798 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3799 fn validate_drop(
3800 &self,
3801 ov: &objc2_app_kit::NSOutlineView,
3802 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3803 item: Option<&objc2::runtime::AnyObject>,
3804 child_index: isize,
3805 ) -> objc2_app_kit::NSDragOperation {
3806 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3807 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3808 return objc2_app_kit::NSDragOperation::None;
3809 };
3810 if drop.retarget {
3812 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3813 }
3814 objc2_app_kit::NSDragOperation::Move
3815 })
3816 }
3817
3818 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3819 fn accept_drop(
3820 &self,
3821 ov: &objc2_app_kit::NSOutlineView,
3822 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3823 item: Option<&objc2::runtime::AnyObject>,
3824 child_index: isize,
3825 ) -> bool {
3826 ffi_guard::contain(false, || {
3827 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3828 return false;
3829 };
3830 match drop.moves {
3833 Some(NavMove::Reorder { from, to }) => {
3834 emit(self.ivars().node, Event::ListReorder { from, to });
3835 }
3836 Some(NavMove::Regroup {
3837 from,
3838 section,
3839 before,
3840 }) => emit(
3841 self.ivars().node,
3842 Event::NavRegroup {
3843 from,
3844 section,
3845 before,
3846 },
3847 ),
3848 None => {}
3849 }
3850 true
3851 })
3852 }
3853 }
3854
3855 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3856
3857 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3858 #[unsafe(method(outlineView:isGroupItem:))]
3861 fn is_group_item(
3862 &self,
3863 _ov: &objc2_app_kit::NSOutlineView,
3864 item: &objc2::runtime::AnyObject,
3865 ) -> bool {
3866 let row = Self::outline_row(item);
3867 row >= 0 && self.item_of_row(row).is_none()
3868 }
3869
3870 #[unsafe(method(outlineView:shouldSelectItem:))]
3871 fn should_select(
3872 &self,
3873 _ov: &objc2_app_kit::NSOutlineView,
3874 item: &objc2::runtime::AnyObject,
3875 ) -> bool {
3876 self.item_of_row(Self::outline_row(item)).is_some()
3877 }
3878
3879 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3880 fn view_for(
3881 &self,
3882 ov: &objc2_app_kit::NSOutlineView,
3883 _col: Option<&objc2_app_kit::NSTableColumn>,
3884 item: &objc2::runtime::AnyObject,
3885 ) -> Option<Retained<NSView>> {
3886 let mtm = self.mtm();
3887 let row = Self::outline_row(item);
3888 let text = self
3889 .ivars()
3890 .row_objects
3891 .borrow()
3892 .get(usize::try_from(row).unwrap_or(usize::MAX))
3893 .cloned();
3894 text.map(|text| {
3896 let text: &NSString = &text;
3897 let Some(index) = self.item_of_row(row) else {
3898 let cell = DayNavCell::new(mtm);
3901 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3902 unsafe {
3903 label.cell().inspect(|c| {
3904 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
3905 });
3906 cell.addSubview(&label);
3907 cell.setTextField(Some(&label));
3908 }
3909 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3910 };
3911 let icon = self
3912 .ivars()
3913 .icons
3914 .borrow()
3915 .get(index)
3916 .and_then(std::clone::Clone::clone);
3917 let badge = self
3918 .ivars()
3919 .badges
3920 .borrow()
3921 .get(index)
3922 .and_then(std::clone::Clone::clone);
3923 let badge_icon = self
3924 .ivars()
3925 .badge_icons
3926 .borrow()
3927 .get(index)
3928 .and_then(std::clone::Clone::clone);
3929 let badge_tint = self
3930 .ivars()
3931 .badge_tints
3932 .borrow()
3933 .get(index)
3934 .copied()
3935 .flatten();
3936 let cell = DayNavCell::new(mtm);
3940 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3941 unsafe {
3942 label.cell().inspect(|c| {
3945 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
3946 });
3947 cell.addSubview(&label);
3948 cell.setTextField(Some(&label));
3949 let accessory = objc2_app_kit::NSStackView::new(mtm);
3956 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3957 accessory.setOrientation(
3958 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3959 );
3960 accessory.setSpacing(4.0);
3961 let mut has_accessory = false;
3962 let trailing: Retained<NSView> = match &badge {
3963 Some(text) => {
3964 let b = NSTextField::labelWithString(text, mtm);
3965 b.setTranslatesAutoresizingMaskIntoConstraints(false);
3966 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3967 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3968 b.setFont(Some(
3969 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3970 objc2_app_kit::NSFont::smallSystemFontSize(),
3971 objc2_app_kit::NSFontWeightRegular,
3972 ),
3973 ));
3974 b.setContentCompressionResistancePriority_forOrientation(
3975 objc2_app_kit::NSLayoutPriorityRequired,
3976 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3977 );
3978 *cell.ivars().count.borrow_mut() = Some(b.clone());
3979 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3980 objc2::rc::Retained::into_super(b),
3981 ));
3982 has_accessory = true;
3983 let v: Retained<NSView> =
3984 objc2::rc::Retained::into_super(accessory.clone());
3985 v
3986 }
3987 None => objc2::rc::Retained::into_super(accessory.clone()),
3988 };
3989 if let Some(img) = &badge_icon {
3994 let iv = objc2_app_kit::NSImageView::new(mtm);
3995 iv.setImage(Some(img));
3996 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3997 if let Some(c) = badge_tint {
3998 iv.setContentTintColor(Some(&nscolor(c)));
3999 }
4000 iv.setContentCompressionResistancePriority_forOrientation(
4001 objc2_app_kit::NSLayoutPriorityRequired,
4002 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
4003 );
4004 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
4005 has_accessory = true;
4006 }
4007 cell.addSubview(&trailing);
4008 if has_accessory {
4009 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
4010 }
4011 objc2_app_kit::NSLayoutConstraint::activateConstraints(
4012 &objc2_foundation::NSArray::from_retained_slice(&[
4013 trailing
4014 .trailingAnchor()
4015 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
4016 trailing
4017 .centerYAnchor()
4018 .constraintEqualToAnchor(&cell.centerYAnchor()),
4019 ]),
4020 );
4021 }
4022 if let Some(img) = icon {
4023 let fill = self.ivars().icon_fills.borrow().get(index).copied();
4024 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
4025 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
4026 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
4027 unsafe {
4028 iv.setImage(Some(&img));
4029 if let Some(t) = tint {
4032 iv.setContentTintColor(Some(&nscolor(t)));
4033 }
4034 iv.setImageScaling(
4035 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
4036 );
4037 cell.addSubview(&iv);
4038 cell.setImageView(Some(&iv));
4039 let progress = self
4040 .ivars()
4041 .icon_progress
4042 .borrow()
4043 .iter()
4044 .find(|(row, _)| *row == index)
4045 .map(|(_, f)| *f);
4046 nav_progress::update(&iv, progress);
4047 }
4048 }
4049 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
4050 })
4051 }
4052
4053 #[unsafe(method_id(outlineView:rowViewForItem:))]
4054 fn row_view_for(
4055 &self,
4056 _ov: &objc2_app_kit::NSOutlineView,
4057 _item: &objc2::runtime::AnyObject,
4058 ) -> Retained<objc2_app_kit::NSTableRowView> {
4059 let row: Retained<DayNavRowView> =
4060 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
4061 objc2::rc::Retained::into_super(row)
4062 }
4063
4064 #[unsafe(method(outlineViewSelectionDidChange:))]
4065 fn selection_did_change(&self, notification: &NSNotification) {
4066 ffi_guard::contain((), || {
4067 if self.ivars().suppress.get() {
4068 return;
4069 }
4070 let Some(obj) = (unsafe { notification.object() }) else {
4071 return;
4072 };
4073 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
4074 return;
4075 };
4076 let row = unsafe { ov.selectedRow() };
4077 if let Some(item) = self.item_of_row(row) {
4078 emit(self.ivars().node, Event::SelectionChanged(item as i64));
4079 }
4080 });
4081 }
4082 }
4083);
4084
4085thread_local! {
4086 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
4089}
4090
4091fn nav_icon_fills(
4093 names: &[Option<String>],
4094 images: &[Option<Retained<objc2_app_kit::NSImage>>],
4095) -> Vec<f64> {
4096 names
4097 .iter()
4098 .zip(images)
4099 .map(|(name, image)| match (name, image) {
4100 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
4101 *m.borrow_mut()
4102 .entry(name.clone())
4103 .or_insert_with(|| nav_icon_fill(image))
4104 }),
4105 _ => 1.0,
4106 })
4107 .collect()
4108}
4109
4110fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
4115 const PX: f64 = 64.0;
4116 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
4117 return 1.0;
4118 };
4119 let (w, h) = (
4120 rep.pixelsWide().max(0) as usize,
4121 rep.pixelsHigh().max(0) as usize,
4122 );
4123 let stride = rep.bytesPerRow().max(0) as usize;
4124 let data = unsafe { rep.bitmapData() };
4125 if data.is_null() || stride < w * 4 {
4126 return 1.0;
4127 }
4128 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
4131 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
4132 for y in 0..h {
4133 for x in 0..w {
4134 if bytes[y * stride + x * 4 + 3] > 24 {
4135 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
4136 }
4137 }
4138 }
4139 if x1 <= x0 || y1 <= y0 {
4140 return 1.0;
4141 }
4142 let size = image.size();
4145 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
4146 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
4147 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
4148}
4149
4150fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
4151 icons
4153 .iter()
4154 .map(|ic| {
4155 use objc2::AllocAnyThread as _;
4156 let name = ic.as_deref()?;
4157 let path = day_spec::resource::resolve_vector_svg(name)
4159 .or_else(|| day_spec::resource::resolve_image_file(name))?;
4160 let img = unsafe {
4161 objc2_app_kit::NSImage::initWithContentsOfFile(
4162 objc2_app_kit::NSImage::alloc(),
4163 &NSString::from_str(&path.to_string_lossy()),
4164 )
4165 }?;
4166 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
4168 Some(img)
4169 })
4170 .collect()
4171}
4172
4173impl DayNavMenuData {
4174 #[allow(clippy::too_many_arguments)]
4175 fn new(
4176 mtm: MainThreadMarker,
4177 node: NodeId,
4178 items: &[String],
4179 icons: &[Option<String>],
4180 badges: &[Option<String>],
4181 badge_icons: &[Option<String>],
4182 badge_tints: &[Option<day_spec::Color>],
4183 sections: &[Option<String>],
4184 tints: &[Option<day_spec::Color>],
4185 menus: &[Vec<day_spec::MenuItem>],
4186 ) -> Retained<Self> {
4187 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
4188 node,
4189 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
4190 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
4191 icons: RefCell::new(resolve_nav_icons(icons)),
4192 tints: RefCell::new(tints.to_vec()),
4193 menus: RefCell::new(menus.to_vec()),
4194 movable: RefCell::new(Vec::new()),
4195 regroup: std::cell::Cell::new(false),
4196 sorted: RefCell::new(Vec::new()),
4197 badges: RefCell::new(ns_badges(badges)),
4198 icon_progress: RefCell::new(Vec::new()),
4199 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
4200 badge_tints: RefCell::new(badge_tints.to_vec()),
4201 rows: RefCell::new(Vec::new()),
4202 row_objects: RefCell::new(Vec::new()),
4203 row_ids: RefCell::new(Vec::new()),
4204 suppress: std::cell::Cell::new(false),
4205 });
4206 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
4207 this.rebuild_rows(items, sections);
4208 this
4209 }
4210
4211 #[allow(clippy::too_many_arguments)]
4215 fn set_items(
4216 &self,
4217 items: &[String],
4218 icons: &[Option<String>],
4219 badges: &[Option<String>],
4220 badge_icons: &[Option<String>],
4221 badge_tints: &[Option<day_spec::Color>],
4222 sections: &[Option<String>],
4223 tints: &[Option<day_spec::Color>],
4224 menus: &[Vec<day_spec::MenuItem>],
4225 ) {
4226 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
4227 let resolved = resolve_nav_icons(icons);
4228 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
4229 *self.ivars().icons.borrow_mut() = resolved;
4230 *self.ivars().tints.borrow_mut() = tints.to_vec();
4231 *self.ivars().menus.borrow_mut() = menus.to_vec();
4232 *self.ivars().badges.borrow_mut() = ns_badges(badges);
4233 self.ivars().icon_progress.borrow_mut().clear();
4234 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
4235 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
4236 self.rebuild_rows(items, sections);
4237 }
4238
4239 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
4243 let mut rows = Vec::with_capacity(items.len());
4244 let mut objects = Vec::with_capacity(items.len());
4245 for (i, label) in items.iter().enumerate() {
4246 if let Some(Some(header)) = sections.get(i) {
4247 rows.push(None);
4248 objects.push(NSString::from_str(header));
4249 }
4250 rows.push(Some(i));
4251 objects.push(NSString::from_str(label));
4252 }
4253 let ids = (0..objects.len())
4254 .map(|i| NSNumber::new_isize(i as isize))
4255 .collect();
4256 *self.ivars().rows.borrow_mut() = rows;
4257 *self.ivars().row_objects.borrow_mut() = objects;
4258 *self.ivars().row_ids.borrow_mut() = ids;
4259 }
4260
4261 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
4264 item.downcast_ref::<NSNumber>()
4265 .map_or(-1, objc2_foundation::NSNumber::integerValue)
4266 }
4267
4268 fn item_of_row(&self, row: isize) -> Option<usize> {
4270 if row < 0 {
4271 return None;
4272 }
4273 self.ivars()
4274 .rows
4275 .borrow()
4276 .get(row as usize)
4277 .copied()
4278 .flatten()
4279 }
4280
4281 fn row_of_item(&self, item: usize) -> Option<usize> {
4283 self.ivars()
4284 .rows
4285 .borrow()
4286 .iter()
4287 .position(|r| *r == Some(item))
4288 }
4289
4290 fn is_movable(&self, item: usize) -> bool {
4291 self.ivars()
4292 .movable
4293 .borrow()
4294 .get(item)
4295 .copied()
4296 .unwrap_or(false)
4297 }
4298
4299 fn nav_drop(
4304 &self,
4305 ov: &objc2_app_kit::NSOutlineView,
4306 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4307 item: Option<&objc2::runtime::AnyObject>,
4308 child_index: isize,
4309 ) -> Option<NavDrop> {
4310 let src = unsafe { info.draggingSource() }?;
4311 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
4312 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
4313 {
4314 return None;
4315 }
4316 let pb = unsafe { info.draggingPasteboard() };
4317 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
4318 .to_string()
4319 .parse::<usize>()
4320 .ok()?;
4321 let rows = self.ivars().rows.borrow();
4322 let proposed = match item {
4325 Some(item) => Self::outline_row(item),
4326 None => child_index,
4327 };
4328 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
4329 if self.ivars().regroup.get() {
4330 regroup_gap(
4331 &rows,
4332 &self.ivars().movable.borrow(),
4333 &self.ivars().sorted.borrow(),
4334 from_row,
4335 proposed,
4336 item.is_some(),
4337 )
4338 } else {
4339 reorder_gap(
4340 &rows,
4341 &self.ivars().movable.borrow(),
4342 from_row,
4343 proposed,
4344 item.is_some(),
4345 )
4346 }
4347 }
4348}
4349
4350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4352struct NavDrop {
4353 gap: usize,
4355 retarget: bool,
4357 moves: Option<NavMove>,
4359}
4360
4361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4363enum NavMove {
4364 Reorder { from: usize, to: usize },
4366 Regroup {
4369 from: usize,
4370 section: usize,
4371 before: Option<usize>,
4372 },
4373}
4374
4375fn reorder_gap(
4380 rows: &[Option<usize>],
4381 movable: &[bool],
4382 from_row: usize,
4383 proposed: usize,
4384 onto: bool,
4385) -> Option<NavDrop> {
4386 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
4387 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
4388 let in_run = |r: usize| rows[r].is_some_and(is_movable);
4389 let first = (0..from_row)
4390 .rev()
4391 .take_while(|r| in_run(*r))
4392 .last()
4393 .unwrap_or(from_row);
4394 let last = (from_row + 1..rows.len())
4395 .take_while(|r| in_run(*r))
4396 .last()
4397 .unwrap_or(from_row);
4398 let gap = proposed.clamp(first, last + 1);
4399 let target_row = if gap > from_row { gap - 1 } else { gap };
4401 let moves = (target_row != from_row)
4402 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
4403 .flatten();
4404 Some(NavDrop {
4405 gap,
4406 retarget: gap != proposed || onto,
4407 moves,
4408 })
4409}
4410
4411fn regroup_gap(
4419 rows: &[Option<usize>],
4420 movable: &[bool],
4421 sorted: &[bool],
4422 from_row: usize,
4423 proposed: usize,
4424 onto: bool,
4425) -> Option<NavDrop> {
4426 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
4427 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
4428 let gap = match rows.get(proposed) {
4429 Some(None) if onto => proposed + 1,
4430 _ => proposed.min(rows.len()),
4431 };
4432 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
4434 Some(header) => Some(header + 1),
4435 None => rows.first().copied().flatten().map(|_| 0),
4436 };
4437 let first = section_start(gap)?;
4438 let end = (first..rows.len())
4439 .find(|r| rows[*r].is_none())
4440 .unwrap_or(rows.len());
4441 let section = rows.get(first).copied().flatten()?;
4442 if !rows[first..end]
4443 .iter()
4444 .all(|r| r.is_some_and(|i| flag(movable, i)))
4445 {
4446 return None;
4447 }
4448 let own = section_start(from_row) == Some(first);
4449 if own && flag(sorted, from) {
4450 return None;
4451 }
4452 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
4453 from,
4454 section,
4455 before: rows.get(gap).copied().flatten(),
4456 });
4457 Some(NavDrop {
4458 gap,
4459 retarget: gap != proposed || onto,
4460 moves,
4461 })
4462}
4463
4464#[cfg(test)]
4465mod nav_gap_tests {
4466 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
4467
4468 const ROWS: [Option<usize>; 10] = [
4470 Some(0),
4471 None,
4472 Some(1),
4473 Some(2),
4474 Some(3),
4475 None,
4476 Some(4),
4477 Some(5),
4478 None,
4479 Some(6),
4480 ];
4481 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
4483 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
4484 const UNSORTED: [bool; 7] = [false; 7];
4485
4486 fn regroup(from: usize, section: usize, before: Option<usize>) -> NavMove {
4487 NavMove::Regroup {
4488 from,
4489 section,
4490 before,
4491 }
4492 }
4493
4494 #[test]
4495 fn regroup_gaps_name_the_section_above_and_the_row_below() {
4496 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4497 assert_eq!(
4499 at(2, 6),
4500 Some(NavDrop {
4501 gap: 6,
4502 retarget: false,
4503 moves: Some(regroup(1, 4, Some(4))),
4504 })
4505 );
4506 assert_eq!(at(6, 5).and_then(|d| d.moves), Some(regroup(4, 1, None)));
4508 assert_eq!(at(2, 7).and_then(|d| d.moves), Some(regroup(1, 4, Some(5))));
4510 assert_eq!(at(2, 8).and_then(|d| d.moves), Some(regroup(1, 4, None)));
4511 }
4512
4513 #[test]
4514 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4515 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4516 for gap in [0, 1, 9, 10] {
4518 assert_eq!(at(2, gap), None, "gap {gap}");
4519 }
4520 for gap in [2, 3, 4, 5] {
4522 assert_eq!(at(2, gap), None, "gap {gap}");
4523 }
4524 assert_eq!(at(0, 6), None);
4526 assert_eq!(at(1, 6), None);
4527 assert_eq!(at(9, 6), None);
4528 }
4529
4530 #[test]
4531 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4532 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4533 assert_eq!(at(2, 4).and_then(|d| d.moves), Some(regroup(1, 1, Some(3))));
4535 assert_eq!(at(2, 5).and_then(|d| d.moves), Some(regroup(1, 1, None)));
4537 for gap in [2, 3] {
4539 let drop = at(2, gap).expect("offered");
4540 assert_eq!(drop.moves, None, "gap {gap}");
4541 }
4542 }
4543
4544 #[test]
4545 fn regroup_drops_onto_a_row_move_to_a_gap() {
4546 assert_eq!(
4548 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4549 Some(NavDrop {
4550 gap: 6,
4551 retarget: true,
4552 moves: Some(regroup(1, 4, Some(4))),
4553 })
4554 );
4555 assert_eq!(
4556 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4557 Some(NavDrop {
4558 gap: 7,
4559 retarget: true,
4560 moves: Some(regroup(1, 4, Some(5))),
4561 })
4562 );
4563 }
4564
4565 #[test]
4566 fn regroup_offers_nothing_above_a_leading_header() {
4567 let rows = [None, Some(0), None, Some(1)];
4569 let movable = [true, true];
4570 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4571 assert_eq!(at(0), None);
4572 assert_eq!(at(1).map(|d| d.moves), Some(None));
4573 assert_eq!(at(2).map(|d| d.moves), Some(None));
4574 assert_eq!(at(3).and_then(|d| d.moves), Some(regroup(0, 1, Some(1))));
4575 assert_eq!(at(4).and_then(|d| d.moves), Some(regroup(0, 1, None)));
4576 }
4577
4578 #[test]
4579 fn reorder_gaps_clamp_to_the_run() {
4580 assert_eq!(
4582 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4583 Some(NavDrop {
4584 gap: 5,
4585 retarget: true,
4586 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4587 })
4588 );
4589 assert_eq!(
4591 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4592 Some(None)
4593 );
4594 assert_eq!(
4596 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4597 Some(NavMove::Reorder { from: 2, to: 1 })
4598 );
4599 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4600 }
4601}
4602
4603const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4605
4606fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4608 badges
4609 .iter()
4610 .map(|b| b.as_deref().map(NSString::from_str))
4611 .collect()
4612}
4613
4614fn post_realize_visible_rows(key: usize) {
4620 <AppKit as Platform>::post(Box::new(move || {
4621 if let Some((table, data)) = list_entry(key) {
4622 unsafe { table.layoutSubtreeIfNeeded() };
4623 let range = unsafe { table.rowsInRect(table.visibleRect()) };
4624 if let Some(source) = data.ivars().source.borrow().clone()
4625 && let Some(report) = &source.first_visible
4626 {
4627 report(range.location.min((source.len)().saturating_sub(1)));
4628 }
4629 for row in range.location..range.location + range.length {
4630 let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4631 if let Some(cell) = cell
4635 && cell.subviews().is_empty()
4636 {
4637 let source = data.ivars().source.borrow().clone();
4638 if let Some(source) = source {
4639 (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4640 }
4641 }
4642 }
4643 }
4644 day_core::pump_events();
4647 }));
4648}
4649
4650fn post_settle_list_drop(key: usize) {
4655 <AppKit as Platform>::post(Box::new(move || {
4656 day_core::pump_events();
4659 let Some((table, data)) = list_entry(key) else {
4660 return;
4661 };
4662 let Some(scroll) = table.enclosingScrollView() else {
4663 return;
4664 };
4665 let clip = scroll.contentView();
4666 let origin = clip.bounds().origin;
4667 let selected = table.selectedRowIndexes();
4668 let suppressed = data.ivars().suppress.replace(true);
4669 table.reloadData();
4670 table.layoutSubtreeIfNeeded();
4672 let restored = objc2_foundation::NSMutableIndexSet::new();
4673 for row in 0..table.numberOfRows().max(0) as usize {
4674 if selected.containsIndex(row) {
4675 restored.addIndex(row);
4676 }
4677 }
4678 table.selectRowIndexes_byExtendingSelection(&restored, false);
4679 let mut bounds = clip.bounds();
4680 bounds.origin = origin;
4681 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4682 scroll.reflectScrolledClipView(&clip);
4683 data.ivars().suppress.set(suppressed);
4684 post_realize_visible_rows(key);
4685 }));
4686}
4687
4688define_class!(
4697 #[unsafe(super(NSTableView))]
4698 #[thread_kind = MainThreadOnly]
4699 #[name = "DayListView"]
4700 struct DayListView;
4701 unsafe impl NSObjectProtocol for DayListView {}
4702 impl DayListView {
4703 #[unsafe(method_id(menuForEvent:))]
4706 fn menu_for_event(
4707 &self,
4708 event: &objc2_app_kit::NSEvent,
4709 ) -> Option<Retained<NSMenu>> {
4710 ffi_guard::contain(None, || {
4711 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4712 let row = unsafe { self.rowAtPoint(point) };
4713 let provider = if row >= 0 {
4714 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4715 .and_then(|cell| list_row_menu_provider(&cell))
4716 } else {
4717 None
4718 };
4719 match provider {
4720 Some((view, provider)) => {
4721 let point = view.convertPoint_fromView(
4722 unsafe { event.locationInWindow() }, None,
4723 );
4724 let items = provider(day_spec::Point::new(point.x, point.y));
4725 if items.is_empty() {
4726 None
4727 } else {
4728 Some(build_ns_menu(self.mtm(), "", &items))
4729 }
4730 }
4731 None => unsafe { msg_send![super(self), menuForEvent: event] },
4732 }
4733 })
4734 }
4735
4736 #[unsafe(method(becomeFirstResponder))]
4737 fn become_first_responder(&self) -> bool {
4738 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4739 if accepted {
4740 self.report_focus(true);
4741 }
4742 accepted
4743 }
4744
4745 #[unsafe(method(resignFirstResponder))]
4746 fn resign_first_responder(&self) -> bool {
4747 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4748 if accepted {
4749 self.report_focus(false);
4750 }
4751 accepted
4752 }
4753
4754 #[unsafe(method(keyDown:))]
4755 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4756 ffi_guard::contain((), || {
4757 let key = unsafe { event.keyCode() };
4758 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4759 let row = unsafe { self.selectedRow() };
4760 if row >= 0 && let Some(target) = unsafe { self.target() } {
4761 let _: () = unsafe { msg_send![&*target, activateRow: self] };
4762 return;
4763 }
4764 }
4765 let _: () = unsafe { msg_send![super(self), keyDown: event] };
4766 });
4767 }
4768 }
4769);
4770
4771fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4774 if let Some(provider) =
4775 CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<NSView>(view) as usize))
4776 {
4777 return Some((view.retain(), provider));
4778 }
4779 view.subviews()
4780 .iter()
4781 .find_map(|view| list_row_menu_provider(&view))
4782}
4783
4784#[expect(
4788 clippy::option_option,
4789 reason = "`None` defers to AppKit's own menu while `Some(None)` is an owner's deliberate no-menu answer"
4790)]
4791fn inherited_context_menu(
4792 view: &NSView,
4793 event: &objc2_app_kit::NSEvent,
4794) -> Option<Option<Retained<NSMenu>>> {
4795 let mut current = Some(view.retain());
4796 while let Some(view) = current {
4797 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4798 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4799 let items = provider(day_spec::Point::new(point.x, point.y));
4800 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4801 }
4802 current = unsafe { view.superview() };
4803 }
4804 None
4805}
4806
4807impl DayListView {
4808 fn report_focus(&self, focused: bool) {
4809 ffi_guard::contain((), || {
4810 if let Some(target) = unsafe { self.target() }
4811 && let Some(data) = target.downcast_ref::<DayListData>()
4812 {
4813 emit(data.ivars().node, Event::FocusChanged(focused));
4814 }
4815 });
4816 }
4817}
4818
4819struct ListIvars {
4820 node: NodeId,
4821 source: RefCell<Option<ListSource>>,
4823 selectable: std::cell::Cell<bool>,
4824 multi: std::cell::Cell<bool>,
4826 suppress: std::cell::Cell<bool>,
4828 tokens: RefCell<Vec<u64>>,
4831 automatic: bool,
4835 sections: bool,
4839 header_estimate: std::cell::Cell<f64>,
4841 heights: RefCell<std::collections::HashMap<u64, f64>>,
4844 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4847 estimate: std::cell::Cell<f64>,
4850 heights_pending: std::cell::Cell<bool>,
4852}
4853
4854define_class!(
4855 #[unsafe(super(NSObject))]
4856 #[thread_kind = MainThreadOnly]
4857 #[name = "DayListData"]
4858 #[ivars = ListIvars]
4859 struct DayListData;
4860
4861 unsafe impl NSObjectProtocol for DayListData {}
4862 unsafe impl NSControlTextEditingDelegate for DayListData {}
4863
4864 impl DayListData {
4865 #[unsafe(method(respondsToSelector:))]
4869 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4870 if selector == objc2::sel!(tableView:heightOfRow:)
4871 && !self.ivars().automatic
4872 && !self.ivars().sections
4873 {
4874 false
4875 } else {
4876 unsafe { msg_send![super(self), respondsToSelector: selector] }
4877 }
4878 }
4879
4880 #[unsafe(method(listViewportChanged:))]
4881 fn list_viewport_changed(&self, notification: &NSNotification) {
4882 ffi_guard::contain((), || {
4883 let source = self.ivars().source.borrow().clone();
4884 if let Some(source) = source && let Some(report) = &source.first_visible
4885 && let Some(object) = notification.object()
4886 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4887 && let Some(document) = clip.documentView()
4888 && let Some(table) = document.downcast_ref::<NSTableView>() {
4889 let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4890 report(visible.location.min((source.len)().saturating_sub(1)));
4891 }
4892 });
4893 }
4894
4895 #[unsafe(method(activateRow:))]
4896 fn activate_row(&self, table: &NSTableView) {
4897 ffi_guard::contain((), || {
4898 let row = unsafe { table.selectedRow() };
4899 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4900 });
4901 }
4902 #[unsafe(method(doubleClickRow:))]
4903 fn double_click_row(&self, table: &NSTableView) {
4904 ffi_guard::contain((), || {
4905 let row = unsafe { table.clickedRow() };
4906 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4907 });
4908 }
4909 }
4910
4911 unsafe impl NSTableViewDataSource for DayListData {
4912 #[unsafe(method(numberOfRowsInTableView:))]
4913 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4914 ffi_guard::contain(0, || {
4918 self.ivars()
4919 .source
4920 .borrow()
4921 .as_ref()
4922 .map_or(0, |s| (s.len)() as isize)
4923 })
4924 }
4925
4926 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4932 fn pasteboard_writer_for_row(
4933 &self,
4934 _tv: &NSTableView,
4935 row: isize,
4936 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4937 let make = || {
4940 let reorderable = self
4942 .ivars()
4943 .source
4944 .borrow()
4945 .as_ref()
4946 .is_some_and(|s| s.reorder.is_some());
4947 if !reorderable || row < 0 || self.is_header(row) {
4949 return None;
4950 }
4951 let item = objc2_app_kit::NSPasteboardItem::new();
4952 unsafe {
4953 item.setString_forType(
4954 &NSString::from_str(&row.to_string()),
4955 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4956 );
4957 }
4958 Some(ProtocolObject::from_retained(item))
4959 };
4960 ffi_guard::contain(None, make)
4961 }
4962
4963 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4964 fn validate_drop(
4965 &self,
4966 tv: &NSTableView,
4967 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4968 row: isize,
4969 _op: objc2_app_kit::NSTableViewDropOperation,
4970 ) -> objc2_app_kit::NSDragOperation {
4971 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4973 let Some((from, len)) = self.drag_context(tv, info) else {
4974 return objc2_app_kit::NSDragOperation::None;
4975 };
4976 let ins = row.clamp(0, len as isize) as usize;
4979 let to = insertion_to_target(from, ins, len);
4980 let accepted = self.can_move(from, to);
4981 if accepted < 0 {
4982 return objc2_app_kit::NSDragOperation::None;
4983 }
4984 let accepted = (accepted as usize).min(len.saturating_sub(1));
4985 if accepted != to {
4986 unsafe {
4988 tv.setDropRow_dropOperation(
4989 target_to_insertion(from, accepted) as isize,
4990 objc2_app_kit::NSTableViewDropOperation::Above,
4991 );
4992 }
4993 }
4994 objc2_app_kit::NSDragOperation::Move
4995 })
4996 }
4997
4998 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4999 fn accept_drop(
5000 &self,
5001 tv: &NSTableView,
5002 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5003 row: isize,
5004 _op: objc2_app_kit::NSTableViewDropOperation,
5005 ) -> bool {
5006 let drop = || {
5008 let Some((from, len)) = self.drag_context(tv, info) else {
5009 return false;
5010 };
5011 let ins = row.clamp(0, len as isize) as usize;
5012 let to = insertion_to_target(from, ins, len);
5013 let accepted = self.can_move(from, to);
5014 if accepted < 0 {
5015 return false;
5016 }
5017 let accepted = (accepted as usize).min(len.saturating_sub(1));
5018 if accepted == from {
5019 return true; }
5021 let mv = self
5025 .ivars()
5026 .source
5027 .borrow()
5028 .as_ref()
5029 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
5030 let Some(mv) = mv else { return false };
5031 mv(from, accepted);
5032 {
5035 let mut toks = self.ivars().tokens.borrow_mut();
5036 if from < toks.len() && accepted < toks.len() {
5037 let t = toks.remove(from);
5038 toks.insert(accepted, t);
5039 }
5040 }
5041 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
5042 if let Some(scroll) = tv.enclosingScrollView() {
5043 post_settle_list_drop(ptr_of(&scroll));
5044 }
5045 true
5046 };
5047 ffi_guard::contain(false, drop)
5049 }
5050 }
5051
5052 unsafe impl NSTableViewDelegate for DayListData {
5053 #[unsafe(method(tableView:heightOfRow:))]
5058 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
5059 ffi_guard::contain(44.0, || {
5060 let ivars = self.ivars();
5061 let header = self.is_header(row);
5062 if !header && !ivars.automatic {
5064 return unsafe { tv.rowHeight() };
5065 }
5066 let token = ivars
5067 .source
5068 .borrow()
5069 .as_ref()
5070 .filter(|s| row >= 0 && (row as usize) < (s.len)())
5071 .map(|s| (s.token_at)(row as usize));
5072 token
5073 .and_then(|t| ivars.heights.borrow().get(&t).copied())
5074 .unwrap_or_else(|| {
5075 if header {
5076 ivars.header_estimate.get()
5077 } else {
5078 ivars.estimate.get()
5079 }
5080 })
5081 })
5082 }
5083
5084 #[unsafe(method(tableView:isGroupRow:))]
5088 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
5089 ffi_guard::contain(false, || self.is_header(row))
5090 }
5091
5092 #[unsafe(method(tableView:shouldSelectRow:))]
5094 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
5095 ffi_guard::contain(true, || !self.is_header(row))
5096 }
5097
5098 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
5099 fn view_for_row(
5100 &self,
5101 tv: &NSTableView,
5102 _col: Option<&NSTableColumn>,
5103 row: isize,
5104 ) -> Option<Retained<NSView>> {
5105 ffi_guard::contain(None, || {
5107 let mtm = self.mtm();
5108 let header = self.is_header(row);
5110 let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
5111 let cell: Retained<NSView> =
5113 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5114 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
5115 unsafe { v.setIdentifier(Some(&ident)) };
5116 v
5117 });
5118 let source = self.ivars().source.borrow().clone();
5122 if let Some(source) = source {
5123 let raw = Retained::as_ptr(&cell) as RawHandle;
5124 (source.bind_row)(row as usize, raw);
5125 if self.ivars().automatic || header {
5126 self.note_row_height(tv, &source, row, raw, header);
5127 }
5128 }
5129 Some(cell)
5130 })
5131 }
5132
5133 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
5134 fn did_remove_row_view(
5135 &self,
5136 _tv: &NSTableView,
5137 row_view: &objc2_app_kit::NSTableRowView,
5138 _row: isize,
5139 ) {
5140 ffi_guard::contain((), || {
5146 let Some(cell) = row_view.subviews().iter().find(|sub| {
5147 sub.identifier()
5148 .is_some_and(|i| {
5149 let i = i.to_string();
5150 i == DAY_ROW_CELL || i == DAY_HEADER_CELL
5151 })
5152 }) else {
5153 return;
5154 };
5155 let cell = Retained::into_raw(cell) as usize;
5158 let Some(this) = (unsafe {
5159 Retained::retain(std::ptr::from_ref::<DayListData>(self).cast_mut())
5160 }) else {
5161 return;
5162 };
5163 let this = Retained::into_raw(this) as usize;
5164 <AppKit as Platform>::post(Box::new(move || {
5165 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5167 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
5168 let (Some(this), Some(cell)) = (this, cell) else {
5169 return;
5170 };
5171 if cell.window().is_some() {
5172 return; }
5174 let recycle = this
5175 .ivars()
5176 .source
5177 .borrow()
5178 .as_ref()
5179 .map(|s| s.recycle.clone());
5180 if let Some(recycle) = recycle {
5181 recycle(Retained::as_ptr(&cell) as RawHandle);
5182 }
5183 }));
5184 });
5185 }
5186
5187 #[unsafe(method(tableViewSelectionDidChange:))]
5188 fn selection_did_change(&self, notification: &NSNotification) {
5189 ffi_guard::contain((), || {
5190 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5191 return;
5192 }
5193 let Some(obj) = (unsafe { notification.object() }) else {
5194 return;
5195 };
5196 let Ok(tv) = obj.downcast::<NSTableView>() else {
5197 return;
5198 };
5199 if self.ivars().multi.get() {
5200 let idx = unsafe { tv.selectedRowIndexes() };
5202 let mut rows = Vec::with_capacity(idx.count());
5203 let mut i = idx.firstIndex();
5204 while i != objc2_foundation::NSNotFound as usize {
5205 rows.push(i as i64);
5206 i = unsafe { idx.indexGreaterThanIndex(i) };
5207 }
5208 emit(self.ivars().node, Event::SelectionSet(rows));
5209 } else {
5210 let row = unsafe { tv.selectedRow() };
5211 if row >= 0 {
5212 emit(self.ivars().node, Event::SelectionChanged(row as i64));
5213 } else {
5214 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
5222 }
5223 }
5224 });
5225 }
5226
5227 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
5233 fn row_actions_for_row(
5234 &self,
5235 tv: &NSTableView,
5236 row: isize,
5237 edge: objc2_app_kit::NSTableRowActionEdge,
5238 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
5239 ffi_guard::contain(NSArray::new(), || {
5241 let sw = self
5242 .ivars()
5243 .source
5244 .borrow()
5245 .as_ref()
5246 .and_then(|s| s.swipe.clone());
5247 let Some(sw) = sw else {
5248 return NSArray::new();
5249 };
5250 if row < 0 {
5251 return NSArray::new();
5252 }
5253 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
5255 day_spec::SwipeEdge::Leading
5256 } else {
5257 day_spec::SwipeEdge::Trailing
5258 };
5259 let offer = (sw.actions_at)(row as usize, day_edge);
5260 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
5261 .iter()
5262 .enumerate()
5263 .map(|(i, a)| {
5264 let style = if a.destructive {
5265 objc2_app_kit::NSTableViewRowActionStyle::Destructive
5266 } else {
5267 objc2_app_kit::NSTableViewRowActionStyle::Regular
5268 };
5269 let perform = sw.perform.clone();
5270 let table = tv.retain();
5273 let handler = block2::RcBlock::new(
5274 move |_action: std::ptr::NonNull<
5275 objc2_app_kit::NSTableViewRowAction,
5276 >,
5277 row: isize| {
5278 ffi_guard::contain((), || {
5279 perform(row as usize, day_edge, i);
5280 unsafe { table.setRowActionsVisible(false) };
5283 });
5284 },
5285 );
5286 let action =
5287 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
5288 style,
5289 &NSString::from_str(&a.label),
5290 &handler,
5291 );
5292 if let Some(t) = a.tint {
5293 unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
5294 }
5295 if let Some(sym) = a.symbol {
5299 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
5300 &NSString::from_str(day_spec::sf_symbol_name(sym)),
5301 None,
5302 );
5303 if let Some(img) = img {
5304 unsafe { action.setImage(Some(&img)) };
5305 }
5306 }
5307 action
5308 })
5309 .collect();
5310 NSArray::from_retained_slice(&actions)
5311 })
5312 }
5313 }
5314);
5315
5316impl DayListData {
5317 fn new(
5318 mtm: MainThreadMarker,
5319 node: NodeId,
5320 selectable: bool,
5321 multi: bool,
5322 automatic: bool,
5323 sections: bool,
5324 ) -> Retained<Self> {
5325 let this = Self::alloc(mtm).set_ivars(ListIvars {
5326 node,
5327 source: RefCell::new(None),
5328 selectable: std::cell::Cell::new(selectable),
5329 multi: std::cell::Cell::new(multi),
5330 suppress: std::cell::Cell::new(false),
5331 tokens: RefCell::new(Vec::new()),
5332 automatic,
5333 sections,
5334 header_estimate: std::cell::Cell::new(28.0),
5335 heights: RefCell::new(std::collections::HashMap::new()),
5336 cell_tokens: RefCell::new(std::collections::HashMap::new()),
5337 estimate: std::cell::Cell::new(44.0),
5338 heights_pending: std::cell::Cell::new(false),
5339 });
5340 unsafe { msg_send![super(this), init] }
5341 }
5342
5343 fn note_row_height(
5347 &self,
5348 table: &NSTableView,
5349 source: &ListSource,
5350 row: isize,
5351 cell: RawHandle,
5352 header: bool,
5353 ) {
5354 let height = (source.cell_height)(cell);
5355 if height <= 0.0 || row < 0 {
5356 return;
5357 }
5358 let token = (source.token_at)(row as usize);
5359 self.ivars()
5360 .cell_tokens
5361 .borrow_mut()
5362 .insert(cell as usize, token);
5363 self.ivars().heights.borrow_mut().insert(token, height);
5364 if header {
5365 self.ivars().header_estimate.set(height);
5366 } else {
5367 self.ivars().estimate.set(height);
5368 }
5369 let drawn = unsafe { table.rectOfRow(row) }.size.height;
5370 if (drawn - height).abs() > 0.5 {
5371 self.post_row_heights(table);
5372 }
5373 }
5374
5375 fn is_header(&self, row: isize) -> bool {
5377 row >= 0
5378 && self
5379 .ivars()
5380 .source
5381 .borrow()
5382 .as_ref()
5383 .and_then(|s| s.is_header.clone())
5384 .is_some_and(|is_header| is_header(row as usize))
5385 }
5386
5387 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
5390 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
5391 if let Some(token) = token {
5392 self.ivars().heights.borrow_mut().insert(token, height);
5393 self.post_row_heights(table);
5394 }
5395 }
5396
5397 fn post_row_heights(&self, table: &NSTableView) {
5401 if self.ivars().heights_pending.replace(true) {
5402 return;
5403 }
5404 let Some(this) = (unsafe { Retained::retain(std::ptr::from_ref::<Self>(self).cast_mut()) })
5407 else {
5408 return;
5409 };
5410 let this = Retained::into_raw(this) as usize;
5411 let table = Retained::into_raw(table.retain()) as usize;
5412 <AppKit as Platform>::post(Box::new(move || {
5413 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5415 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
5416 let (Some(this), Some(table)) = (this, table) else {
5417 return;
5418 };
5419 this.ivars().heights_pending.set(false);
5420 ffi_guard::contain((), || this.apply_row_heights(&table));
5421 }));
5422 }
5423
5424 fn apply_row_heights(&self, table: &NSTableView) {
5425 let Some(source) = self.ivars().source.borrow().clone() else {
5426 return;
5427 };
5428 let count = unsafe { table.numberOfRows() }.max(0) as usize;
5429 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
5430 let first = shown.location.saturating_sub(8);
5432 let last = (shown.location + shown.length + 8)
5433 .min(count)
5434 .min((source.len)());
5435 let changed = objc2_foundation::NSMutableIndexSet::new();
5436 {
5437 let heights = self.ivars().heights.borrow();
5438 for row in first..last {
5439 if let Some(&height) = heights.get(&(source.token_at)(row)) {
5440 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
5441 if (drawn - height).abs() > 0.5 {
5442 unsafe { changed.addIndex(row) };
5443 }
5444 }
5445 }
5446 }
5447 if changed.count() == 0 {
5448 return;
5449 }
5450 NSAnimationContext::beginGrouping();
5452 NSAnimationContext::currentContext().setDuration(0.0);
5453 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
5454 NSAnimationContext::endGrouping();
5455 }
5456
5457 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
5469 let source = self.ivars().source.borrow();
5470 let source = source.as_ref()?;
5471 let n = (source.len)();
5472 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
5473 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
5474 if old.len() != n || n == 0 || old == new {
5475 return None;
5476 }
5477 let (mut so, mut sn) = (old.clone(), new.clone());
5478 so.sort_unstable();
5479 sn.sort_unstable();
5480 if so != sn {
5481 return None;
5482 }
5483 for i in 0..n {
5484 if old[i] != new[i]
5485 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
5486 {
5487 return None;
5488 }
5489 }
5490 let mut work = old;
5491 let mut moves = Vec::new();
5492 for i in 0..n {
5493 if work[i] == new[i] {
5494 continue;
5495 }
5496 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
5497 let t = work.remove(j);
5498 work.insert(i, t);
5499 moves.push((j, i));
5500 }
5501 Some(moves)
5502 }
5503
5504 fn drag_context(
5508 &self,
5509 tv: &NSTableView,
5510 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5511 ) -> Option<(usize, usize)> {
5512 let src = unsafe { info.draggingSource() }?;
5513 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
5514 != std::ptr::from_ref::<NSTableView>(tv).cast::<std::ffi::c_void>()
5515 {
5516 return None;
5517 }
5518 let pb = unsafe { info.draggingPasteboard() };
5519 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5520 .to_string()
5521 .parse::<usize>()
5522 .ok()?;
5523 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5524 (from < len).then_some((from, len))
5525 }
5526
5527 fn can_move(&self, from: usize, to: usize) -> i64 {
5529 self.ivars()
5530 .source
5531 .borrow()
5532 .as_ref()
5533 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5534 .unwrap_or(-1)
5535 }
5536}
5537
5538const DAY_ROW_CELL: &str = "day.cell";
5540const DAY_HEADER_CELL: &str = "day.header";
5541
5542const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5544
5545fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5548 let to = if ins > from { ins - 1 } else { ins };
5549 to.min(len.saturating_sub(1))
5550}
5551
5552fn target_to_insertion(from: usize, to: usize) -> usize {
5554 if to > from { to + 1 } else { to }
5555}
5556
5557type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5559
5560fn list_entry(key: usize) -> Option<ListEntry> {
5567 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5568}
5569
5570struct TreeIvars {
5575 node: NodeId,
5576 source: RefCell<Option<TreeSource>>,
5578 selectable: std::cell::Cell<bool>,
5579 suppress: std::cell::Cell<bool>,
5581 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5585}
5586
5587define_class!(
5588 #[unsafe(super(NSObject))]
5589 #[thread_kind = MainThreadOnly]
5590 #[name = "DayTreeData"]
5591 #[ivars = TreeIvars]
5592 struct DayTreeData;
5593
5594 unsafe impl NSObjectProtocol for DayTreeData {}
5595
5596 unsafe impl NSOutlineViewDataSource for DayTreeData {
5597 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5598 fn number_of_children(
5599 &self,
5600 _ov: &objc2_app_kit::NSOutlineView,
5601 item: Option<&objc2::runtime::AnyObject>,
5602 ) -> isize {
5603 ffi_guard::contain(0, || {
5607 let parent = item.and_then(Self::token_of_item);
5608 if item.is_some() && parent.is_none() {
5609 return 0; }
5611 self.ivars()
5612 .source
5613 .borrow()
5614 .as_ref()
5615 .map_or(0, |s| (s.children_len)(parent) as isize)
5616 })
5617 }
5618
5619 #[unsafe(method_id(outlineView:child:ofItem:))]
5620 fn child_of_item(
5621 &self,
5622 _ov: &objc2_app_kit::NSOutlineView,
5623 index: isize,
5624 item: Option<&objc2::runtime::AnyObject>,
5625 ) -> Retained<objc2::runtime::AnyObject> {
5626 let token = ffi_guard::contain(0, || {
5630 let parent = item.and_then(Self::token_of_item);
5631 self.ivars()
5632 .source
5633 .borrow()
5634 .as_ref()
5635 .map_or(0, |s| (s.child_token)(parent, index.max(0) as usize))
5636 });
5637 let ns = self.intern(token);
5638 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5639 }
5640
5641 #[unsafe(method(outlineView:isItemExpandable:))]
5642 fn is_expandable(
5643 &self,
5644 _ov: &objc2_app_kit::NSOutlineView,
5645 item: &objc2::runtime::AnyObject,
5646 ) -> bool {
5647 ffi_guard::contain(false, || {
5648 let Some(token) = Self::token_of_item(item) else {
5649 return false;
5650 };
5651 self.ivars()
5652 .source
5653 .borrow()
5654 .as_ref()
5655 .is_some_and(|s| (s.expandable)(token))
5656 })
5657 }
5658
5659 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5665 fn pasteboard_writer_for_item(
5666 &self,
5667 _ov: &objc2_app_kit::NSOutlineView,
5668 item: &objc2::runtime::AnyObject,
5669 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5670 let make = || {
5671 let movable = self
5672 .ivars()
5673 .source
5674 .borrow()
5675 .as_ref()
5676 .is_some_and(|s| s.moves.is_some());
5677 let token = Self::token_of_item(item)?;
5678 if !movable {
5679 return None;
5680 }
5681 let pbitem = objc2_app_kit::NSPasteboardItem::new();
5682 unsafe {
5683 pbitem.setString_forType(
5684 &NSString::from_str(&token.to_string()),
5685 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5686 );
5687 }
5688 Some(ProtocolObject::from_retained(pbitem))
5689 };
5690 ffi_guard::contain(None, make)
5691 }
5692
5693 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5694 fn validate_drop(
5695 &self,
5696 ov: &objc2_app_kit::NSOutlineView,
5697 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5698 item: Option<&objc2::runtime::AnyObject>,
5699 child_index: isize,
5700 ) -> objc2_app_kit::NSDragOperation {
5701 ffi_guard::contain(
5702 objc2_app_kit::NSDragOperation::None,
5703 || match Self::drop_proposal(ov, info, item, child_index) {
5704 Some((token, parent, index)) if self.can_move(token, parent, index) => {
5705 objc2_app_kit::NSDragOperation::Move
5706 }
5707 _ => objc2_app_kit::NSDragOperation::None,
5708 },
5709 )
5710 }
5711
5712 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5713 fn accept_drop(
5714 &self,
5715 ov: &objc2_app_kit::NSOutlineView,
5716 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5717 item: Option<&objc2::runtime::AnyObject>,
5718 child_index: isize,
5719 ) -> bool {
5720 let drop = || {
5721 let Some((token, parent, index)) = Self::drop_proposal(ov, info, item, child_index)
5722 else {
5723 return false;
5724 };
5725 if !self.can_move(token, parent, index) {
5726 return false;
5727 }
5728 let mv = self
5731 .ivars()
5732 .source
5733 .borrow()
5734 .as_ref()
5735 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5736 let Some(mv) = mv else { return false };
5737 mv(token, parent, index);
5738 true
5739 };
5740 ffi_guard::contain(false, drop)
5741 }
5742 }
5743
5744 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5745
5746 unsafe impl NSOutlineViewDelegate for DayTreeData {
5747 #[unsafe(method(outlineView:isGroupItem:))]
5748 fn is_group_item(
5749 &self,
5750 _ov: &objc2_app_kit::NSOutlineView,
5751 item: &objc2::runtime::AnyObject,
5752 ) -> bool {
5753 Self::token_of_item(item).is_some_and(|t| {
5754 self.ivars()
5755 .source
5756 .borrow()
5757 .as_ref()
5758 .is_some_and(|s| (s.section_header)(t))
5759 })
5760 }
5761 #[unsafe(method(outlineView:shouldSelectItem:))]
5762 fn should_select_item(
5763 &self,
5764 _ov: &objc2_app_kit::NSOutlineView,
5765 item: &objc2::runtime::AnyObject,
5766 ) -> bool {
5767 Self::token_of_item(item).is_some_and(|t| {
5768 self.ivars()
5769 .source
5770 .borrow()
5771 .as_ref()
5772 .is_some_and(|s| !(s.section_header)(t))
5773 })
5774 }
5775
5776 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5777 fn view_for_item(
5778 &self,
5779 ov: &objc2_app_kit::NSOutlineView,
5780 _col: Option<&NSTableColumn>,
5781 item: &objc2::runtime::AnyObject,
5782 ) -> Option<Retained<NSView>> {
5783 ffi_guard::contain(None, || {
5785 let mtm = self.mtm();
5786 let token = Self::token_of_item(item)?;
5787 let ident = NSString::from_str("day.tree.cell");
5788 let cell: Retained<NSView> =
5792 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5793 let v: Retained<NSView> =
5794 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5795 unsafe { v.setIdentifier(Some(&ident)) };
5796 v
5797 });
5798 if let Some(source) = self.ivars().source.borrow().as_ref() {
5799 let raw = Retained::as_ptr(&cell) as RawHandle;
5800 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5801 unsafe {
5802 cell.setTextField(None);
5803 }
5804 }
5805 (source.bind_row)(token, raw);
5806 if (source.section_header)(token) {
5809 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5810 for child in &unsafe { view.subviews() } {
5811 if let Ok(label) = child.clone().downcast::<NSTextField>() {
5812 return Some(label);
5813 }
5814 if let Some(label) = label_in(&child) {
5815 return Some(label);
5816 }
5817 }
5818 None
5819 }
5820 if let Some(label) = label_in(&cell) {
5821 let cell = cell.downcast_ref::<DayTreeCell>()?;
5822 unsafe {
5823 cell.setTextField(Some(&label));
5824 }
5825 }
5826 }
5827 }
5828 Some(cell)
5829 })
5830 }
5831
5832 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5833 fn type_select_string(
5834 &self,
5835 _ov: &objc2_app_kit::NSOutlineView,
5836 _col: Option<&NSTableColumn>,
5837 item: &objc2::runtime::AnyObject,
5838 ) -> Option<Retained<NSString>> {
5839 ffi_guard::contain(None, || {
5840 let token = Self::token_of_item(item)?;
5841 let text = self
5842 .ivars()
5843 .source
5844 .borrow()
5845 .as_ref()
5846 .map_or_default(|s| (s.type_select_text)(token));
5847 (!text.is_empty()).then(|| NSString::from_str(&text))
5849 })
5850 }
5851
5852 #[unsafe(method_id(outlineView:rowViewForItem:))]
5853 fn row_view_for_item(
5854 &self,
5855 ov: &objc2_app_kit::NSOutlineView,
5856 _item: &objc2::runtime::AnyObject,
5857 ) -> Retained<objc2_app_kit::NSTableRowView> {
5858 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5859 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5861 } else {
5862 let rv: Retained<DayTreeRowView> =
5864 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5865 Retained::into_super(rv)
5866 }
5867 }
5868
5869 #[unsafe(method(outlineViewSelectionDidChange:))]
5870 fn selection_did_change(&self, notification: &NSNotification) {
5871 ffi_guard::contain((), || {
5872 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5873 return;
5874 }
5875 let Some(obj) = (unsafe { notification.object() }) else {
5876 return;
5877 };
5878 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5879 return;
5880 };
5881 let idx = unsafe { ov.selectedRowIndexes() };
5883 let mut tokens = Vec::with_capacity(idx.count());
5884 let mut i = idx.firstIndex();
5885 while i != objc2_foundation::NSNotFound as usize {
5886 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5887 && let Some(tok) = Self::token_of_item(&item)
5888 {
5889 tokens.push(tok);
5890 }
5891 i = unsafe { idx.indexGreaterThanIndex(i) };
5892 }
5893 emit(self.ivars().node, Event::TreeSelection(tokens));
5894 });
5895 }
5896
5897 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5898 fn did_remove_row_view(
5899 &self,
5900 ov: &objc2_app_kit::NSOutlineView,
5901 row_view: &objc2_app_kit::NSTableRowView,
5902 _row: isize,
5903 ) {
5904 ffi_guard::contain((), || {
5910 let mut cell_ptr: Option<usize> = None;
5911 for sub in &row_view.subviews() {
5912 let is_cell = sub
5913 .identifier()
5914 .is_some_and(|i| i.to_string() == "day.tree.cell");
5915 if is_cell {
5916 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5917 }
5918 }
5919 let Some(cell) = cell_ptr else { return };
5920 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5921 return;
5922 };
5923 let key = Retained::as_ptr(&scroll) as usize;
5924 let retained =
5928 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5929 as usize;
5930 <AppKit as Platform>::post(Box::new(move || {
5931 let cell_view: Retained<NSView> =
5934 match unsafe { Retained::from_raw(retained as *mut NSView) } {
5935 Some(v) => v,
5936 None => return,
5937 };
5938 let recycle = tree_entry(key).and_then(|(_, data)| {
5939 data.ivars()
5940 .source
5941 .borrow()
5942 .as_ref()
5943 .map(|s| s.recycle.clone())
5944 });
5945 let Some(recycle) = recycle else { return };
5946 if cell_view.window().is_some() {
5947 return; }
5949 recycle(cell as RawHandle);
5950 }));
5951 });
5952 }
5953
5954 #[unsafe(method(outlineViewItemDidExpand:))]
5955 fn item_did_expand(&self, notification: &NSNotification) {
5956 self.report_disclosure(notification, true);
5957 }
5958
5959 #[unsafe(method(outlineViewItemDidCollapse:))]
5960 fn item_did_collapse(&self, notification: &NSNotification) {
5961 self.report_disclosure(notification, false);
5962 }
5963 }
5964);
5965
5966impl DayTreeData {
5967 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5968 let this = Self::alloc(mtm).set_ivars(TreeIvars {
5969 node,
5970 source: RefCell::new(None),
5971 selectable: std::cell::Cell::new(selectable),
5972 suppress: std::cell::Cell::new(false),
5973 items: RefCell::new(HashMap::new()),
5974 });
5975 unsafe { msg_send![super(this), init] }
5976 }
5977
5978 fn intern(&self, token: u64) -> Retained<NSNumber> {
5980 self.ivars()
5981 .items
5982 .borrow_mut()
5983 .entry(token)
5984 .or_insert_with(|| NSNumber::new_u64(token))
5985 .clone()
5986 }
5987
5988 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5989 item.downcast_ref::<NSNumber>()
5990 .map(objc2_foundation::NSNumber::as_u64)
5991 }
5992
5993 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5996 ffi_guard::contain((), || {
5997 if self.ivars().suppress.get() {
5998 return;
5999 }
6000 let token = unsafe { notification.userInfo() }
6001 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
6002 .and_then(|item| Self::token_of_item(&item));
6003 if let Some(token) = token {
6004 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
6005 }
6006 });
6007 }
6008
6009 fn drop_proposal(
6013 ov: &objc2_app_kit::NSOutlineView,
6014 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6015 item: Option<&objc2::runtime::AnyObject>,
6016 child_index: isize,
6017 ) -> Option<(u64, Option<u64>, Option<usize>)> {
6018 let src = unsafe { info.draggingSource() }?;
6019 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
6020 != std::ptr::from_ref::<objc2_app_kit::NSOutlineView>(ov).cast::<std::ffi::c_void>()
6021 {
6022 return None;
6023 }
6024 let pb = unsafe { info.draggingPasteboard() };
6025 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
6026 .to_string()
6027 .parse::<u64>()
6028 .ok()?;
6029 let parent = match item {
6030 Some(i) => Some(Self::token_of_item(i)?), None => None,
6032 };
6033 let index = (child_index >= 0).then_some(child_index as usize);
6034 Some((token, parent, index))
6035 }
6036
6037 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
6039 self.ivars()
6040 .source
6041 .borrow()
6042 .as_ref()
6043 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
6044 .is_some_and(|v| v == MoveVerdict::Allow)
6045 }
6046}
6047
6048define_class!(
6054 #[unsafe(super(objc2_app_kit::NSOutlineView))]
6055 #[thread_kind = MainThreadOnly]
6056 #[name = "DayOutlineView"]
6057 struct DayOutlineView;
6058
6059 impl DayOutlineView {
6060 #[unsafe(method(layout))]
6061 fn layout(&self) {
6062 sync_tree_width(self);
6063 let _: () = unsafe { msg_send![super(self), layout] };
6064 }
6065
6066 #[unsafe(method_id(menuForEvent:))]
6069 fn menu_for_event(
6070 &self,
6071 event: &objc2_app_kit::NSEvent,
6072 ) -> Option<Retained<NSMenu>> {
6073 ffi_guard::contain(None, || {
6074 let scroll = unsafe { self.enclosingScrollView() }?;
6075 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
6076 let row_menu = data
6077 .ivars()
6078 .source
6079 .borrow()
6080 .as_ref()
6081 .and_then(|s| s.row_menu.clone())?;
6082 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6083 let row = unsafe { self.rowAtPoint(p) };
6084 if row < 0 {
6085 return None;
6086 }
6087 let token =
6088 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
6089 let items = row_menu(token);
6090 if items.is_empty() {
6091 return None;
6092 }
6093 Some(build_ns_menu(self.mtm(), "", &items))
6094 })
6095 }
6096 }
6097);
6098
6099define_class!(
6106 #[unsafe(super(objc2_app_kit::NSTableRowView))]
6107 #[thread_kind = MainThreadOnly]
6108 #[name = "DayTreeRowView"]
6109 struct DayTreeRowView;
6110
6111 impl DayTreeRowView {
6112 #[unsafe(method(drawSelectionInRect:))]
6113 fn draw_selection_in_rect(&self, _dirty: NSRect) {
6114 if !unsafe { self.isSelected() } {
6115 return;
6116 }
6117 let color = if unsafe { self.isEmphasized() } {
6118 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
6119 } else {
6120 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
6121 };
6122 let b = self.bounds();
6123 let pill = NSRect::new(
6124 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
6125 NSSize::new(
6126 (b.size.width - 10.0).max(0.0),
6127 (b.size.height - 2.0).max(0.0),
6128 ),
6129 );
6130 unsafe {
6131 color.setFill();
6132 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
6133 pill, 5.0, 5.0,
6134 )
6135 .fill();
6136 }
6137 }
6138 }
6139);
6140
6141define_class!(
6145 #[unsafe(super(objc2_app_kit::NSTableCellView))]
6146 #[thread_kind = MainThreadOnly]
6147 #[name = "DayTreeCell"]
6148 struct DayTreeCell;
6149
6150 impl DayTreeCell {
6151 #[unsafe(method(isFlipped))]
6152 fn is_flipped(&self) -> bool {
6153 true
6154 }
6155
6156 #[unsafe(method(layout))]
6157 fn layout(&self) {
6158 let _: () = unsafe { msg_send![super(self), layout] };
6159 ffi_guard::contain((), || {
6160 let width = self.bounds().size.width;
6161 if width <= 0.0 {
6162 return;
6163 }
6164 let mut cur = unsafe { self.superview() };
6168 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
6169 while let Some(v) = cur {
6170 cur = unsafe { v.superview() };
6171 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
6172 outline = Some(ov);
6173 break;
6174 }
6175 }
6176 let Some(ov) = outline else { return };
6177 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
6178 return;
6179 };
6180 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
6181 .and_then(|(_, data)| {
6182 data.ivars()
6183 .source
6184 .borrow()
6185 .as_ref()
6186 .map(|s| s.layout_cell_size.clone())
6187 });
6188 if let Some(f) = f {
6189 f(std::ptr::from_ref::<Self>(self) as RawHandle, Size::new(width, self.bounds().size.height));
6190 }
6191 });
6192 }
6193 }
6194);
6195
6196impl DayTreeCell {
6197 fn new(mtm: MainThreadMarker) -> Retained<Self> {
6198 unsafe { msg_send![Self::alloc(mtm), init] }
6199 }
6200}
6201
6202const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
6204
6205type TreeEntry = (
6207 Retained<objc2_app_kit::NSOutlineView>,
6208 Retained<DayTreeData>,
6209);
6210
6211fn tree_entry(key: usize) -> Option<TreeEntry> {
6214 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
6215}
6216
6217fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
6221 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
6222 return;
6223 };
6224 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
6225 let f = outline.frame();
6226 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
6227 unsafe {
6228 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
6229 outline.sizeLastColumnToFit();
6230 }
6231 }
6232}
6233
6234fn post_realize_visible_tree_rows(key: usize) {
6237 <AppKit as Platform>::post(Box::new(move || {
6238 if let Some((outline, _)) = tree_entry(key) {
6239 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
6240 for row in range.location..range.location + range.length {
6241 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
6242 }
6243 }
6244 day_core::pump_events();
6245 }));
6246}
6247
6248type NavMenuEntry = (
6250 Retained<objc2_app_kit::NSOutlineView>,
6251 Retained<DayNavMenuData>,
6252);
6253
6254fn ns_rect(r: day_spec::Rect) -> NSRect {
6255 NSRect::new(
6256 NSPoint::new(r.origin.x, r.origin.y),
6257 NSSize::new(r.size.width, r.size.height),
6258 )
6259}
6260
6261fn draw_op(op: &DrawOp) {
6262 unsafe {
6263 match op {
6264 DrawOp::Stamp(st) => {
6270 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
6271 for p in &st.at {
6272 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
6273 unsafe { batch.appendBezierPath(©) };
6274 }
6275 }
6276 let color = match &st.paint {
6277 day_spec::Paint::Solid(c) => *c,
6278 _ => day_spec::Color::WHITE,
6281 };
6282 match &st.stroke {
6283 None => {
6284 nscolor(color).setFill();
6285 unsafe { batch.fill() };
6286 }
6287 Some(style) => {
6288 nscolor(color).setStroke();
6289 apply_stroke_style(&batch, style);
6290 unsafe { batch.stroke() };
6291 }
6292 }
6293 }
6294 DrawOp::Fill(shape, paint) => match paint {
6295 day_spec::Paint::Solid(color) => {
6296 nscolor(*color).setFill();
6297 if let Some(p) = bezier(shape) {
6298 p.fill();
6299 }
6300 }
6301 day_spec::Paint::Linear(g) => {
6302 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6305 let b = shape.bounds();
6306 let (s, e) = (g.start.resolve(b), g.end.resolve(b));
6307 NSGraphicsContext::saveGraphicsState_class();
6308 p.addClip();
6309 grad.drawFromPoint_toPoint_options(
6310 NSPoint::new(s.x, s.y),
6311 NSPoint::new(e.x, e.y),
6312 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6313 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6314 );
6315 NSGraphicsContext::restoreGraphicsState_class();
6316 }
6317 }
6318 day_spec::Paint::Radial(g) => {
6319 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6322 let b = shape.bounds();
6323 NSGraphicsContext::saveGraphicsState_class();
6324 p.addClip();
6325 concat_unit_to_bounds(b);
6326 let c = NSPoint::new(g.center.x, g.center.y);
6327 grad.drawFromCenter_radius_toCenter_radius_options(
6328 c,
6329 0.0,
6330 c,
6331 g.radius,
6332 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6333 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6334 );
6335 NSGraphicsContext::restoreGraphicsState_class();
6336 }
6337 }
6338 },
6339 DrawOp::Stroke(shape, paint, style) => {
6340 if let Some(p) = bezier(shape) {
6341 apply_stroke_style(&p, style);
6342 if let day_spec::Paint::Solid(color) = paint {
6343 nscolor(*color).setStroke();
6344 p.stroke();
6345 } else {
6346 let Some(ctx) = NSGraphicsContext::currentContext() else {
6352 return;
6353 };
6354 let cg = ctx.CGContext();
6355 NSGraphicsContext::saveGraphicsState_class();
6356 objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
6357 objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(&cg));
6358 objc2_core_graphics::CGContext::clip(Some(&cg));
6359 draw_gradient_in(paint, shape.bounds());
6360 NSGraphicsContext::restoreGraphicsState_class();
6361 }
6362 }
6363 }
6364 DrawOp::Clip(shape) => {
6365 if let Some(p) = bezier(shape) {
6367 p.addClip();
6368 }
6369 }
6370 DrawOp::Text {
6371 text,
6372 at,
6373 size,
6374 color,
6375 anchor,
6376 font,
6377 } => {
6378 let font = canvas_nsfont(*size, font);
6379 let attrs = canvas_text_attrs(&font, *color);
6380 let ns = NSString::from_str(text);
6381 let mut origin = NSPoint::new(at.x, at.y);
6382 if *anchor != day_spec::TextAnchor::LEADING {
6387 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
6388 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
6389 origin.x += dx;
6390 origin.y += dy;
6391 }
6392 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
6393 }
6394 DrawOp::Image {
6398 image,
6399 rect,
6400 opacity,
6401 source,
6402 } => {
6403 let held = BITMAPS.with(|m| {
6404 m.borrow()
6405 .get(&image.0)
6406 .map(|b| (b.image.clone(), b.info.pixels))
6407 });
6408 if let Some((img, pixels)) = held {
6409 let region = match source {
6415 None => Some((NSRect::ZERO, *rect)),
6416 Some(src) => {
6417 day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
6418 let sz = img.size();
6419 let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
6420 let from = NSRect::new(
6421 NSPoint::new(
6422 src.origin.x * rx,
6423 (pixels.height - src.origin.y - src.size.height) * ry,
6424 ),
6425 NSSize::new(src.size.width * rx, src.size.height * ry),
6426 );
6427 (from, dest)
6428 })
6429 }
6430 };
6431 if let Some((from, dest)) = region {
6432 let dest = NSRect::new(
6433 NSPoint::new(dest.origin.x, dest.origin.y),
6434 NSSize::new(dest.size.width, dest.size.height),
6435 );
6436 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
6440 dest,
6441 from,
6442 objc2_app_kit::NSCompositingOperation::SourceOver,
6443 *opacity,
6444 true,
6445 None,
6446 );
6447 }
6448 }
6449 }
6450 DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
6451 DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
6452 DrawOp::Concat(m) => {
6453 let t = NSAffineTransform::new();
6454 t.setTransformStruct(NSAffineTransformStruct {
6455 m11: m.a,
6456 m12: m.b,
6457 m21: m.c,
6458 m22: m.d,
6459 tX: m.tx,
6460 tY: m.ty,
6461 });
6462 t.concat();
6463 }
6464 }
6465 }
6466}
6467
6468fn nsgradient(
6470 stops: &[(f64, day_spec::Color)],
6471) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
6472 if stops.is_empty() {
6473 return None;
6474 }
6475 let colors = objc2_foundation::NSArray::from_retained_slice(
6476 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
6477 );
6478 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
6479 unsafe {
6480 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
6481 objc2_app_kit::NSGradient::alloc(),
6482 &colors,
6483 locations.as_ptr(),
6484 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
6485 )
6486 }
6487}
6488
6489fn concat_unit_to_bounds(b: day_spec::Rect) {
6492 let t = NSAffineTransform::new();
6493 t.setTransformStruct(NSAffineTransformStruct {
6494 m11: b.size.width,
6495 m12: 0.0,
6496 m21: 0.0,
6497 m22: b.size.height,
6498 tX: b.origin.x,
6499 tY: b.origin.y,
6500 });
6501 unsafe { t.concat() };
6502}
6503
6504fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
6510 use day_spec::{LineCap, LineJoin};
6511 unsafe {
6512 p.setLineWidth(style.width);
6513 p.setLineCapStyle(match style.cap {
6514 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
6515 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
6516 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
6517 });
6518 if style.is_plain() {
6519 return;
6520 }
6521 p.setLineJoinStyle(match style.join {
6522 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
6523 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
6524 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
6525 });
6526 p.setMiterLimit(style.miter_limit);
6527 if !style.dash.is_empty() {
6528 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
6529 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
6530 }
6531 }
6532}
6533
6534fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6538 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6539 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6540 match paint {
6541 day_spec::Paint::Linear(g) => {
6542 if let Some(grad) = nsgradient(&g.stops) {
6543 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6544 unsafe {
6545 grad.drawFromPoint_toPoint_options(
6546 NSPoint::new(s.x, s.y),
6547 NSPoint::new(e.x, e.y),
6548 opts,
6549 );
6550 };
6551 }
6552 }
6553 day_spec::Paint::Radial(g) => {
6554 if let Some(grad) = nsgradient(&g.stops) {
6555 NSGraphicsContext::saveGraphicsState_class();
6556 concat_unit_to_bounds(bounds);
6557 let c = NSPoint::new(g.center.x, g.center.y);
6558 unsafe {
6559 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts);
6560 };
6561 NSGraphicsContext::restoreGraphicsState_class();
6562 }
6563 }
6564 day_spec::Paint::Solid(_) => {}
6565 }
6566}
6567
6568fn apply_button_content(
6569 btn: &NSButton,
6570 title: &str,
6571 icon: Option<&day_spec::Icon>,
6572 icon_only: bool,
6573) {
6574 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6575 if let Some(image) = &image {
6576 let size = image.size();
6577 let longest = size.width.max(size.height);
6578 if longest > 0.0 {
6579 image.setSize(objc2_foundation::NSSize::new(
6580 size.width * 20.0 / longest,
6581 size.height * 20.0 / longest,
6582 ));
6583 }
6584 }
6585 let style = BUTTON_STYLES
6586 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6587 .unwrap_or_default();
6588 BUTTON_IMAGES.with(|images| {
6589 let _ = images.remove(ptr_of(btn));
6590 if let Some(image) = &image {
6591 images.insert(ptr_of(btn), image.clone());
6592 }
6593 });
6594 set_button_title(btn, title, style);
6595 unsafe {
6598 btn.setImagePosition(if image.is_none() {
6599 objc2_app_kit::NSCellImagePosition::NoImage
6600 } else if icon_only {
6601 objc2_app_kit::NSCellImagePosition::ImageOnly
6602 } else {
6603 objc2_app_kit::NSCellImagePosition::ImageLeading
6604 });
6605 }
6606 set_button_image(btn, style);
6607 unsafe {
6608 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6611 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6612 }
6613 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6614 btn.setToolTip(tooltip.as_deref());
6615 }
6616}
6617
6618fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6622 use day_spec::props::ButtonStyleSpec as S;
6623 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6624 let image = image.map(|source| {
6625 let S::Tinted(fill) = style else {
6626 return source;
6627 };
6628 let size = source.size();
6629 let ink = nscolor(S::on_tint(fill));
6630 let draw = block2::RcBlock::new(move |rect: NSRect| {
6631 source.drawInRect_fromRect_operation_fraction(
6632 rect,
6633 NSRect::ZERO,
6634 objc2_app_kit::NSCompositingOperation::SourceOver,
6635 1.0,
6636 );
6637 unsafe {
6638 ink.setFill();
6639 objc2_app_kit::NSRectFillUsingOperation(
6640 rect,
6641 objc2_app_kit::NSCompositingOperation::SourceIn,
6642 );
6643 }
6644 objc2::runtime::Bool::YES
6645 });
6646 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6647 });
6648 unsafe {
6649 let position = btn.imagePosition();
6650 let image = image.map(|source| {
6655 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6658 return source;
6659 }
6660 let size = source.size();
6661 let template = source.isTemplate();
6662 let padded = NSSize::new(size.width + 8.0, size.height);
6663 let draw = block2::RcBlock::new(move |_rect: NSRect| {
6664 source.drawInRect_fromRect_operation_fraction(
6665 NSRect::new(NSPoint::new(0.0, 0.0), size),
6666 NSRect::ZERO,
6667 objc2_app_kit::NSCompositingOperation::SourceOver,
6668 1.0,
6669 );
6670 objc2::runtime::Bool::YES
6671 });
6672 let out =
6673 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6674 out.setTemplate(template);
6675 out
6676 });
6677 btn.setImage(image.as_deref());
6678 btn.setImagePosition(position);
6679 btn.setImageHugsTitle(true);
6680 }
6681}
6682
6683fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6689 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6690 unsafe {
6691 if on {
6692 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6693 }
6694 btn.setState(if on {
6695 NSControlStateValueOn
6696 } else {
6697 NSControlStateValueOff
6698 });
6699 }
6700}
6701
6702const TINT_CORNER_RADIUS: f64 = 6.0;
6705
6706fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6716 use day_spec::props::ButtonStyleSpec as S;
6717 let title = unsafe { btn.title() }.to_string();
6718 unsafe {
6719 btn.setKeyEquivalent(&NSString::from_str(""));
6721 btn.setBezelColor(None);
6722 btn.setBordered(!matches!(style, S::Plain));
6723 match style {
6724 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6725 S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6726 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6729 }
6730 btn.setWantsLayer(true);
6731 if let Some(layer) = btn.layer() {
6732 match style {
6733 S::Tinted(c) => {
6734 layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6735 layer.setCornerRadius(TINT_CORNER_RADIUS);
6736 }
6737 _ => layer.setBackgroundColor(None),
6738 }
6739 }
6740 }
6741 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6742 let ink = match style {
6743 S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6744 _ => None,
6745 };
6746 unsafe {
6747 btn.setContentTintColor(ink.as_deref());
6748 }
6749 set_button_title(btn, &title, style);
6750 set_button_image(btn, style);
6751}
6752
6753fn set_button_title(
6763 btn: &objc2_app_kit::NSButton,
6764 title: &str,
6765 style: day_spec::props::ButtonStyleSpec,
6766) {
6767 use day_spec::props::ButtonStyleSpec as S;
6768 let position = unsafe { btn.imagePosition() };
6771 let S::Tinted(fill) = style else {
6772 unsafe {
6774 btn.setTitle(&NSString::from_str(title));
6775 btn.setImagePosition(position);
6776 }
6777 return;
6778 };
6779 unsafe {
6780 let col = nscolor(S::on_tint(fill));
6781 let font = btn
6782 .font()
6783 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6784 let para = objc2_app_kit::NSMutableParagraphStyle::new();
6787 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6788 let keys: [&NSString; 3] = [
6789 objc2_app_kit::NSFontAttributeName,
6790 objc2_app_kit::NSForegroundColorAttributeName,
6791 objc2_app_kit::NSParagraphStyleAttributeName,
6792 ];
6793 let objs: [&objc2::runtime::AnyObject; 3] = [
6794 font.as_ref() as &objc2::runtime::AnyObject,
6795 col.as_ref() as &objc2::runtime::AnyObject,
6796 para.as_ref() as &objc2::runtime::AnyObject,
6797 ];
6798 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6799 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6800 objc2_foundation::NSAttributedString::alloc(),
6801 &NSString::from_str(title),
6802 Some(&attrs),
6803 );
6804 btn.setAttributedTitle(&s);
6805 btn.setImagePosition(position);
6806 }
6807}
6808
6809define_class!(
6812 #[unsafe(super(objc2_app_kit::NSImageView))]
6813 #[thread_kind = MainThreadOnly]
6814 #[name = "DayFillImageView"]
6815 struct FillImageView;
6816
6817 impl FillImageView {
6818 #[unsafe(method(drawRect:))]
6819 fn draw_rect(&self, dirty: NSRect) {
6820 let bounds = self.bounds();
6821 let image = unsafe { self.image() };
6822 let Some(size) = image.map(|image| image.size()).filter(|size| {
6823 size.width > 0.0 && size.height > 0.0
6824 && bounds.size.width > 0.0 && bounds.size.height > 0.0
6825 }) else {
6826 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6827 return;
6828 };
6829 let x = bounds.size.width / size.width;
6830 let y = bounds.size.height / size.height;
6831 let scale = x.max(y) / x.min(y);
6832 let cx = bounds.origin.x + bounds.size.width / 2.0;
6833 let cy = bounds.origin.y + bounds.size.height / 2.0;
6834 NSGraphicsContext::saveGraphicsState_class();
6835 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6836 let transform = NSAffineTransform::transform();
6837 transform.translateXBy_yBy(cx, cy);
6838 transform.scaleBy(scale);
6839 transform.translateXBy_yBy(-cx, -cy);
6840 transform.concat();
6841 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6842 NSGraphicsContext::restoreGraphicsState_class();
6843 }
6844
6845 #[unsafe(method(setFrameSize:))]
6846 fn set_frame_size(&self, size: NSSize) {
6847 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6848 NSView::setNeedsDisplay(self, true);
6849 }
6850 }
6851);
6852
6853fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6854 use day_spec::Shape;
6855 use objc2_app_kit::NSBezierPath;
6856 unsafe {
6857 Some(match shape {
6858 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6859 Shape::RoundedRect(r, rad) => {
6860 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6861 }
6862 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6863 Shape::Arc {
6864 rect,
6865 start_deg,
6866 sweep_deg,
6867 } => {
6868 let p = NSBezierPath::new();
6869 let center = NSPoint::new(
6870 rect.origin.x + rect.size.width / 2.0,
6871 rect.origin.y + rect.size.height / 2.0,
6872 );
6873 let radius = rect.size.width.min(rect.size.height) / 2.0;
6874 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6876 center,
6877 radius,
6878 *start_deg,
6879 *start_deg + *sweep_deg,
6880 );
6881 p
6882 }
6883 Shape::Line(a, b) => {
6884 let p = NSBezierPath::new();
6885 p.moveToPoint(NSPoint::new(a.x, a.y));
6886 p.lineToPoint(NSPoint::new(b.x, b.y));
6887 p
6888 }
6889 Shape::Polygon(pts) => {
6890 if pts.len() < 2 {
6891 return None;
6892 }
6893 let p = NSBezierPath::new();
6894 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6895 for pt in &pts[1..] {
6896 p.lineToPoint(NSPoint::new(pt.x, pt.y));
6897 }
6898 p.closePath();
6899 p
6900 }
6901 Shape::Path(path) => {
6902 use day_spec::PathSeg;
6903 if path.segs.is_empty() {
6904 return None;
6905 }
6906 let p = NSBezierPath::new();
6907 let mut cur = NSPoint::new(0.0, 0.0);
6911 for seg in &path.segs {
6912 match seg {
6913 PathSeg::Move(a) => {
6914 cur = NSPoint::new(a.x, a.y);
6915 p.moveToPoint(cur);
6916 }
6917 PathSeg::Line(a) => {
6918 cur = NSPoint::new(a.x, a.y);
6919 p.lineToPoint(cur);
6920 }
6921 PathSeg::Quad(c, a) => {
6922 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6923 let c1 = NSPoint::new(
6924 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6925 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6926 );
6927 let c2 = NSPoint::new(
6928 end.x + 2.0 / 3.0 * (ctl.x - end.x),
6929 end.y + 2.0 / 3.0 * (ctl.y - end.y),
6930 );
6931 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6932 cur = end;
6933 }
6934 PathSeg::Cubic(c1, c2, a) => {
6935 cur = NSPoint::new(a.x, a.y);
6936 p.curveToPoint_controlPoint1_controlPoint2(
6937 cur,
6938 NSPoint::new(c1.x, c1.y),
6939 NSPoint::new(c2.x, c2.y),
6940 );
6941 }
6942 PathSeg::Close => p.closePath(),
6943 }
6944 }
6945 p.setWindingRule(match path.rule {
6946 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6947 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6948 });
6949 p
6950 }
6951 })
6952 }
6953}
6954
6955struct UndoIvars {
6963 state: std::cell::RefCell<day_spec::UndoState>,
6964}
6965
6966define_class!(
6967 #[unsafe(super(objc2_foundation::NSUndoManager))]
6968 #[thread_kind = MainThreadOnly]
6969 #[name = "DayUndoManager"]
6970 #[ivars = UndoIvars]
6971 struct DayUndoManager;
6972
6973 impl DayUndoManager {
6977 #[unsafe(method(canUndo))]
6978 fn can_undo(&self) -> bool {
6979 self.ivars().state.borrow().can_undo
6980 }
6981
6982 #[unsafe(method(canRedo))]
6983 fn can_redo(&self) -> bool {
6984 self.ivars().state.borrow().can_redo
6985 }
6986
6987 #[unsafe(method(undo))]
6988 fn do_undo(&self) {
6989 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }));
6990 }
6991
6992 #[unsafe(method(redo))]
6993 fn do_redo(&self) {
6994 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }));
6995 }
6996
6997 #[unsafe(method_id(undoMenuItemTitle))]
6998 fn undo_menu_item_title(&self) -> Retained<NSString> {
6999 let label = self.ivars().state.borrow().undo_label.clone();
7002 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7003 }
7004
7005 #[unsafe(method_id(redoMenuItemTitle))]
7006 fn redo_menu_item_title(&self) -> Retained<NSString> {
7007 let label = self.ivars().state.borrow().redo_label.clone();
7008 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7009 }
7010 }
7011);
7012
7013fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
7014 UNDO_FRONT.with(|u| {
7015 u.borrow_mut()
7016 .get_or_insert_with(|| {
7017 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
7018 state: std::cell::RefCell::new(day_spec::UndoState::default()),
7019 });
7020 unsafe { msg_send![super(this), init] }
7021 })
7022 .clone()
7023 })
7024}
7025
7026struct WinIvars {
7034 node: Option<NodeId>,
7035 group: Option<String>,
7038 last_state: Cell<i32>,
7041}
7042
7043define_class!(
7044 #[unsafe(super(NSObject))]
7045 #[thread_kind = MainThreadOnly]
7046 #[name = "DayWinDelegate"]
7047 #[ivars = WinIvars]
7048 struct DayWinDelegate;
7049
7050 unsafe impl NSObjectProtocol for DayWinDelegate {}
7051
7052 impl DayWinDelegate {
7056 #[unsafe(method(undo:))]
7060 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7061 ffi_guard::contain((), || {
7062 if let Some(m) = self.acting_undo_manager() {
7063 unsafe { m.undo() };
7064 }
7065 });
7066 }
7067
7068 #[unsafe(method(redo:))]
7070 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7071 ffi_guard::contain((), || {
7072 if let Some(m) = self.acting_undo_manager() {
7073 unsafe { m.redo() };
7074 }
7075 });
7076 }
7077
7078 #[unsafe(method(cut:))]
7079 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7080 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
7081 }
7082
7083 #[unsafe(method(copy:))]
7084 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7085 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
7086 }
7087
7088 #[unsafe(method(paste:))]
7089 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7090 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
7091 }
7092
7093 #[unsafe(method(selectAll:))]
7094 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7095 ffi_guard::contain((), || {
7096 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
7097 });
7098 }
7099
7100 #[unsafe(method(validateMenuItem:))]
7104 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
7105 ffi_guard::contain(false, || {
7106 let state = EDIT_STATE.with(std::cell::Cell::get);
7107 match unsafe { item.action() } {
7108 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
7111 Some(m) => {
7112 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
7113 unsafe { m.canUndo() }
7114 }
7115 None => false,
7116 },
7117 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
7118 Some(m) => {
7119 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
7120 unsafe { m.canRedo() }
7121 }
7122 None => false,
7123 },
7124 Some(a) if a == sel!(selectAll:) => state.can_select_all,
7125 Some(a) if a == sel!(cut:) => state.can_cut,
7126 Some(a) if a == sel!(copy:) => state.can_copy,
7127 Some(a) if a == sel!(paste:) => {
7128 state.can_paste && {
7129 let pb = unsafe { NSPasteboard::generalPasteboard() };
7130 pb.types().is_some_and(|types| !types.is_empty())
7131 }
7132 }
7133 _ => true,
7134 }
7135 })
7136 }
7137 }
7138
7139 unsafe impl NSWindowDelegate for DayWinDelegate {
7140 #[unsafe(method(windowDidResize:))]
7141 fn window_did_resize(&self, notification: &NSNotification) {
7142 ffi_guard::contain((), || {
7143 if let Some(obj) = unsafe { notification.object() }
7144 && let Ok(win) = obj.downcast::<NSWindow>()
7145 && let Some(size) = pin_below_title_bar(&win)
7146 {
7147 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7148 emit(target, Event::WindowResized(size));
7149 }
7150 self.report_state_of(notification);
7152 });
7153 }
7154
7155 #[unsafe(method(windowShouldClose:))]
7156 fn window_should_close(&self, _window: &NSWindow) -> bool {
7157 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
7158 }
7159
7160 #[unsafe(method(windowWillClose:))]
7161 fn window_will_close(&self, _notification: &NSNotification) {
7162 ffi_guard::contain((), || {
7163 match self.ivars().node {
7164 Some(node) => emit(node, Event::WindowClosed),
7167 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
7172 None => {
7173 let app = NSApplication::sharedApplication(self.mtm());
7174 unsafe { app.terminate(None) };
7175 }
7176 }
7177 });
7178 }
7179
7180 #[unsafe(method_id(windowWillReturnUndoManager:))]
7181 fn window_will_return_undo_manager(
7182 &self,
7183 _window: &NSWindow,
7184 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7185 ffi_guard::contain(None, || {
7189 UNDO_FRONT.with(|u| {
7190 u.borrow()
7191 .as_ref()
7192 .map(|m| Retained::into_super(m.clone()))
7193 })
7194 })
7195 }
7196
7197 #[unsafe(method(windowDidBecomeKey:))]
7198 fn window_did_become_key(&self, _notification: &NSNotification) {
7199 ffi_guard::contain((), || {
7200 if let Some(node) = self.ivars().node {
7201 emit(node, Event::WindowFocused(true));
7202 }
7203 });
7204 }
7205
7206 #[unsafe(method(windowDidResignKey:))]
7207 fn window_did_resign_key(&self, _notification: &NSNotification) {
7208 ffi_guard::contain((), || {
7209 if let Some(node) = self.ivars().node {
7210 emit(node, Event::WindowFocused(false));
7211 }
7212 });
7213 }
7214
7215 #[unsafe(method(windowDidMiniaturize:))]
7216 fn window_did_miniaturize(&self, notification: &NSNotification) {
7217 ffi_guard::contain((), || self.report_state_of(notification));
7218 }
7219
7220 #[unsafe(method(windowDidDeminiaturize:))]
7221 fn window_did_deminiaturize(&self, notification: &NSNotification) {
7222 ffi_guard::contain((), || self.report_state_of(notification));
7223 }
7224
7225 #[unsafe(method(windowDidEnterFullScreen:))]
7226 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
7227 ffi_guard::contain((), || self.report_state_of(notification));
7228 }
7229
7230 #[unsafe(method(windowDidExitFullScreen:))]
7231 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
7232 ffi_guard::contain((), || self.report_state_of(notification));
7233 }
7234 }
7235
7236 impl DayWinDelegate {
7240 #[unsafe(method(newWindowForTab:))]
7241 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
7242 ffi_guard::contain((), || {
7243 let _ = match self.ivars().group.as_deref() {
7246 Some(group) => day_core::windows::open_new_window_for_group(group),
7247 None => day_core::windows::open_new_window(),
7248 };
7249 });
7250 }
7251 }
7252);
7253
7254impl DayWinDelegate {
7255 fn report_state_of(&self, notification: &NSNotification) {
7256 if let Some(obj) = unsafe { notification.object() }
7257 && let Ok(win) = obj.downcast::<NSWindow>()
7258 {
7259 self.report_state(&win);
7260 }
7261 }
7262}
7263
7264fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7267 match unsafe { event.keyCode() } {
7268 123 => Some("ArrowLeft"),
7269 124 => Some("ArrowRight"),
7270 125 => Some("ArrowDown"),
7271 126 => Some("ArrowUp"),
7272 _ => {
7280 let held = NSEventModifierFlags::Command
7281 | NSEventModifierFlags::Option
7282 | NSEventModifierFlags::Control;
7283 if event.modifierFlags().intersects(held) {
7284 return None;
7285 }
7286 let typed = event.characters()?.to_string();
7287 let mut chars = typed.chars();
7288 match (chars.next(), chars.next()) {
7289 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
7290 _ => None,
7291 }
7292 }
7293 }
7294}
7295
7296fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7299 Some(match unsafe { event.keyCode() } {
7300 123 => "ArrowLeft",
7301 124 => "ArrowRight",
7302 125 => "ArrowDown",
7303 126 => "ArrowUp",
7304 36 | 76 => "Enter",
7305 48 => "Tab",
7306 53 => "Escape",
7307 51 => "Backspace",
7308 117 => "Delete",
7309 115 => "Home",
7310 119 => "End",
7311 116 => "PageUp",
7312 121 => "PageDown",
7313 114 => "Insert",
7314 122 => "F1",
7315 120 => "F2",
7316 99 => "F3",
7317 118 => "F4",
7318 96 => "F5",
7319 97 => "F6",
7320 98 => "F7",
7321 100 => "F8",
7322 101 => "F9",
7323 109 => "F10",
7324 103 => "F11",
7325 111 => "F12",
7326 _ => return None,
7327 })
7328}
7329
7330fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
7341 let ptr = std::ptr::from_ref::<DayCanvas>(view).cast::<NSView>() as usize;
7342 let flags = event.modifierFlags();
7343 let mods = key_modifiers(flags);
7344 if flags.contains(NSEventModifierFlags::Command) {
7345 return false;
7346 }
7347 let composing = MARKED.with(|t| t.contains(ptr));
7348 if !composing && let Some(named) = named_key(event) {
7349 emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
7350 return true;
7351 }
7352 let unmodified =
7353 unsafe { event.charactersIgnoringModifiers() }.map_or_default(|s| s.to_string());
7354 let typeable = !unmodified.is_empty()
7356 && !unmodified
7357 .chars()
7358 .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
7359 if !composing && flags.contains(NSEventModifierFlags::Control) {
7360 if typeable {
7361 emit(
7362 node,
7363 Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
7364 );
7365 }
7366 return true;
7367 }
7368 if !composing && !typeable {
7369 return true;
7370 }
7371 INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
7372 view.interpretKeyEvents(&NSArray::from_slice(&[event]));
7373 INTERPRETING.with(|i| *i.borrow_mut() = None);
7374 true
7375}
7376
7377fn text_of_input_string(string: &AnyObject) -> String {
7379 if let Some(s) = string.downcast_ref::<NSString>() {
7380 s.to_string()
7381 } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
7382 s.string().to_string()
7383 } else {
7384 String::new()
7385 }
7386}
7387
7388fn key_modifiers(f: NSEventModifierFlags) -> u8 {
7390 let mut modifiers = 0u8;
7391 if f.contains(NSEventModifierFlags::Shift) {
7392 modifiers |= day_spec::KeyEvent::SHIFT;
7393 }
7394 if f.contains(NSEventModifierFlags::Command) {
7395 modifiers |= day_spec::KeyEvent::PRIMARY;
7396 }
7397 if f.contains(NSEventModifierFlags::Option) {
7398 modifiers |= day_spec::KeyEvent::ALT;
7399 }
7400 if f.contains(NSEventModifierFlags::Control) {
7401 modifiers |= day_spec::KeyEvent::CONTROL;
7402 }
7403 modifiers
7404}
7405
7406impl DayWinDelegate {
7407 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7412 let responder = NSApplication::sharedApplication(self.mtm())
7413 .keyWindow()
7414 .and_then(|w| w.firstResponder());
7415 responder
7416 .and_then(|r| unsafe { r.undoManager() })
7417 .or_else(|| {
7418 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
7419 })
7420 }
7421}
7422
7423impl DayWinDelegate {
7424 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
7425 let this = Self::alloc(mtm).set_ivars(WinIvars {
7426 node,
7427 group,
7428 last_state: Cell::new(day_spec::WindowState::Normal.code()),
7429 });
7430 unsafe { msg_send![super(this), init] }
7431 }
7432
7433 fn report_state(&self, window: &NSWindow) {
7437 let state = ns_window_state(window);
7438 if self.ivars().last_state.replace(state.code()) != state.code() {
7439 log::debug!("appkit: window state now {state:?}");
7440 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7441 emit(target, Event::WindowStateChanged(state));
7442 }
7443 }
7444}
7445
7446fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
7449 if window.isMiniaturized() {
7450 day_spec::WindowState::Minimized
7451 } else if window
7452 .styleMask()
7453 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
7454 {
7455 day_spec::WindowState::Fullscreen
7456 } else if window.isZoomed() {
7457 day_spec::WindowState::Maximized
7458 } else {
7459 day_spec::WindowState::Normal
7460 }
7461}
7462
7463fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
7466 use day_spec::WindowState as S;
7467 let current = ns_window_state(window);
7468 if current == state {
7469 return;
7470 }
7471 unsafe {
7472 match current {
7473 S::Minimized => window.deminiaturize(None),
7474 S::Fullscreen => {
7478 window.toggleFullScreen(None);
7479 return;
7480 }
7481 S::Maximized if state != S::Minimized => window.zoom(None),
7482 _ => {}
7483 }
7484 match state {
7485 S::Normal => {}
7486 S::Minimized => window.miniaturize(None),
7487 S::Maximized => {
7488 if !window.isZoomed() {
7489 window.zoom(None);
7490 }
7491 }
7492 S::Fullscreen => window.toggleFullScreen(None),
7493 }
7494 }
7495}
7496
7497#[distributed_slice]
7503pub static RENDERERS: [fn() -> Renderer<AppKit>];
7504
7505struct SecondaryWin {
7509 window: Retained<NSWindow>,
7510 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
7512 content: Handle,
7513}
7514
7515struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
7518impl Drop for MenuEscapeMonitor {
7519 fn drop(&mut self) {
7520 unsafe { NSEvent::removeMonitor(&self.0) };
7521 }
7522}
7523
7524pub struct AppKit {
7525 menu_escape_monitor: Option<MenuEscapeMonitor>,
7526 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
7527 sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
7529
7530 mtm: MainThreadMarker,
7531 registry: Registry<AppKit>,
7532 window: Option<Retained<NSWindow>>,
7533 content: Option<Handle>,
7534 secondary: Vec<SecondaryWin>,
7535 app_name: String,
7536 cascade: Option<NSPoint>,
7541 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7544}
7545
7546impl AppKit {
7547 fn swap_text_field(
7552 &mut self,
7553 h: &Handle,
7554 old: &NSTextField,
7555 node: NodeId,
7556 secure: bool,
7557 ) -> Retained<NSTextField> {
7558 let new = new_text_field(self.mtm, node, secure);
7559 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7560 let window = h.window();
7563 let focused = window
7564 .as_deref()
7565 .is_some_and(|w| owns_first_responder(w, h));
7566 let selection = old.currentEditor().map(|e| e.selectedRange());
7567 unsafe {
7568 new.setStringValue(&old.stringValue());
7569 new.setPlaceholderString(old.placeholderString().as_deref());
7570 new.setEnabled(old.isEnabled());
7571 new.setFont(old.font().as_deref());
7572 new.setFrame(h.frame());
7573 new.setHidden(h.isHidden());
7574 new.setMenu(h.menu().as_deref());
7575 new.setToolTip(h.toolTip().as_deref());
7576 if h.wantsLayer() {
7578 new.setWantsLayer(true);
7579 new.setAlphaValue(h.alphaValue());
7580 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7581 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7582 if !from.is_null() && !to.is_null() {
7583 let t: CGAffineTransform = msg_send![from, affineTransform];
7584 let _: () = msg_send![to, setAffineTransform: t];
7585 }
7586 }
7587 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7590 new.setAccessibilityIdentifier(Some(&id));
7591 }
7592 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7593 new.setAccessibilityLabel(Some(&label));
7594 }
7595 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7596 new.setAccessibilityHelp(Some(&help));
7597 }
7598 if !h.isAccessibilityElement() {
7599 new.setAccessibilityElement(false);
7600 }
7601 }
7602 for r in &unsafe { h.gestureRecognizers() } {
7604 unsafe {
7605 h.removeGestureRecognizer(&r);
7606 new.addGestureRecognizer(&r);
7607 }
7608 }
7609 GESTURES.with(|m| {
7610 let mut m = m.borrow_mut();
7611 if let Some(targets) = m.remove(&old_key) {
7612 m.insert(new_key, targets);
7613 }
7614 });
7615 if let Some((owner, area)) = self.cursors.remove(&old_key) {
7616 unsafe {
7617 h.removeTrackingArea(&area);
7618 new.addTrackingArea(&area);
7619 }
7620 self.cursors.insert(new_key, (owner, area));
7621 }
7622 PAN_NODES.with(|t| rekey(t, old_key, new_key));
7623 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7624 ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
7625 ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
7626 KEY_NODES.with(|t| rekey(t, old_key, new_key));
7627 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7628 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7629 transfer::moved(h, &new);
7630 unsafe { old.setDelegate(None) };
7633 TARGETS.with(|m| {
7634 m.borrow_mut().remove(&old_key);
7635 });
7636 if let Some(parent) = unsafe { h.superview() } {
7637 unsafe {
7638 parent.addSubview_positioned_relativeTo(
7639 &new,
7640 objc2_app_kit::NSWindowOrderingMode::Above,
7641 Some(h),
7642 );
7643 h.removeFromSuperview();
7644 }
7645 }
7646 if focused && let Some(window) = window {
7647 FIELD_SWAP.with(|s| s.set(true));
7648 let taken = window.makeFirstResponder(Some(&new));
7649 FIELD_SWAP.with(|s| s.set(false));
7650 if taken && let Some(editor) = new.currentEditor() {
7653 let len = unsafe { new.stringValue() }.length();
7654 let range = selection
7655 .filter(|r| r.location.saturating_add(r.length) <= len)
7656 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7657 editor.setSelectedRange(range);
7658 }
7659 }
7660 day_spec::sidetable::sweep(old_key);
7662 new
7663 }
7664
7665 #[must_use]
7671 pub fn new() -> Self {
7672 let mtm =
7673 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7674 let mut registry = Registry::default();
7675 for f in RENDERERS {
7676 registry.register(f());
7677 }
7678 AppKit {
7679 menu_escape_monitor: None,
7680 mtm,
7681 registry,
7682 window: None,
7683 sharing: None,
7684 sharing_delegate: None,
7685 content: None,
7686 secondary: Vec::new(),
7687 app_name: "Day".into(),
7688 cascade: None,
7689 cursors: HashMap::new(),
7690 }
7691 }
7692
7693 #[must_use]
7695 pub fn mtm(&self) -> MainThreadMarker {
7696 self.mtm
7697 }
7698
7699 fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
7708 if content.window().is_none_or(|w| w.isVisible()) {
7709 return None;
7710 }
7711 let main = NSApplication::sharedApplication(self.mtm).mainWindow();
7712 let anchor = main
7713 .filter(|m| {
7714 self.secondary
7715 .iter()
7716 .any(|w| std::ptr::eq(&raw const *w.window, &raw const **m))
7717 })
7718 .or_else(|| {
7719 self.secondary
7720 .iter()
7721 .find(|w| w.window.isVisible())
7722 .map(|w| w.window.clone())
7723 })?;
7724 let shown = anchor
7725 .tabGroup()
7726 .and_then(|g| g.selectedWindow())
7727 .unwrap_or(anchor);
7728 self.secondary
7729 .iter()
7730 .find(|w| std::ptr::eq(&raw const *w.window, &raw const *shown) && w.window.isVisible())
7731 .map(|w| w.content.clone())
7732 }
7733
7734 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7735 if let Some(w) = self
7736 .secondary
7737 .iter()
7738 .find(|w| ptr_of(&w.content) == ptr_of(host))
7739 {
7740 return Some(w.window.clone());
7741 }
7742 self.content
7743 .as_ref()
7744 .filter(|c| ptr_of(c) == ptr_of(host))
7745 .and(self.window.clone())
7746 }
7747
7748 fn make_window(
7754 &self,
7755 options: &WindowOptions,
7756 prefs_style: bool,
7757 node: Option<NodeId>,
7758 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7759 use day_spec::WindowTabbing as T;
7760 use objc2_app_kit::NSWindowTabbingMode as M;
7761 let mtm = self.mtm;
7762 let (title, size, min_size, tabbing) = (
7763 options.title.as_str(),
7764 options.size,
7765 options.min_size,
7766 &options.tabbing,
7767 );
7768 let content_rect =
7769 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7770 let style = window_chrome::style_mask(options, prefs_style);
7772 let window = window_chrome::alloc_window(
7773 mtm,
7774 content_rect,
7775 style,
7776 options.chrome == day_spec::WindowChrome::Frameless,
7777 );
7778 unsafe { window.setReleasedWhenClosed(false) };
7779 window.setTitle(&NSString::from_str(title));
7780 if let Some(min) = min_size {
7781 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7782 }
7783 if let Some(max) = options.max_size {
7784 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7785 }
7786 let group = match tabbing {
7787 T::Group(g) | T::Preferred(g) => Some(g.clone()),
7788 T::Automatic | T::Disallowed => None,
7789 };
7790 match tabbing {
7791 _ if prefs_style => window.setTabbingMode(M::Disallowed),
7792 T::Disallowed => window.setTabbingMode(M::Disallowed),
7793 T::Automatic => unsafe {
7797 window.setTabbingIdentifier(&NSString::from_str("day.normal"));
7798 },
7799 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7800 T::Preferred(g) => {
7801 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7802 window.setTabbingMode(M::Preferred);
7803 }
7804 }
7805 if group.is_some() {
7806 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7809 }
7810 let delegate = DayWinDelegate::new(mtm, node, group);
7811 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7812 let content = view_of(&DayFlipped::new(mtm));
7813 window.setContentView(Some(&content));
7814 window_chrome::apply(&window, &content, options);
7815 window.setAutorecalculatesKeyViewLoop(true);
7824 (window, delegate, content)
7825 }
7826}
7827
7828impl Default for AppKit {
7829 fn default() -> Self {
7830 Self::new()
7831 }
7832}
7833
7834fn view_of<T: AsRef<NSView>>(x: &Retained<T>) -> Handle {
7835 Retained::from((**x).as_ref())
7836}
7837
7838fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7839 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7840}
7841
7842fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7845 use objc2_app_kit::*;
7846 unsafe {
7847 Some(match f {
7848 Font::LargeTitle => NSFontTextStyleLargeTitle,
7849 Font::Title => NSFontTextStyleTitle1,
7850 Font::Title2 => NSFontTextStyleTitle2,
7851 Font::Title3 => NSFontTextStyleTitle3,
7852 Font::Headline => NSFontTextStyleHeadline,
7853 Font::Subheadline => NSFontTextStyleSubheadline,
7854 Font::Body => NSFontTextStyleBody,
7855 Font::Callout => NSFontTextStyleCallout,
7856 Font::Footnote => NSFontTextStyleFootnote,
7857 Font::Caption => NSFontTextStyleCaption1,
7858 Font::Caption2 => NSFontTextStyleCaption2,
7859 Font::System(_) | Font::Custom(..) => return None,
7860 })
7861 }
7862}
7863
7864fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7865 use day_spec::FontWeight as W;
7866 use objc2_app_kit::*;
7867 unsafe {
7868 match w {
7869 W::UltraLight => NSFontWeightUltraLight,
7870 W::Thin => NSFontWeightThin,
7871 W::Light => NSFontWeightLight,
7872 W::Regular => NSFontWeightRegular,
7873 W::Medium => NSFontWeightMedium,
7874 W::Semibold => NSFontWeightSemibold,
7875 W::Bold => NSFontWeightBold,
7876 W::Heavy => NSFontWeightHeavy,
7877 W::Black => NSFontWeightBlack,
7878 }
7879 }
7880}
7881
7882fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7885 use day_spec::FontWeight as W;
7886 match w {
7887 W::UltraLight => 2,
7888 W::Thin => 3,
7889 W::Light => 4,
7890 W::Regular => 5,
7891 W::Medium => 6,
7892 W::Semibold => 8,
7893 W::Bold => 9,
7894 W::Heavy => 10,
7895 W::Black => 12,
7896 }
7897}
7898
7899fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7904 use objc2_app_kit::*;
7905 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7906 let prepared = OFFSCREEN_FONTS.with(|t| {
7909 t.borrow()
7910 .iter()
7911 .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
7912 .map(|(_, f)| f.clone())
7913 });
7914 if let Some(f) = prepared {
7915 return f;
7916 }
7917 let Some(mtm) = objc2::MainThreadMarker::new() else {
7918 return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7922 };
7923 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7924 let mut traits = NSFontTraitMask::empty();
7925 if weight >= day_spec::FontWeight::Semibold {
7926 traits |= NSFontTraitMask::BoldFontMask;
7927 }
7928 if font.italic {
7929 traits |= NSFontTraitMask::ItalicFontMask;
7930 }
7931 let Some(family) = font.family.as_deref() else {
7932 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7933 return if font.italic {
7934 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7935 } else {
7936 base
7937 };
7938 };
7939 let ns_family = NSString::from_str(family);
7940 if let Some(f) = unsafe {
7941 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7942 } {
7943 return f;
7944 }
7945 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7946 return if traits.is_empty() {
7947 f
7948 } else {
7949 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7950 };
7951 }
7952 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7953 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7954}
7955
7956fn canvas_text_attrs(
7959 font: &NSFont,
7960 color: day_spec::Color,
7961) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7962 let col = nscolor(color);
7963 let keys: [&NSString; 2] = unsafe {
7965 [
7966 objc2_app_kit::NSFontAttributeName,
7967 objc2_app_kit::NSForegroundColorAttributeName,
7968 ]
7969 };
7970 let objs: [&objc2::runtime::AnyObject; 2] = [
7971 font as &objc2::runtime::AnyObject,
7972 col.as_ref() as &objc2::runtime::AnyObject,
7973 ];
7974 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7975}
7976
7977fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7980 use objc2_app_kit::*;
7981 let base: Retained<NSFont> = match spec.style {
7982 Font::System(pt) => {
7983 let w = spec
7984 .weight
7985 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
7986 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7987 }
7988 Font::Custom(name, pt) => {
7992 if let Some(f) = unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7993 if spec
7994 .weight
7995 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7996 {
7997 let mtm =
7998 objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7999 unsafe {
8000 NSFontManager::sharedFontManager(mtm)
8001 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
8002 }
8003 } else {
8004 f
8005 }
8006 } else {
8007 log::warn!(
8008 "unknown font family {name:?} — falling back to the system font \
8009 (is the file in the project's fonts/ directory?)"
8010 );
8011 let w = spec
8012 .weight
8013 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8014 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
8015 }
8016 }
8017 style => {
8018 let ts = ns_text_style(style).expect("semantic style");
8021 let opts = objc2_foundation::NSDictionary::new();
8022 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
8023 match spec.weight {
8024 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
8026 None => f,
8027 }
8028 }
8029 };
8030 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
8035 let w = spec
8036 .weight
8037 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8038 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
8039 } else {
8040 base
8041 };
8042 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
8046 let w = spec
8047 .weight
8048 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8049 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
8050 } else {
8051 base
8052 };
8053 #[expect(
8057 clippy::float_cmp,
8058 reason = "1.0 is the exact unscaled default of `FontSpec::scale`"
8059 )]
8060 let base = if spec.scale == 1.0 {
8061 base
8062 } else {
8063 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8064 let pts = spec.resolved_points(base.pointSize());
8065 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
8066 };
8067 if spec.italic {
8068 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8069 unsafe {
8070 NSFontManager::sharedFontManager(mtm)
8071 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
8072 }
8073 } else {
8074 base
8075 }
8076}
8077
8078fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
8088 use objc2_foundation::{NSMutableAttributedString, NSRange};
8089 unsafe {
8090 let cur = tf.attributedStringValue();
8091 let m = NSMutableAttributedString::initWithAttributedString(
8092 NSMutableAttributedString::alloc(),
8093 &cur,
8094 );
8095 let style = objc2_app_kit::NSMutableParagraphStyle::new();
8096 style.setAlignment(align);
8097 style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
8100 m.addAttribute_value_range(
8101 objc2_app_kit::NSParagraphStyleAttributeName,
8102 &style,
8103 NSRange::new(0, cur.length()),
8104 );
8105 tf.setAttributedStringValue(&m);
8106 }
8107}
8108
8109fn attributed_label(
8110 text: &str,
8111 base_font: &NSFont,
8112 color: Option<day_spec::Color>,
8113 role: day_spec::props::TextRole,
8114 runs: &[day_spec::TextRun],
8115) -> Retained<objc2_foundation::NSAttributedString> {
8116 use objc2_foundation::{NSMutableAttributedString, NSRange};
8117 let ns = NSString::from_str(text);
8118 let s = unsafe {
8119 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
8120 };
8121 let whole = NSRange::new(0, ns.length());
8122 unsafe {
8123 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
8124 let fg = color.map_or_else(
8132 || match role {
8133 day_spec::props::TextRole::Secondary => {
8134 objc2_app_kit::NSColor::secondaryLabelColor()
8135 }
8136 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
8137 },
8138 nscolor,
8139 );
8140 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
8141 }
8142 for r in runs {
8143 let Some(range) = utf16_range(text, &r.range) else {
8144 continue;
8145 };
8146 unsafe {
8147 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
8148 if let Some(c) = r.color {
8149 s.addAttribute_value_range(
8150 objc2_app_kit::NSForegroundColorAttributeName,
8151 &nscolor(c),
8152 range,
8153 );
8154 }
8155 if let Some(c) = r.background {
8156 s.addAttribute_value_range(
8157 objc2_app_kit::NSBackgroundColorAttributeName,
8158 &nscolor(c),
8159 range,
8160 );
8161 }
8162 if r.underline.is_on() {
8163 let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
8164 s.addAttribute_value_range(
8165 objc2_app_kit::NSUnderlineStyleAttributeName,
8166 &style,
8167 range,
8168 );
8169 }
8170 if r.strikethrough {
8171 let one = objc2_foundation::NSNumber::new_i64(1);
8172 s.addAttribute_value_range(
8173 objc2_app_kit::NSStrikethroughStyleAttributeName,
8174 &one,
8175 range,
8176 );
8177 }
8178 if let Some(url) = r.link.as_deref() {
8179 let value = NSString::from_str(url);
8182 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
8183 }
8184 }
8185 }
8186 s.into_super()
8187}
8188
8189fn ns_underline(u: day_spec::Underline) -> i64 {
8193 use day_spec::Underline as U;
8194 match u {
8195 U::None => 0,
8196 U::Single => 0x01,
8197 U::Double => 0x09,
8198 U::Dotted => 0x01 | 0x0100,
8199 U::Wavy => 0x01 | 0x0400,
8200 }
8201}
8202
8203fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
8205 let start = text.get(..r.start)?.encode_utf16().count();
8206 let len = text.get(r.clone())?.encode_utf16().count();
8207 Some(objc2_foundation::NSRange::new(start, len))
8208}
8209
8210fn register_bundled_fonts() {
8215 #[link(name = "CoreText", kind = "framework")]
8217 unsafe extern "C" {
8218 fn CTFontManagerRegisterFontsForURL(
8219 font_url: *const std::ffi::c_void,
8220 scope: u32, error: *mut *const std::ffi::c_void,
8222 ) -> bool;
8223 }
8224 for path in day_spec::fonts::bundled_fonts() {
8225 let url = unsafe {
8226 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
8227 };
8228 let ok = unsafe {
8229 CTFontManagerRegisterFontsForURL(
8230 Retained::as_ptr(&url).cast::<std::ffi::c_void>(),
8231 1,
8232 std::ptr::null_mut(),
8233 )
8234 };
8235 if !ok {
8236 log::warn!("could not register bundled font {}", path.display());
8237 }
8238 }
8239}
8240
8241fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
8244 match a {
8245 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
8246 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
8247 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
8248 }
8249}
8250
8251fn configure_label_cell(tf: &NSTextField) {
8252 if let Some(cell) = unsafe { tf.cell() } {
8253 unsafe {
8254 cell.setWraps(true);
8255 cell.setUsesSingleLineMode(false);
8256 cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
8257 }
8258 }
8259}
8260
8261fn content_of(parent: &Handle) -> Retained<NSView> {
8263 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
8264 && let Some(doc) = unsafe { sv.documentView() }
8265 {
8266 return doc;
8267 }
8268 parent.clone()
8269}
8270
8271fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
8277 let Some(a) = anim else {
8278 body();
8279 return;
8280 };
8281 let (dur, timing) = appkit_timing(a);
8282 unsafe {
8283 NSAnimationContext::beginGrouping();
8284 let ctx = NSAnimationContext::currentContext();
8285 ctx.setDuration(dur);
8286 ctx.setTimingFunction(Some(&timing));
8287 ctx.setAllowsImplicitAnimation(true);
8288 body();
8289 NSAnimationContext::endGrouping();
8290 }
8291}
8292
8293fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
8296 unsafe {
8297 let named = |n| {
8298 (
8299 a.duration_secs().max(0.01),
8300 CAMediaTimingFunction::functionWithName(n),
8301 )
8302 };
8303 match a.curve {
8304 Curve::Linear => named(kCAMediaTimingFunctionLinear),
8305 Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
8306 Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
8307 Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
8308 Curve::Spring { damping, .. } => {
8309 let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
8311 (
8312 a.duration_secs().max(0.05),
8313 CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
8314 )
8315 }
8316 }
8317 }
8318}
8319
8320fn warn_missing_renderer(kind: PieceKind) {
8325 day_spec::placeholder::report(kind, "appkit");
8326}
8327
8328pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
8332 view_of(&unsafe {
8333 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
8334 })
8335}
8336
8337impl Toolkit for AppKit {
8338 fn ui_idle(&mut self) -> bool {
8341 toolbar::chrome_settled()
8342 }
8343
8344 type Handle = Handle;
8345
8346 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
8347 use day_spec::SystemColor;
8348 let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
8349 let block = block2::StackBlock::new(|| {
8350 let color = match role {
8351 SystemColor::Accent => NSColor::controlAccentColor(),
8352 SystemColor::Text => NSColor::labelColor(),
8353 SystemColor::SecondaryText => NSColor::secondaryLabelColor(),
8354 SystemColor::Background => NSColor::windowBackgroundColor(),
8355 SystemColor::Surface => NSColor::controlBackgroundColor(),
8356 };
8357 if let Some(rgb) =
8358 color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())
8359 {
8360 result.set(day_spec::Color::rgba(
8361 rgb.redComponent(),
8362 rgb.greenComponent(),
8363 rgb.blueComponent(),
8364 rgb.alphaComponent(),
8365 ));
8366 }
8367 });
8368 NSApplication::sharedApplication(self.mtm())
8369 .effectiveAppearance()
8370 .performAsCurrentDrawingAppearance(&block);
8371 result.get()
8372 }
8373
8374 fn dark_mode(&mut self) -> bool {
8375 let app = NSApplication::sharedApplication(self.mtm());
8378 app.effectiveAppearance()
8379 .name()
8380 .to_string()
8381 .contains("Dark")
8382 }
8383
8384 fn reduce_motion(&mut self) -> bool {
8387 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
8388 }
8389
8390 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
8394 use day_spec::AppBadge;
8395 let label = match badge {
8396 AppBadge::None | AppBadge::Count(0) => None,
8398 AppBadge::Count(n) => Some(n.to_string()),
8399 AppBadge::Text(t) if t.is_empty() => None,
8400 AppBadge::Text(t) => Some(t.clone()),
8401 AppBadge::Dot => Some("\u{2022}".to_string()),
8403 };
8404 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
8405 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
8406 unsafe { tile.setBadgeLabel(ns.as_deref()) };
8407 tile.display();
8408 }
8409
8410 fn set_appearance(&mut self, dark: Option<bool>) {
8411 let app = NSApplication::sharedApplication(self.mtm());
8412 let appearance = dark.and_then(|d| {
8413 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
8414 if d {
8415 objc2_app_kit::NSAppearanceNameDarkAqua
8416 } else {
8417 objc2_app_kit::NSAppearanceNameAqua
8418 }
8419 })
8420 });
8421 unsafe { app.setAppearance(appearance.as_deref()) };
8423 }
8424
8425 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
8426 controls::refresh_gesture::attach(handle, host);
8427 }
8428
8429 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
8430 unsafe {
8431 handle.setHidden(!visible);
8432 }
8433 }
8434
8435 #[expect(
8436 clippy::match_same_arms,
8437 reason = "one arm per capability, each documented with the AppKit mechanism behind it"
8438 )]
8439 fn capability(&self, cap: Cap) -> Support {
8440 match cap {
8441 Cap::ShareActions => Support::Native,
8443 Cap::SearchField => Support::Native,
8444 Cap::ComboBox => Support::Native,
8445 Cap::Stepper => Support::Native,
8446 Cap::DateTimePicker => Support::Native,
8447 Cap::ColorPicker => Support::Native,
8448 Cap::PullRefresh => Support::Emulated,
8449 Cap::Pager => Support::Emulated,
8450 Cap::PullRefreshGesture => Support::Emulated,
8451 Cap::Cursor => Support::Native,
8455 Cap::FontList => Support::Native,
8457 Cap::ListItem => Support::Native,
8459 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
8463 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
8466 Cap::Announce => Support::Native,
8469 Cap::ReduceMotion => Support::Native,
8472 Cap::Snapshot
8473 | Cap::NativeSymbols
8474 | Cap::NavTabs
8483 | Cap::NavSplit
8484 | Cap::NavRepresent
8488 | Cap::NavContentList
8491 | Cap::Dialogs
8492 | Cap::FileDialogs
8493 | Cap::FolderDialog
8495 | Cap::Animation
8496 | Cap::TextEditable
8498 | Cap::TextSelectable
8499 | Cap::TextSpellCheck
8500 | Cap::NavReorder | Cap::ListReorder
8503 | Cap::ListRecycling
8506 | Cap::ListSwipeActions
8509 | Cap::ListSections
8511 | Cap::Tree
8514 | Cap::TreeSections
8515 | Cap::TreeMove
8516 | Cap::MultiWindow
8518 | Cap::WindowStates
8521 | Cap::WindowFullscreen
8522 | Cap::ContentProtection
8524 | Cap::WindowTabbing
8527 | Cap::DockMenu
8529 | Cap::FramelessWindow
8533 | Cap::OverlayTitleBar
8534 | Cap::TransparentWindow
8535 | Cap::WindowMaterial
8536 | Cap::DragRegion
8538 | Cap::StatusItem
8541 | Cap::AppProgress
8542 | Cap::DockVisibility
8543 | Cap::WindowGeometry
8546 | Cap::WindowPosition
8547 | Cap::WindowLevel
8548 | Cap::WindowAppearance
8549 | Cap::RequestAttention
8550 | Cap::Monitors
8551 | Cap::DynamicShortcuts
8553 | Cap::Toolbar
8555 | Cap::ToolbarSearch
8557 | Cap::AppMenu
8558 | Cap::AppBadgeCount
8561 | Cap::AppBadgeText
8562 | Cap::UndoBridge
8565 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
8566 | Cap::AppBadgeDot
8567 | Cap::Appearance
8568 | Cap::BaselineAlignment
8570 | Cap::Inspector
8573 | Cap::Split
8575 | Cap::TextRuns
8576 | Cap::TextLinks => Support::Native,
8577 Cap::Cover => Support::Emulated,
8580 Cap::CoverSheet => Support::Native,
8582 _ => Support::Unsupported,
8583 }
8584 }
8585
8586 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
8587 let mtm = self.mtm;
8588 match Builtin::from_key(kind) {
8589 Some(Builtin::Container) => {
8590 let v = DayFlipped::new(mtm);
8591 if let Some(p) = props.downcast_ref::<ContainerProps>() {
8592 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
8593 v.set_section_card(p.corner_radius);
8594 } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
8595 v.set_surface(p.background, p.corner_radius, p.clips);
8596 }
8597 }
8598 view_of(&v)
8599 }
8600 Some(Builtin::Scroll) => {
8601 let horizontal = props
8602 .downcast_ref::<day_spec::props::ScrollProps>()
8603 .is_some_and(|p| p.horizontal);
8604 let sv = unsafe { NSScrollView::new(mtm) };
8605 unsafe {
8606 sv.setHasVerticalScroller(!horizontal);
8607 sv.setHasHorizontalScroller(horizontal);
8608 sv.setDrawsBackground(false);
8609 sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8615 }
8616 let doc = DayFlipped::new(mtm);
8617 unsafe { sv.setDocumentView(Some(doc.as_ref())) };
8618 view_of(&sv)
8619 }
8620 Some(Builtin::Label) => {
8621 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
8626 return placeholder_view(mtm, kind);
8627 };
8628 let tf = DayLabel::new(mtm, id, &p.text);
8629 configure_label_cell(&tf);
8630 if !p.wraps || p.max_lines > 0 {
8631 unsafe {
8632 tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8633 if !p.wraps || p.max_lines == 1 {
8634 tf.setUsesSingleLineMode(true);
8635 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8636 }
8637 }
8638 }
8639 unsafe { tf.setFont(Some(&nsfont(p.font))) };
8640 match (p.color, p.role) {
8644 (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8645 (None, day_spec::props::TextRole::Secondary) => unsafe {
8646 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
8647 },
8648 (None, day_spec::props::TextRole::Primary) => {}
8649 }
8650 if !p.runs.is_empty() {
8651 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8652 unsafe { tf.setAttributedStringValue(&s) };
8653 }
8654 tf.ivars().has_runs.set(!p.runs.is_empty());
8655 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8656 if p.align != day_spec::props::TextAlign::Leading {
8661 unsafe { tf.setAlignment(nstextalign(p.align)) };
8662 if !p.runs.is_empty() {
8663 set_paragraph_alignment(&tf, nstextalign(p.align));
8664 }
8665 }
8666 view_of(&Retained::into_super(tf))
8667 }
8668 Some(Builtin::Button) => {
8669 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8670 return placeholder_view(mtm, kind);
8671 };
8672 let target = DayTarget::new(mtm, id);
8673 let btn = unsafe {
8674 NSButton::buttonWithTitle_target_action(
8675 &NSString::from_str(&p.title),
8676 Some(&*target),
8677 Some(sel!(action:)),
8678 mtm,
8679 )
8680 };
8681 apply_button_style(&btn, p.style);
8682 if p.icon.is_some() {
8683 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8684 }
8685 unsafe { btn.setEnabled(p.enabled) };
8686 set_button_selected(&btn, p.selected);
8687 let view = view_of(&btn);
8688 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8689 view
8690 }
8691 Some(Builtin::Toggle) => {
8692 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8693 return placeholder_view(mtm, kind);
8694 };
8695 let target = DayTarget::new(mtm, id);
8696 let sw = unsafe { NSSwitch::new(mtm) };
8697 unsafe {
8698 sw.setState(isize::from(p.on));
8699 sw.setEnabled(p.enabled);
8700 sw.setTarget(Some(&*target));
8701 sw.setAction(Some(sel!(action:)));
8702 }
8703 let view = view_of(&sw);
8704 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8705 view
8706 }
8707 Some(Builtin::Slider) => {
8708 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8709 return placeholder_view(mtm, kind);
8710 };
8711 let target = DayTarget::new(mtm, id);
8712 let sl = unsafe {
8713 NSSlider::sliderWithValue_minValue_maxValue_target_action(
8714 p.value,
8715 p.min,
8716 p.max,
8717 Some(&*target),
8718 Some(sel!(action:)),
8719 mtm,
8720 )
8721 };
8722 unsafe { sl.setContinuous(true) };
8723 let view = view_of(&sl);
8724 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8725 view
8726 }
8727 Some(Builtin::Picker) => picker::realize_any(self, props, id),
8728 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8729 Some(Builtin::TextField) => {
8730 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8731 return placeholder_view(mtm, kind);
8732 };
8733 let tf = new_text_field(mtm, id, false);
8734 unsafe {
8735 tf.setStringValue(&NSString::from_str(&p.text));
8736 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8737 }
8738 view_of(&tf)
8739 }
8740 Some(Builtin::Divider) => {
8741 let b = unsafe { NSBox::new(mtm) };
8742 unsafe { b.setBoxType(NSBoxType::Separator) };
8743 view_of(&b)
8744 }
8745 Some(Builtin::Progress) => {
8746 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8747 return placeholder_view(mtm, kind);
8748 };
8749 if p.value.is_none() {
8750 return crate::controls::spinner::make(self, p, id);
8751 }
8752 let pi = unsafe { NSProgressIndicator::new(mtm) };
8753 unsafe {
8754 if let Some(v) = p.value {
8755 pi.setStyle(NSProgressIndicatorStyle::Bar);
8756 pi.setIndeterminate(false);
8757 pi.setMinValue(0.0);
8758 pi.setMaxValue(1.0);
8759 pi.setDoubleValue(v);
8760 } else {
8761 pi.setStyle(NSProgressIndicatorStyle::Spinning);
8762 pi.setIndeterminate(true);
8763 pi.startAnimation(None);
8764 }
8765 }
8766 view_of(&pi)
8767 }
8768 Some(Builtin::Canvas) => {
8769 let canvas = DayCanvas::new(mtm);
8770 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8771 view_of(&canvas)
8772 }
8773 Some(Builtin::Inspector) => {
8774 let (visible, width, leading) =
8775 props
8776 .downcast_ref::<InspectorProps>()
8777 .map_or((false, 280.0, false), |p| {
8778 (
8779 p.visible,
8780 p.width,
8781 p.edge == day_spec::props::PaneEdge::Leading,
8782 )
8783 });
8784 let content_wrap = view_of(&DayFlipped::new(mtm));
8785 let panel_flipped = DayFlipped::new(mtm);
8786 panel_flipped.set_pane_backdrop();
8790 let panel_wrap = view_of(&panel_flipped);
8791 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8792 let _ = unsafe { split_vc.view() };
8795 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8796 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8797 unsafe {
8798 content_vc.setView(&content_wrap);
8799 panel_vc.setView(&panel_wrap);
8800 }
8801 let content_item = unsafe {
8802 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8803 };
8804 let panel_item = unsafe {
8809 if leading {
8810 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8811 } else {
8812 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8813 }
8814 };
8815 unsafe {
8816 panel_item.setCanCollapse(false);
8820 panel_item.setCollapsed(!visible);
8821 panel_item.setMinimumThickness(width);
8822 panel_item.setMaximumThickness(width);
8823 panel_item.setAllowsFullHeightLayout(true);
8824 if leading {
8825 split_vc.addSplitViewItem(&panel_item);
8826 split_vc.addSplitViewItem(&content_item);
8827 } else {
8828 split_vc.addSplitViewItem(&content_item);
8829 split_vc.addSplitViewItem(&panel_item);
8830 }
8831 }
8832 let split = unsafe { split_vc.splitView() };
8833 unsafe {
8834 split.setVertical(true);
8835 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8836 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8840 }
8841 let view = view_of(&split);
8842 INSPECTOR_STATE.with(|m| {
8843 m.borrow_mut().insert(
8844 ptr_of(&view),
8845 InspectorState {
8846 content_wrap,
8847 panel_wrap,
8848 split_vc,
8849 panel_item,
8850 },
8851 )
8852 });
8853 view
8854 }
8855 Some(Builtin::InspectorPane) => {
8856 let pane = view_of(&DayNavPage::new(mtm, id));
8860 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8861 let panel = props
8862 .downcast_ref::<InspectorPaneProps>()
8863 .is_some_and(|p| p.panel);
8864 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8865 pane
8866 }
8867 Some(Builtin::Split) => {
8868 let (axis, fraction, min_pane) = props
8869 .downcast_ref::<SplitProps>()
8870 .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
8871 (p.axis, p.fraction, p.min_pane)
8872 });
8873 let wrap = view_of(&DayFlipped::new(mtm));
8874 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8875 let first_wrap = view_of(&DayFlipped::new(mtm));
8876 let second_wrap = view_of(&DayFlipped::new(mtm));
8877 unsafe {
8878 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8880 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8881 split.addArrangedSubview(&first_wrap);
8882 split.addArrangedSubview(&second_wrap);
8883 split.setFrame(wrap.bounds());
8884 split.setAutoresizingMask(
8885 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8886 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8887 );
8888 wrap.addSubview(&split);
8889 }
8890 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8891 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8892 SPLIT_STATE.with(|m| {
8893 m.borrow_mut().insert(
8894 ptr_of(&wrap),
8895 SplitState {
8896 split,
8897 first_wrap,
8898 second_wrap,
8899 delegate,
8900 },
8901 )
8902 });
8903 wrap
8904 }
8905 Some(Builtin::SplitPane) => {
8906 let pane = view_of(&DayNavPage::new(mtm, id));
8909 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8910 let second = props
8911 .downcast_ref::<SplitPaneProps>()
8912 .is_some_and(|p| p.second);
8913 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8914 pane
8915 }
8916 Some(Builtin::Nav) => {
8917 let presentation = props
8918 .downcast_ref::<NavProps>()
8919 .map_or(NavPresentation::Split, |p| p.presentation);
8920 let is_split = presentation.is_split();
8921 let sidebar_wrap = view_of(&DayFlipped::new(mtm));
8930 let detail_wrap = view_of(&DayFlipped::new(mtm));
8931 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8932 let _ = unsafe { split_vc.view() };
8938 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8941 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8942 unsafe {
8943 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8944 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8945 }
8946 let sidebar_item = unsafe {
8947 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8948 };
8949 let detail_item = unsafe {
8950 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8951 };
8952 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8958 let list_visible = props
8964 .downcast_ref::<NavProps>()
8965 .is_none_or(|p| p.list_visible);
8966 let (list_wrap, list_item) = match list_width {
8967 Some(w) => {
8968 let wrap = view_of(&DayFlipped::new(mtm));
8969 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8970 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8971 let item = unsafe {
8972 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8973 };
8974 unsafe {
8975 item.setCanCollapse(true);
8976 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8977 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8978 item.setCollapsed(!list_visible);
8979 }
8980 (Some(wrap), Some(item))
8981 }
8982 None => (None, None),
8983 };
8984 unsafe {
8985 sidebar_item.setCanCollapse(is_split);
8988 sidebar_item.setCollapsed(!is_split);
8989 if is_split {
8990 sidebar_item.setAllowsFullHeightLayout(true);
8994 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8995 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8996 } else {
8997 sidebar_item.setMinimumThickness(0.0);
8998 sidebar_item.setMaximumThickness(0.0);
8999 }
9000 split_vc.addSplitViewItem(&sidebar_item);
9001 if let Some(item) = list_item.as_ref() {
9002 split_vc.addSplitViewItem(item);
9003 }
9004 split_vc.addSplitViewItem(&detail_item);
9005 }
9006 let split = unsafe { split_vc.splitView() };
9007 unsafe {
9014 let after = split.nextResponder();
9015 split.setNextResponder(Some(&split_vc));
9016 let own_view = split_vc.view();
9026 let vc_resp: *const objc2_app_kit::NSResponder = {
9027 let r: &objc2_app_kit::NSResponder = &split_vc;
9028 r
9029 };
9030 let view_resp: *const objc2_app_kit::NSResponder = {
9031 let r: &objc2_app_kit::NSResponder = &own_view;
9032 r
9033 };
9034 let upstream = after.filter(|a| {
9035 let p: *const objc2_app_kit::NSResponder = &raw const **a;
9036 p != vc_resp && p != view_resp
9037 });
9038 split_vc.setNextResponder(upstream.as_deref());
9039 }
9040 unsafe {
9041 split.setVertical(true);
9042 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
9043 split.setTranslatesAutoresizingMaskIntoConstraints(true);
9051 }
9052 let root_title = props
9053 .downcast_ref::<NavProps>()
9054 .map_or_default(|p| p.title.clone());
9055 let header = if presentation == NavPresentation::Stack {
9058 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
9059 } else {
9060 None
9061 };
9062 let tabs = (presentation == NavPresentation::Tabs).then(|| {
9065 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
9066 let documents = props
9067 .downcast_ref::<NavProps>()
9068 .is_some_and(|p| p.documents.is_some());
9069 let (inset, inset_top) = if documents {
9075 (0.0, 0.0)
9076 } else {
9077 (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
9078 };
9079 let b = detail_wrap.bounds();
9080 let frame = NSRect::new(
9081 NSPoint::new(inset, inset_top),
9082 NSSize::new(
9083 (b.size.width - 2.0 * inset).max(0.0),
9084 (b.size.height - inset_top - inset).max(0.0),
9085 ),
9086 );
9087 unsafe {
9088 tv.setTabViewType(if documents {
9089 objc2_app_kit::NSTabViewType::NoTabsNoBorder
9090 } else {
9091 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
9092 });
9093 tv.setFrame(frame);
9094 tv.setAutoresizingMask(
9095 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9096 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9097 );
9098 detail_wrap.addSubview(&tv);
9099 }
9100 TabHost {
9101 view: tv,
9102 target: None,
9103 }
9104 });
9105 let view = view_of(&split);
9106 NAV_STATE.with(|m| {
9107 m.borrow_mut().insert(
9108 ptr_of(&view),
9109 NavState {
9110 sidebar_wrap,
9111 detail_wrap,
9112 split_vc,
9113 sidebar_item,
9114 list_wrap,
9115 list_item,
9116 pages: Vec::new(),
9117 list_page: None,
9118 sidebar_page: None,
9119 list_width,
9120 list_visible,
9121 list_positioned: false,
9122 positioned: false,
9123 presentation,
9124 selected: 0,
9125 tabs,
9126 header,
9127 root_title,
9128 node: id,
9129 title_strip: 0.0,
9130 },
9131 )
9132 });
9133 view
9134 }
9135 Some(Builtin::NavPage) => {
9136 let page = view_of(&DayNavPage::new(mtm, id));
9137 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
9138 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
9139 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
9140 }
9141 page
9142 }
9143 Some(Builtin::Cover) => {
9147 let page = DayNavPage::new(mtm, id);
9148 let cover_props = props.downcast_ref::<CoverProps>();
9149 page.ivars()
9152 .sheet
9153 .set(cover_props.is_some_and(|p| p.sheet || p.half));
9154 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
9155 page.ivars().large.set(cover_props.is_some_and(|p| p.large));
9156 unsafe { page.setHidden(true) };
9157 view_of(&page)
9158 }
9159 Some(Builtin::NavMenu) => {
9160 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
9161 return placeholder_view(mtm, kind);
9162 };
9163 let data = DayNavMenuData::new(
9164 mtm,
9165 id,
9166 &p.items,
9167 &p.icons,
9168 &p.badges,
9169 &p.badge_icons,
9170 &p.badge_tints,
9171 &p.sections,
9172 &p.tints,
9173 &p.menus,
9174 );
9175 (*data.ivars().movable.borrow_mut()).clone_from(&p.movable);
9176 data.ivars().regroup.set(p.regroup);
9177 (*data.ivars().sorted.borrow_mut()).clone_from(&p.sorted);
9178 let outline: Retained<objc2_app_kit::NSOutlineView> = {
9180 let o: Retained<DayNavOutlineView> =
9181 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
9182 NAV_OUTLINE_MENUS
9183 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
9184 unsafe { msg_send![&*o, self] }
9185 };
9186 let col = unsafe {
9187 objc2_app_kit::NSTableColumn::initWithIdentifier(
9188 objc2_app_kit::NSTableColumn::alloc(mtm),
9189 &NSString::from_str("item"),
9190 )
9191 };
9192 unsafe {
9193 outline.addTableColumn(&col);
9194 outline.setOutlineTableColumn(Some(&col));
9195 outline.setHeaderView(None);
9196 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9209 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
9214 outline.setFloatsGroupRows(true);
9217 outline.setIndentationPerLevel(0.0);
9218 outline.registerForDraggedTypes(
9221 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9222 DAY_NAV_PASTEBOARD_TYPE,
9223 )]),
9224 );
9225 outline.setDraggingSourceOperationMask_forLocal(
9226 objc2_app_kit::NSDragOperation::Move,
9227 true,
9228 );
9229 outline.setDraggingSourceOperationMask_forLocal(
9230 objc2_app_kit::NSDragOperation::None,
9231 false,
9232 );
9233 outline.setDraggingDestinationFeedbackStyle(
9234 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9235 );
9236 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9237 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9238 outline.reloadData();
9239 }
9240 let scroll = unsafe { NSScrollView::new(mtm) };
9241 unsafe {
9242 scroll.setDrawsBackground(false);
9243 scroll.setHasVerticalScroller(true);
9244 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9248 scroll.setHasHorizontalScroller(false);
9250 outline.setAutoresizingMask(
9251 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9252 );
9253 outline.setColumnAutoresizingStyle(
9254 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9255 );
9256 scroll.setDocumentView(Some(&outline));
9257 }
9258 let view = view_of(&scroll);
9259 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
9262 data.ivars().suppress.set(true);
9263 unsafe {
9264 outline.selectRowIndexes_byExtendingSelection(
9265 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9266 false,
9267 );
9268 };
9269 data.ivars().suppress.set(false);
9270 }
9271 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9272 view
9273 }
9274 Some(Builtin::List) => {
9275 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
9276 return placeholder_view(mtm, kind);
9277 };
9278 let table: Retained<DayListView> =
9280 unsafe { msg_send![DayListView::alloc(mtm), init] };
9281 let table = Retained::into_super(table);
9282 if p.inset_grouped {
9283 unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
9286 }
9287 let col = unsafe {
9288 NSTableColumn::initWithIdentifier(
9289 NSTableColumn::alloc(mtm),
9290 &NSString::from_str("day.list.col"),
9291 )
9292 };
9293 let data = DayListData::new(
9294 mtm,
9295 id,
9296 p.selectable,
9297 p.multi_select,
9298 p.row_height == RowHeight::Automatic,
9299 p.sections,
9300 );
9301 unsafe {
9302 if p.multi_select {
9303 table.setAllowsMultipleSelection(true);
9304 }
9305 table.addTableColumn(&col);
9306 table.setHeaderView(None);
9307 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
9316 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
9320 if p.separators == Some(true) {
9324 table.setGridStyleMask(
9325 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
9326 );
9327 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
9328 }
9329 table.setColumnAutoresizingStyle(
9330 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9331 );
9332 table.setFloatsGroupRows(p.sections);
9335 match p.row_height {
9336 RowHeight::Uniform(h) => table.setRowHeight(h),
9337 RowHeight::Automatic => table.setRowHeight(44.0),
9338 }
9339 if !p.selectable {
9340 table.setSelectionHighlightStyle(
9341 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9342 );
9343 }
9344 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9348 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9349 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9350 table.setTarget(Some(&*data));
9351 if p.activatable {
9352 table.setDoubleAction(Some(sel!(doubleClickRow:)));
9353 }
9354 if p.reorderable {
9355 table.registerForDraggedTypes(
9359 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9360 DAY_ROW_PASTEBOARD_TYPE,
9361 )]),
9362 );
9363 table.setDraggingSourceOperationMask_forLocal(
9364 objc2_app_kit::NSDragOperation::Move,
9365 true,
9366 );
9367 table.setDraggingSourceOperationMask_forLocal(
9368 objc2_app_kit::NSDragOperation::None,
9369 false,
9370 );
9371 table.setDraggingDestinationFeedbackStyle(
9372 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9373 );
9374 }
9375 }
9376 let scroll = unsafe { NSScrollView::new(mtm) };
9377 unsafe {
9378 scroll.setDrawsBackground(false);
9379 scroll.setHasVerticalScroller(true);
9380 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9384 scroll.setDocumentView(Some(&table));
9385 let clip = scroll.contentView();
9386 clip.setPostsBoundsChangedNotifications(true);
9387 objc2_foundation::NSNotificationCenter::defaultCenter()
9388 .addObserver_selector_name_object(
9389 &data,
9390 sel!(listViewportChanged:),
9391 Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
9392 Some(&clip),
9393 );
9394 }
9395 let view = view_of(&scroll);
9396 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
9397 view
9398 }
9399 Some(Builtin::Tree) => {
9400 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
9401 return placeholder_view(mtm, kind);
9402 };
9403 let outline: Retained<objc2_app_kit::NSOutlineView> = {
9405 let o: Retained<DayOutlineView> =
9406 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
9407 unsafe { msg_send![&*o, self] }
9408 };
9409 let col = unsafe {
9410 NSTableColumn::initWithIdentifier(
9411 NSTableColumn::alloc(mtm),
9412 &NSString::from_str("day.tree.col"),
9413 )
9414 };
9415 let data = DayTreeData::new(mtm, id, p.selectable);
9416 unsafe {
9417 if p.multi_select {
9418 outline.setAllowsMultipleSelection(true);
9419 }
9420 outline.addTableColumn(&col);
9421 outline.setOutlineTableColumn(Some(&col));
9422 outline.setHeaderView(None);
9423 if p.section_headers {
9424 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9427 outline.setFloatsGroupRows(true);
9428 } else {
9429 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
9432 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
9433 }
9434 outline.setColumnAutoresizingStyle(
9435 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9436 );
9437 outline.setAutoresizesOutlineColumn(true);
9438 if let Some(indent) = p.indent {
9439 outline.setIndentationPerLevel(indent);
9440 }
9441 match p.row_height {
9442 RowHeight::Uniform(h) => outline.setRowHeight(h),
9443 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
9444 RowHeight::Automatic => {}
9445 }
9446 if !p.selectable {
9447 outline.setSelectionHighlightStyle(
9448 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9449 );
9450 }
9451 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9452 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9453 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9454 if p.movable {
9455 outline.registerForDraggedTypes(
9460 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9461 DAY_TREE_PASTEBOARD_TYPE,
9462 )]),
9463 );
9464 outline.setDraggingSourceOperationMask_forLocal(
9465 objc2_app_kit::NSDragOperation::Move,
9466 true,
9467 );
9468 outline.setDraggingSourceOperationMask_forLocal(
9469 objc2_app_kit::NSDragOperation::None,
9470 false,
9471 );
9472 }
9473 }
9474 let scroll = unsafe { NSScrollView::new(mtm) };
9475 unsafe {
9476 scroll.setDrawsBackground(false);
9477 scroll.setHasVerticalScroller(true);
9478 scroll.setHasHorizontalScroller(false);
9479 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9480 outline.setAutoresizingMask(
9481 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9482 );
9483 scroll.setDocumentView(Some(&outline));
9484 }
9485 let view = view_of(&scroll);
9486 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9487 view
9488 }
9489 Some(Builtin::Image) => {
9490 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
9491 return placeholder_view(mtm, kind);
9492 };
9493 let iv: Retained<objc2_app_kit::NSImageView> =
9494 if p.content_mode == ContentMode::Fill {
9495 let view: Retained<FillImageView> =
9496 unsafe { msg_send![FillImageView::alloc(mtm), init] };
9497 Retained::from(
9498 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
9499 )
9500 } else {
9501 unsafe { objc2_app_kit::NSImageView::new(mtm) }
9502 };
9503 let scaling = match p.content_mode {
9506 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
9507 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
9508 };
9509 unsafe { iv.setImageScaling(scaling) };
9510 if let Some(img) = appkit_image_for(&p.source) {
9511 if p.tint.is_some() || p.template {
9516 unsafe { img.setTemplate(true) };
9517 }
9518 unsafe { iv.setImage(Some(&img)) };
9519 }
9520 if let Some(t) = p.tint {
9521 unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
9522 }
9523 IMAGE_MODES.with(|t| {
9524 t.insert(
9525 ptr_of(&iv),
9526 ImageMode {
9527 template: p.template,
9528 tinted: p.tint.is_some(),
9529 },
9530 )
9531 });
9532 view_of(&iv)
9533 }
9534 Some(Builtin::ListItem) => {
9535 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
9536 else {
9537 return placeholder_view(mtm, kind);
9538 };
9539 make_list_item(p, mtm)
9540 }
9541 Some(Builtin::ListCell) | None => {
9544 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
9545 return make(self, props, id);
9546 }
9547 warn_missing_renderer(kind);
9551 placeholder_view(mtm, kind)
9552 }
9553 }
9554 }
9555
9556 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
9557 match kind {
9558 kinds::LIST_ITEM => {
9559 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
9560 return;
9561 };
9562 let props = LIST_ITEMS.with(|m| {
9563 use day_spec::props::ListItemPatch as P;
9564 let mut m = m.borrow_mut();
9565 let props = m.get_mut(&ptr_of(h))?;
9566 match p {
9567 P::Title(t) => props.title.clone_from(t),
9568 P::Subtitle(t) => props.subtitle.clone_from(t),
9569 P::Detail(t) => props.detail.clone_from(t),
9570 P::Icon(i) => props.icon.clone_from(i),
9571 P::IconTint(c) => props.icon_tint = *c,
9572 P::Checked(on) => props.checked = *on,
9573 }
9574 Some(props.clone())
9575 });
9576 if let Some(props) = props {
9577 dress_list_item(h, &props, self.mtm());
9578 }
9579 }
9580 kinds::IMAGE => {
9581 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
9582 match p {
9583 day_spec::props::ImagePatch::Tint(c) => {
9584 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9588 let key = ptr_of(&iv);
9589 let template = IMAGE_MODES
9590 .with(|t| {
9591 t.with(key, |m| {
9592 m.tinted = c.is_some();
9593 m.renders_template()
9594 })
9595 })
9596 .unwrap_or(c.is_some());
9597 if let Some(img) = unsafe { iv.image() } {
9598 unsafe { img.setTemplate(template) };
9599 }
9600 unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
9601 }
9602 }
9603 day_spec::props::ImagePatch::Source(source) => {
9607 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9608 if let Some(img) = appkit_image_for(source) {
9614 let template = IMAGE_MODES
9615 .with(|t| t.get(ptr_of(&iv)))
9616 .is_some_and(ImageMode::renders_template);
9617 unsafe {
9618 img.setTemplate(template);
9619 iv.setImage(Some(&img));
9620 }
9621 }
9622 }
9623 }
9624 }
9625 }
9626 }
9627 kinds::CONTAINER => {
9628 if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
9629 patch.downcast_ref::<ContainerPatch>(),
9630 h.clone().downcast::<DayFlipped>(),
9631 ) {
9632 v.set_surface(*c, 0.0, false);
9640 }
9641 }
9642 kinds::LABEL => {
9643 if let (Some(p), Ok(tf)) = (
9644 patch.downcast_ref::<LabelPatch>(),
9645 h.clone().downcast::<NSTextField>(),
9646 ) {
9647 match p {
9648 LabelPatch::Text(t) => {
9649 unsafe { tf.setStringValue(&NSString::from_str(t)) };
9650 if let Some(label) = h.downcast_ref::<DayLabel>() {
9651 label.ivars().has_runs.set(false);
9652 label.set_links(false);
9653 }
9654 }
9655 LabelPatch::Color(c) => unsafe {
9656 tf.setTextColor(c.map(nscolor).as_deref());
9657 },
9658 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9659 LabelPatch::Runs(text, runs) => {
9660 let base = unsafe { tf.font() };
9664 let s = match base.as_deref() {
9665 Some(f) => {
9666 attributed_label(text, f, None, TextRole::default(), runs)
9667 }
9668 None => attributed_label(
9669 text,
9670 &nsfont(day_spec::FontSpec::default()),
9671 None,
9672 TextRole::default(),
9673 runs,
9674 ),
9675 };
9676 unsafe { tf.setAttributedStringValue(&s) };
9677 set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9680 if let Some(label) = h.downcast_ref::<DayLabel>() {
9681 label.ivars().has_runs.set(!runs.is_empty());
9682 label.set_links(runs.iter().any(|r| r.link.is_some()));
9683 }
9684 }
9685 }
9686 }
9687 }
9688 kinds::BUTTON => {
9689 if let (Some(p), Ok(btn)) = (
9690 patch.downcast_ref::<ButtonPatch>(),
9691 h.clone().downcast::<NSButton>(),
9692 ) {
9693 match p {
9694 ButtonPatch::Content(c) => {
9695 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only);
9696 }
9697 ButtonPatch::Title(t) => {
9698 let style = BUTTON_STYLES
9699 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9700 .unwrap_or_default();
9701 set_button_title(&btn, t, style);
9702 }
9703 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9704 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9705 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9706 }
9707 }
9708 }
9709 kinds::TOGGLE => {
9710 if let (Some(p), Ok(sw)) = (
9711 patch.downcast_ref::<TogglePatch>(),
9712 h.clone().downcast::<NSSwitch>(),
9713 ) {
9714 match p {
9715 TogglePatch::On(on) => {
9716 let want = isize::from(*on);
9717 if unsafe { sw.state() } != want {
9718 unsafe { sw.setState(want) };
9719 }
9720 }
9721 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9722 }
9723 }
9724 }
9725 kinds::SLIDER => {
9726 if let (Some(p), Ok(sl)) = (
9727 patch.downcast_ref::<SliderPatch>(),
9728 h.clone().downcast::<NSSlider>(),
9729 ) {
9730 match p {
9731 SliderPatch::Value(v) => {
9732 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9733 unsafe { sl.setDoubleValue(*v) };
9734 }
9735 }
9736 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9737 }
9738 }
9739 }
9740 kinds::PROGRESS => {
9741 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9742 {
9743 crate::controls::spinner::update(self, h, p);
9744 return;
9745 }
9746
9747 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9748 patch.downcast_ref::<ProgressPatch>(),
9749 h.clone().downcast::<NSProgressIndicator>(),
9750 ) {
9751 unsafe {
9752 if let Some(val) = v {
9753 if pi.isIndeterminate() {
9754 pi.stopAnimation(None);
9755 pi.setIndeterminate(false);
9756 pi.setStyle(NSProgressIndicatorStyle::Bar);
9757 pi.setMinValue(0.0);
9758 pi.setMaxValue(1.0);
9759 }
9760 if (pi.doubleValue() - val).abs() > 0.0001 {
9761 pi.setDoubleValue(*val);
9762 }
9763 } else {
9764 pi.setIndeterminate(true);
9765 pi.setStyle(NSProgressIndicatorStyle::Spinning);
9766 pi.startAnimation(None);
9767 }
9768 }
9769 }
9770 }
9771 kinds::NAV_MENU => {
9772 if let Some(NavMenuPatch::Items {
9773 items,
9774 icons,
9775 badges,
9776 badge_icons,
9777 badge_tints,
9778 sections,
9779 tints,
9780 menus,
9781 movable,
9782 sorted,
9783 selected,
9784 rows_changed,
9785 ..
9786 }) = patch.downcast_ref::<NavMenuPatch>()
9787 {
9788 NAV_MENUS.with(|m| {
9789 let m = m.borrow();
9790 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9791 return;
9792 };
9793 (*data.ivars().movable.borrow_mut()).clone_from(movable);
9794 (*data.ivars().sorted.borrow_mut()).clone_from(sorted);
9795 data.set_items(
9796 items,
9797 icons,
9798 badges,
9799 badge_icons,
9800 badge_tints,
9801 sections,
9802 tints,
9803 menus,
9804 );
9805 data.ivars().suppress.set(true);
9806 if let Some(rows) = rows_changed {
9809 let set = objc2_foundation::NSMutableIndexSet::new();
9810 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9811 unsafe { set.addIndex(row) };
9812 }
9813 unsafe {
9814 outline.reloadDataForRowIndexes_columnIndexes(
9815 &set,
9816 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9817 );
9818 };
9819 data.ivars().suppress.set(false);
9820 return;
9821 }
9822 unsafe {
9823 outline.reloadData();
9824 match selected.and_then(|i| data.row_of_item(i)) {
9825 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9826 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9827 false,
9828 ),
9829 None => outline.deselectAll(None),
9830 }
9831 }
9832 data.ivars().suppress.set(false);
9833 });
9834 adopt_menu_for_tabs(self.mtm(), h);
9836 } else if let Some(NavMenuPatch::IconProgress(progress)) =
9837 patch.downcast_ref::<NavMenuPatch>()
9838 {
9839 NAV_MENUS.with(|menus| {
9840 let menus = menus.borrow();
9841 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9842 return;
9843 };
9844 let previous = data.ivars().icon_progress.replace(progress.clone());
9845 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9846 let Some(index) = item else {
9847 continue;
9848 };
9849 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9850 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9851 continue;
9852 }
9853 if let Some(view) = unsafe {
9854 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9855 } && let Some(cell) =
9856 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9857 && let Some(icon) = unsafe { cell.imageView() }
9858 {
9859 nav_progress::update(&icon, value);
9860 }
9861 }
9862 });
9863 } else if let Some(NavMenuPatch::Selected(sel)) =
9864 patch.downcast_ref::<NavMenuPatch>()
9865 {
9866 NAV_MENUS.with(|m| {
9867 let m = m.borrow();
9868 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9869 return;
9870 };
9871 data.ivars().suppress.set(true);
9872 unsafe {
9873 match sel.and_then(|i| data.row_of_item(i)) {
9874 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9875 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9876 false,
9877 ),
9878 None => outline.deselectAll(None),
9879 }
9880 }
9881 data.ivars().suppress.set(false);
9882 });
9883 }
9884 }
9885 kinds::INSPECTOR => {
9886 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9887 INSPECTOR_STATE.with(|m| {
9888 if let Some(state) = m.borrow().get(&ptr_of(h)) {
9889 state.panel_item.setCollapsed(!*v);
9892 }
9893 });
9894 }
9895 }
9896 kinds::SPLIT => {
9897 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9898 SPLIT_STATE.with(|m| {
9899 let m = m.borrow();
9900 let Some(state) = m.get(&ptr_of(h)) else {
9901 return;
9902 };
9903 let iv = state.delegate.ivars();
9904 match p {
9905 SplitPatch::Fraction(f) => {
9906 iv.share.set(f.clamp(0.0, 1.0));
9907 if iv.positioned.get() {
9908 split_place(&state.split, iv);
9909 }
9910 }
9911 SplitPatch::Axis(axis) => unsafe {
9912 state
9913 .split
9914 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9915 state.split.adjustSubviews();
9916 if iv.positioned.get() {
9917 split_place(&state.split, iv);
9918 }
9919 },
9920 }
9921 });
9922 }
9923 }
9924 kinds::NAV => {
9925 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9926 nav_present(self.mtm(), h, *next);
9927 return;
9928 }
9929 if let Some(p) = patch.downcast_ref::<NavPatch>() {
9930 NAV_STATE.with(|m| {
9931 let mut m = m.borrow_mut();
9932 let Some(state) = m.get_mut(&ptr_of(h)) else {
9933 return;
9934 };
9935 match p {
9936 NavPatch::Pushed { title, .. } => {
9937 let last = state.pages.len().saturating_sub(1);
9939 state.selected = last;
9940 for (i, page) in state.pages.iter().enumerate() {
9941 page.setHidden(i != last);
9942 }
9943 if let Some(hdr) = state.header.as_mut() {
9944 hdr.titles.push(title.clone());
9945 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9946 }
9947 }
9948 NavPatch::Popped => {
9949 let n = state.pages.len();
9952 if let Some(top) = state.pages.last() {
9953 top.setHidden(true);
9954 }
9955 if n >= 2 {
9956 state.pages[n - 2].setHidden(false);
9957 }
9958 state.selected = n.saturating_sub(2);
9959 if let Some(hdr) = state.header.as_mut() {
9960 if hdr.titles.len() > 1 {
9961 hdr.titles.pop();
9962 }
9963 let after: Vec<Retained<NSView>> = state
9966 .pages
9967 .iter()
9968 .take(n.saturating_sub(1))
9969 .cloned()
9970 .collect();
9971 sync_nav_header(hdr, &state.detail_wrap, &after);
9972 }
9973 }
9974 NavPatch::Title(t) => {
9975 if let Some(hdr) = state.header.as_mut() {
9976 if let Some(last) = hdr.titles.last_mut() {
9977 last.clone_from(t);
9978 }
9979 unsafe {
9980 hdr.title.setStringValue(&NSString::from_str(t));
9981 }
9982 }
9983 }
9984 #[expect(
9988 clippy::match_same_arms,
9989 reason = "each no-op patch keeps its own arm and the comment saying why it is one"
9990 )]
9991 NavPatch::GuardTop(_) => {}
9992 NavPatch::Reorder(order) => {
9993 let old = state.pages.clone();
9994 state.pages =
9995 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9996 if let Some(tabs) = &state.tabs {
9997 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9998 unsafe {
9999 let items = tabs.view.tabViewItems();
10000 for item in &items {
10001 tabs.view.removeTabViewItem(&item);
10002 }
10003 for i in order {
10004 if let Some(item) = items.iter().nth(*i) {
10005 tabs.view.addTabViewItem(&item);
10006 }
10007 }
10008 }
10009 TAB_PICK_SUPPRESS.with(|s| s.set(false));
10010 }
10011 }
10012 #[expect(
10014 clippy::match_same_arms,
10015 reason = "each no-op patch keeps its own arm and the comment saying why it is one"
10016 )]
10017 NavPatch::Presentation(_) => {}
10018 NavPatch::Select(i) => {
10022 state.selected = *i;
10023 match state.tabs.as_ref() {
10024 Some(tabs) => {
10026 let n = unsafe { tabs.view.numberOfTabViewItems() };
10027 if (*i as isize) < n {
10028 TAB_PICK_SUPPRESS.with(|s| s.set(true));
10029 unsafe {
10030 tabs.view.selectTabViewItemAtIndex(*i as isize);
10031 };
10032 TAB_PICK_SUPPRESS.with(|s| s.set(false));
10033 }
10034 }
10035 None => {
10036 for (n, page) in state.pages.iter().enumerate() {
10037 page.setHidden(n != *i);
10038 }
10039 }
10040 }
10041 }
10042 NavPatch::ListVisible(v) => {
10048 state.list_visible = *v;
10049 if let Some(item) = state.list_item.as_ref() {
10050 item.setCollapsed(!*v);
10051 let split = unsafe { state.split_vc.splitView() };
10052 unsafe { split.layoutSubtreeIfNeeded() };
10053 if let Some(w) = take_list_placement(state) {
10058 unsafe {
10059 split.setPosition_ofDividerAtIndex(
10060 day_spec::NAV_SIDEBAR_WIDTH + w,
10061 1,
10062 );
10063 }
10064 }
10065 if *v
10072 && let Some(wrap) = state.list_wrap.as_ref()
10073 && let Some(page) = state.list_page.as_ref()
10074 {
10075 unsafe {
10076 wrap.layoutSubtreeIfNeeded();
10077 page.setFrame(wrap.bounds());
10078 }
10079 }
10080 }
10081 }
10082 NavPatch::ListInStack(_) => {}
10086 }
10087 });
10088 }
10089 }
10090 kinds::COVER => {
10096 if let (Some(p), Ok(page)) = (
10097 patch.downcast_ref::<CoverPatch>(),
10098 h.clone().downcast::<DayNavPage>(),
10099 ) {
10100 let node = page.ivars().node;
10101 match p {
10102 CoverPatch::Present { background, .. } => {
10103 if page.ivars().sheet.get() {
10104 if let Some(parent) =
10105 primary_content().and_then(|v| unsafe { v.window() })
10106 {
10107 let bounds = parent.frame().size;
10108 let max = if page.ivars().large.get() {
10109 day_spec::props::LARGE_SHEET_MAX
10110 } else {
10111 day_spec::props::SHEET_MAX
10112 };
10113 let height = if page.ivars().half.get() {
10114 (bounds.height * 0.5).clamp(160.0, max.height)
10115 } else {
10116 (bounds.height - 80.0).clamp(300.0, max.height)
10117 };
10118 let size = NSSize::new(
10119 (bounds.width - 40.0).clamp(320.0, max.width),
10120 height,
10121 );
10122 let window = unsafe {
10123 NSWindow::initWithContentRect_styleMask_backing_defer(
10124 NSWindow::alloc(MainThreadMarker::new().unwrap()),
10125 NSRect::new(NSPoint::new(0.0, 0.0), size),
10126 NSWindowStyleMask::Titled,
10127 NSBackingStoreType::Buffered,
10128 false,
10129 )
10130 };
10131 unsafe {
10132 window.setReleasedWhenClosed(false);
10133 page.removeFromSuperview();
10134 page.setHidden(false);
10135 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
10136 window.setContentView(Some(&page));
10137 }
10138 let key = ptr_of(h);
10139 SHEET_NODES.with(|t| {
10140 t.insert(Retained::as_ptr(&window) as usize, node)
10141 });
10142 install_sheet_escape_monitor();
10143 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
10144 dispatch2::DispatchQueue::main().exec_async(move || {
10145 ffi_guard::contain((), || {
10146 let window =
10147 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
10148 if let (Some(window), Some(parent)) = (
10149 window,
10150 primary_content()
10151 .and_then(|v| unsafe { v.window() }),
10152 ) {
10153 unsafe {
10154 parent.beginSheet_completionHandler(
10155 &window, None,
10156 );
10157 }
10158 }
10159 });
10160 });
10161 emit(
10162 node,
10163 Event::FrameChanged(Size::new(size.width, size.height)),
10164 );
10165 }
10166 return;
10167 }
10168 unsafe {
10172 page.setWantsLayer(true);
10173 if let Some(layer) = page.layer() {
10174 let color = match background {
10175 Some(bg) => nscolor(*bg),
10176 None => NSColor::windowBackgroundColor(),
10177 };
10178 layer.setBackgroundColor(Some(&color.CGColor()));
10179 }
10180 }
10181 if let Some(content) = primary_content() {
10184 if let Some(window) = unsafe { content.window() } {
10185 toolbar::cover_presented(ptr_of(h), &window);
10186 }
10187 let top = title_bar_inset(&content);
10192 let full = content.frame().size;
10193 page.ivars().top_inset.set(top);
10194 unsafe {
10195 page.removeFromSuperview();
10196 content.addSubview(&page);
10197 page.setFrame(NSRect::new(
10198 NSPoint::new(0.0, -top),
10199 NSSize::new(full.width, full.height),
10200 ));
10201 page.setBoundsOrigin(NSPoint::new(0.0, -top));
10202 page.setAutoresizingMask(
10203 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10204 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10205 );
10206 page.setHidden(false);
10207 }
10208 emit(
10209 node,
10210 Event::FrameChanged(Size::new(
10211 full.width,
10212 (full.height - top).max(0.0),
10213 )),
10214 );
10215 }
10216 }
10217 CoverPatch::DismissDisabled(_) => {}
10218 CoverPatch::Dismiss => {
10219 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
10220 toolbar::cover_dismissed(ptr_of(h));
10221 unsafe {
10222 page.setHidden(true);
10223 page.removeFromSuperview();
10224 }
10225 emit(node, Event::CoverHidden);
10226 }
10227 }
10228 }
10229 }
10230 kinds::PICKER => picker::update_any(self, h, patch),
10231 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
10232 kinds::TEXT_FIELD => {
10233 if let (Some(p), Ok(tf)) = (
10234 patch.downcast_ref::<TextFieldPatch>(),
10235 h.clone().downcast::<NSTextField>(),
10236 ) {
10237 match p {
10238 TextFieldPatch::Text { text, from_native } => {
10239 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
10241 unsafe { tf.setStringValue(&NSString::from_str(text)) };
10242 }
10243 }
10244 TextFieldPatch::Placeholder(t) => unsafe {
10245 tf.setPlaceholderString(Some(&NSString::from_str(t)));
10246 },
10247 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
10248 TextFieldPatch::Select(sel) => {
10252 if let Some(editor) = tf.currentEditor() {
10253 let (start, end) = sel.utf16(&editor.string().to_string());
10254 editor.setSelectedRange(objc2_foundation::NSRange::new(
10255 start,
10256 end - start,
10257 ));
10258 }
10259 }
10260 }
10261 }
10262 }
10263 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
10264 Some(ListPatch::Splice(deltas)) => {
10265 if let Some((table, data)) = list_entry(ptr_of(h)) {
10271 use objc2_app_kit::NSTableViewAnimationOptions;
10272 for d in deltas {
10273 unsafe {
10274 table.beginUpdates();
10275 match d {
10276 day_spec::props::RowDelta::Insert(i) => table
10277 .insertRowsAtIndexes_withAnimation(
10278 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10279 NSTableViewAnimationOptions::SlideDown,
10280 ),
10281 day_spec::props::RowDelta::Remove(i) => table
10282 .removeRowsAtIndexes_withAnimation(
10283 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10284 NSTableViewAnimationOptions::SlideUp,
10285 ),
10286 day_spec::props::RowDelta::Move(from, to) => {
10287 table.moveRowAtIndex_toIndex(*from as isize, *to as isize);
10288 }
10289 }
10290 table.endUpdates();
10291 }
10292 }
10293 if let Some(source) = data.ivars().source.borrow().as_ref() {
10297 let n = (source.len)();
10298 *data.ivars().tokens.borrow_mut() =
10299 (0..n).map(|i| (source.token_at)(i)).collect();
10300 }
10301 }
10302 post_realize_visible_rows(ptr_of(h));
10303 }
10304 Some(ListPatch::Reload) => {
10305 if let Some((table, data)) = list_entry(ptr_of(h)) {
10306 let selected = unsafe { table.selectedRowIndexes() };
10310 let tokens: Vec<u64> = data
10311 .ivars()
10312 .tokens
10313 .borrow()
10314 .iter()
10315 .enumerate()
10316 .filter(|(row, _)| selected.containsIndex(*row))
10317 .map(|(_, token)| *token)
10318 .collect();
10319 data.ivars().suppress.set(true);
10320 if let Some(moves) = data.permutation_moves(&table) {
10327 unsafe {
10328 table.beginUpdates();
10329 for (from, to) in moves {
10330 table.moveRowAtIndex_toIndex(from as isize, to as isize);
10331 }
10332 table.endUpdates();
10333 }
10334 } else {
10335 unsafe { table.reloadData() };
10336 }
10337 let restored = objc2_foundation::NSMutableIndexSet::new();
10338 for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
10339 if tokens.contains(token) {
10340 restored.addIndex(row);
10341 }
10342 }
10343 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
10344 data.ivars().suppress.set(false);
10345 }
10346 post_realize_visible_rows(ptr_of(h));
10352 }
10353 Some(ListPatch::ScrollToRow(row)) => {
10354 let (key, row) = (ptr_of(h), *row);
10357 <AppKit as Platform>::post(Box::new(move || {
10358 if let Some((table, _)) = list_entry(key) {
10359 let rows = unsafe { table.numberOfRows() };
10360 if rows > 0 {
10361 unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
10362 }
10363 }
10364 }));
10365 post_realize_visible_rows(ptr_of(h));
10366 }
10367 Some(ListPatch::ScrollToEnd) => {
10368 let key = ptr_of(h);
10373 <AppKit as Platform>::post(Box::new(move || {
10374 if let Some((table, _)) = list_entry(key) {
10375 let rows = unsafe { table.numberOfRows() };
10376 if rows > 0 {
10377 unsafe { table.scrollRowToVisible(rows - 1) };
10378 }
10379 }
10380 }));
10381 post_realize_visible_rows(ptr_of(h));
10383 }
10384 Some(ListPatch::Selected(rows)) => {
10385 if let Some((table, data)) = list_entry(ptr_of(h)) {
10388 data.ivars().suppress.set(true);
10389 unsafe {
10390 if rows.is_empty() {
10391 table.deselectAll(None);
10392 } else {
10393 let set = objc2_foundation::NSMutableIndexSet::new();
10394 let count = table.numberOfRows().max(0) as usize;
10395 for r in rows.iter().copied().filter(|r| *r < count) {
10396 set.addIndex(r);
10397 }
10398 table.selectRowIndexes_byExtendingSelection(&set, false);
10399 }
10400 }
10401 data.ivars().suppress.set(false);
10402 }
10403 }
10404 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
10405 if let Some((table, data)) = list_entry(ptr_of(h)) {
10406 data.row_resized(&table, *cell, *height);
10407 }
10408 }
10409 Some(ListPatch::Editing(_)) | None => {}
10412 },
10413 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
10414 Some(TreePatch::Reload) => {
10415 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
10420 unsafe { outline.reloadData() };
10421 }
10422 post_realize_visible_tree_rows(ptr_of(h));
10423 }
10424 Some(TreePatch::Expand(token, on)) => {
10425 let (key, token, on) = (ptr_of(h), *token, *on);
10430 <AppKit as Platform>::post(Box::new(move || {
10431 if let Some((outline, data)) = tree_entry(key) {
10432 let item = data.intern(token);
10433 data.ivars().suppress.set(true);
10436 unsafe {
10437 if on {
10438 outline.expandItem(Some(&item));
10439 } else {
10440 outline.collapseItem(Some(&item));
10441 }
10442 }
10443 data.ivars().suppress.set(false);
10444 }
10445 day_core::pump_events();
10446 }));
10447 post_realize_visible_tree_rows(ptr_of(h));
10448 }
10449 Some(TreePatch::Selected(tokens)) => {
10450 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
10451 data.ivars().suppress.set(true);
10452 unsafe {
10453 if tokens.is_empty() {
10454 outline.deselectAll(None);
10455 } else {
10456 let set = objc2_foundation::NSMutableIndexSet::new();
10457 for t in tokens {
10458 let row = outline.rowForItem(Some(&data.intern(*t)));
10461 if row >= 0 {
10462 set.addIndex(row as usize);
10463 }
10464 }
10465 outline.selectRowIndexes_byExtendingSelection(&set, false);
10466 }
10467 }
10468 data.ivars().suppress.set(false);
10469 }
10470 }
10471 Some(TreePatch::Reveal(token)) => {
10472 let (key, token) = (ptr_of(h), *token);
10475 <AppKit as Platform>::post(Box::new(move || {
10476 if let Some((outline, data)) = tree_entry(key) {
10477 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
10478 if row >= 0 {
10479 unsafe { outline.scrollRowToVisible(row) };
10480 }
10481 }
10482 }));
10483 post_realize_visible_tree_rows(ptr_of(h));
10484 }
10485 None => {}
10486 },
10487 _ => {
10488 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
10489 update(self, h, patch);
10490 }
10491 }
10492 }
10493 }
10494
10495 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
10497 let f = self.registry.get(kind).and_then(|r| r.release);
10500 if let Some(f) = f {
10501 f(self, h);
10502 }
10503 }
10504 fn release(&mut self, h: Handle) {
10505 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
10506 self.secondary.retain(|w| {
10510 if ptr_of(&w.content) == ptr_of(&h) {
10511 w.window.close();
10512 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
10516 false
10517 } else {
10518 true
10519 }
10520 });
10521 TARGETS.with(|m| {
10522 m.borrow_mut().remove(&ptr_of(&h));
10523 });
10524 LIST_STATE.with(|m| {
10525 m.borrow_mut().remove(&ptr_of(&h));
10526 });
10527 TREE_STATE.with(|m| {
10528 m.borrow_mut().remove(&ptr_of(&h));
10529 });
10530 GESTURES.with(|m| {
10531 m.borrow_mut().remove(&ptr_of(&h));
10532 });
10533 NAV_STATE.with(|m| {
10534 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
10535 unsafe {
10543 nav.split_vc.setNextResponder(None);
10544 let split = nav.split_vc.splitView();
10545 if split.nextResponder().is_some_and(|r| {
10546 core::ptr::eq::<objc2::runtime::AnyObject>(
10547 r.as_ref(),
10548 nav.split_vc.as_ref(),
10549 )
10550 }) {
10551 split.setNextResponder(None);
10552 }
10553 }
10554 }
10555 });
10556 NAV_PAGES.with(|set| {
10557 set.borrow_mut().remove(&ptr_of(&h));
10558 });
10559 SPLIT_STATE.with(|m| {
10560 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
10561 state.split.setDelegate(None);
10562 }
10563 });
10564 INSPECTOR_STATE.with(|m| {
10565 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
10566 unsafe {
10569 insp.split_vc.setNextResponder(None);
10570 let split = insp.split_vc.splitView();
10571 if split.nextResponder().is_some_and(|r| {
10572 core::ptr::eq::<objc2::runtime::AnyObject>(
10573 r.as_ref(),
10574 insp.split_vc.as_ref(),
10575 )
10576 }) {
10577 split.setNextResponder(None);
10578 }
10579 }
10580 }
10581 });
10582 NAV_MENUS.with(|m| {
10583 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
10584 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
10589 }
10590 });
10591 day_spec::sidetable::sweep(ptr_of(&h));
10597 unsafe { h.removeFromSuperview() };
10598 }
10599
10600 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
10601 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
10605 unsafe { content_of(parent).addSubview(child) };
10606 adopt_menu_for_tabs(self.mtm(), child);
10607 return;
10608 }
10609 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
10612 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
10613 let handled = NAV_STATE.with(|m| {
10614 let mut m = m.borrow_mut();
10615 let Some(state) = m.get_mut(&ptr_of(parent)) else {
10616 return false;
10617 };
10618 if page_pane == Some(day_spec::props::Pane::List)
10621 && let Some(wrap) = state.list_wrap.as_ref()
10622 {
10623 state.list_page = Some(child.clone());
10624 unsafe {
10625 child.setFrame(wrap.bounds());
10626 child.setAutoresizingMask(
10627 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10628 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10629 );
10630 wrap.addSubview(child);
10631 }
10632 return true;
10633 }
10634 if is_sidebar_page {
10635 state.sidebar_page = Some(child.clone());
10636 }
10637 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
10643 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
10648 state.pages.push(child.clone());
10649 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
10650 unsafe {
10651 child.setAutoresizingMask(
10652 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10653 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10654 );
10655 item.setView(Some(child));
10656 tabs.view.addTabViewItem(&item);
10657 }
10658 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10659 sync_tab_labels(tabs, &titles, state.selected);
10660 }
10661 return true;
10662 }
10663 let (wrap, frame) = if to_pane {
10664 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10665 } else {
10666 state.pages.push(child.clone());
10667 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10668 (
10669 &state.detail_wrap,
10670 nav_page_frame(&state.detail_wrap, visible),
10671 )
10672 };
10673 unsafe {
10674 child.setFrame(frame);
10675 child.setAutoresizingMask(
10676 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10677 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10678 );
10679 wrap.addSubview(child);
10680 }
10681 true
10682 });
10683 if handled {
10684 return;
10685 }
10686 let split_pane = SPLIT_STATE.with(|m| {
10689 let m = m.borrow();
10690 let Some(state) = m.get(&ptr_of(parent)) else {
10691 return false;
10692 };
10693 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10694 let wrap = if second {
10695 &state.second_wrap
10696 } else {
10697 &state.first_wrap
10698 };
10699 unsafe {
10700 child.setFrame(wrap.bounds());
10701 child.setAutoresizingMask(
10702 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10703 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10704 );
10705 wrap.addSubview(child);
10706 }
10707 true
10708 });
10709 if split_pane {
10710 return;
10711 }
10712 let inspected = INSPECTOR_STATE.with(|m| {
10715 let m = m.borrow();
10716 let Some(state) = m.get(&ptr_of(parent)) else {
10717 return false;
10718 };
10719 let panel = INSPECTOR_PANES
10720 .with(|t| t.get(ptr_of(child)))
10721 .unwrap_or(false);
10722 let wrap = if panel {
10723 &state.panel_wrap
10724 } else {
10725 &state.content_wrap
10726 };
10727 unsafe {
10728 child.setFrame(wrap.bounds());
10729 child.setAutoresizingMask(
10730 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10731 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10732 );
10733 wrap.addSubview(child);
10734 }
10735 true
10736 });
10737 if !inspected {
10738 unsafe { content_of(parent).addSubview(child) };
10741 }
10742 }
10743
10744 fn remove(&mut self, parent: &Handle, child: &Handle) {
10745 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10746 let mtm = self.mtm();
10747 NAV_STATE.with(|m| {
10748 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10749 if let Some(tabs) = state.tabs.as_ref() {
10751 unsafe {
10752 let n = tabs.view.numberOfTabViewItems();
10753 for i in 0..n {
10754 let item = tabs.view.tabViewItemAtIndex(i);
10755 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10756 tabs.view.removeTabViewItem(&item);
10757 break;
10758 }
10759 }
10760 }
10761 }
10762 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10763 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10764 state.sidebar_page = None;
10765 }
10766 }
10767 });
10768 unsafe { child.removeFromSuperview() };
10769 }
10770
10771 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10772 unsafe { content_of(parent).addSubview(child) };
10773 }
10774
10775 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10776 match kind {
10777 kinds::LABEL => {
10778 if let Some(tf) = h.downcast_ref::<NSTextField>() {
10779 let w = p.width.unwrap_or(1.0e6);
10780 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10782 let mut height = s.height.ceil();
10783 if tf.maximumNumberOfLines() == 1 {
10786 thread_local! {
10787 static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10788 }
10789 if let Some(font) = unsafe { tf.font() } {
10790 height = height.min(
10791 METRICS
10792 .with(|metrics| metrics.defaultLineHeightForFont(&font))
10793 .ceil(),
10794 );
10795 }
10796 }
10797 return Size::new(s.width.ceil().min(w), height);
10798 }
10799 Size::ZERO
10800 }
10801 kinds::BUTTON | kinds::TOGGLE => {
10802 let s = unsafe { h.fittingSize() };
10803 Size::new(s.width.ceil(), s.height.ceil())
10804 }
10805 kinds::SLIDER => {
10806 let s = unsafe { h.fittingSize() };
10807 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10808 }
10809 kinds::PICKER => picker::measure_any(self, h, p),
10810 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10811 kinds::TEXT_FIELD => {
10812 let s = unsafe { h.fittingSize() };
10813 Size::new(
10814 p.width.unwrap_or(s.width.max(160.0)),
10815 s.height.max(22.0).ceil(),
10816 )
10817 }
10818 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10819 kinds::LIST_ITEM => {
10822 let s = h.fittingSize();
10823 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10824 }
10825 kinds::PROGRESS => {
10826 let indeterminate = h
10828 .clone()
10829 .downcast::<NSProgressIndicator>()
10830 .is_ok_and(|pi| unsafe { pi.isIndeterminate() });
10831 if indeterminate {
10832 let large = h
10833 .downcast_ref::<NSProgressIndicator>()
10834 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10835 let side = if large { 32.0 } else { 20.0 };
10836 Size::new(side, side)
10837 } else {
10838 Size::new(p.width.unwrap_or(180.0), 20.0)
10839 }
10840 }
10841 kinds::NAV_MENU => {
10842 let rows = NAV_MENUS.with(|m| {
10843 m.borrow()
10844 .get(&ptr_of(h))
10845 .map_or(0, |(_, d)| d.ivars().items.borrow().len())
10846 });
10847 Size::new(
10848 p.width.unwrap_or(220.0),
10849 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10850 )
10851 }
10852 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10854 _ => {
10855 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10856 measure(self, h, p)
10857 } else {
10858 let s = unsafe { h.fittingSize() };
10859 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10860 }
10861 }
10862 }
10863 }
10864
10865 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10866 unsafe {
10867 h.setWantsLayer(true);
10868 }
10869 let v = h.clone();
10870 with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10871 }
10872
10873 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10874 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10877 let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10878 let v = h.clone();
10879 with_appkit_anim(anim, move || {
10880 if let Some(base) = base {
10881 apply_geometry(&v, base, t);
10882 }
10883 });
10884 }
10885
10886 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10887 if let Some(label) = h.downcast_ref::<DayLabel>() {
10888 label.ivars().selectable.set(selectable);
10889 label.set_links(label.ivars().has_links.get());
10890 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10891 unsafe { tf.setSelectable(selectable) };
10892 }
10893 None
10894 }
10895
10896 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10897 let node = text_field_node(h)?;
10898 let old = h.downcast_ref::<NSTextField>()?;
10899 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10902 .then(|| self.swap_text_field(h, old, node, traits.secure));
10903 let tf = swapped.as_deref().unwrap_or(old);
10904 unsafe {
10905 tf.setEditable(!traits.read_only);
10908 tf.setSelectable(true);
10909 }
10910 let content_type = match traits.purpose {
10914 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10915 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10916 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10917 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10918 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10919 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10920 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10921 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10922 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10923 };
10924 unsafe {
10925 tf.setContentType(content_type);
10926 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10929 }
10930 swapped.as_ref().map(view_of)
10933 }
10934
10935 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10936 let key = Retained::as_ptr(h) as usize;
10937 if cursor == Cursor::Default {
10938 if let Some((owner, area)) = self.cursors.remove(&key) {
10940 unsafe { h.removeTrackingArea(&area) };
10941 if owner.ivars().hiding.replace(false) {
10942 NSCursor::unhide();
10943 }
10944 }
10945 return;
10946 }
10947 let hidden = cursor == Cursor::None;
10948 let shape = if hidden { None } else { ns_cursor(&cursor) };
10949 let mtm = self.mtm;
10950 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10951 let owner = DayCursorOwner::new(mtm);
10952 let opts = NSTrackingAreaOptions::CursorUpdate
10955 | NSTrackingAreaOptions::MouseEnteredAndExited
10956 | NSTrackingAreaOptions::ActiveInKeyWindow
10957 | NSTrackingAreaOptions::InVisibleRect;
10958 let any: &objc2::runtime::AnyObject = &owner;
10959 let area = unsafe {
10960 NSTrackingArea::initWithRect_options_owner_userInfo(
10961 NSTrackingArea::alloc(),
10962 NSRect::ZERO,
10963 opts,
10964 Some(any),
10965 None,
10966 )
10967 };
10968 unsafe { h.addTrackingArea(&area) };
10969 (owner, area)
10970 });
10971 let changed = {
10972 let iv = owner.ivars();
10973 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10974 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10975 (None, None) => true,
10976 _ => false,
10977 };
10978 *iv.cursor.borrow_mut() = shape;
10979 let was_hidden = iv.hidden.replace(hidden);
10980 !same || was_hidden != hidden
10981 };
10982 if changed && let Some(w) = h.window() {
10985 unsafe { w.invalidateCursorRectsForView(h) };
10986 }
10987 }
10988
10989 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
11003 if !day_spec::kind_has_baseline(kind) {
11004 return None;
11005 }
11006 let current = unsafe { h.frame() };
11009 if (current.size.height - size.height).abs() > 0.5 {
11010 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
11011 }
11012 let insets = unsafe { h.alignmentRectInsets() };
11013 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
11014 let font = h
11015 .downcast_ref::<NSControl>()
11016 .and_then(|c| unsafe { c.font() });
11017 let offset = match font {
11018 Some(_) if kind == kinds::TEXT_AREA => reported,
11021 Some(f) => {
11022 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
11023 let line = ascender - descender;
11024 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
11025 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
11026 }
11027 None => reported,
11028 };
11029 (offset > 0.0 && offset < size.height).then_some(offset)
11031 }
11032
11033 fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
11034 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
11036 return;
11037 }
11038 let r = NSRect::new(
11041 NSPoint::new(frame.origin.x, frame.origin.y),
11042 NSSize::new(frame.size.width, frame.size.height),
11043 );
11044 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
11049 let strip = unsafe { split.superview() }
11053 .and_then(|sup| {
11054 let content = unsafe { sup.window() }?.contentView()?;
11055 let mut ancestor = Some(sup.clone());
11059 while let Some(view) = ancestor {
11060 if std::ptr::eq(&raw const *view, &raw const *content) {
11061 break;
11062 }
11063 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
11064 return None; }
11066 ancestor = unsafe { view.superview() };
11067 }
11068 let point = unsafe {
11069 sup.convertPoint_toView(
11070 NSPoint::new(frame.origin.x, frame.origin.y),
11071 Some(&content),
11072 )
11073 };
11074 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
11075 })
11076 .unwrap_or(0.0);
11077 let r = NSRect::new(
11078 NSPoint::new(r.origin.x, r.origin.y - strip),
11079 NSSize::new(r.size.width, r.size.height + strip),
11080 );
11081 let wraps = NAV_STATE.with(|m| {
11082 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
11083 #[expect(
11084 clippy::float_cmp,
11085 reason = "unchanged-value check against the strip stored last time"
11086 )]
11087 let changed = s.title_strip != strip;
11088 changed.then(|| {
11089 s.title_strip = strip;
11090 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
11091 w.extend(s.list_wrap.clone());
11092 w
11093 })
11094 })
11095 });
11096 let first = NAV_STATE.with(|m| {
11097 m.borrow_mut()
11098 .get_mut(&ptr_of(h))
11099 .map_or((false, None), |s| {
11100 if !s.presentation.is_split() {
11101 return (false, None);
11102 }
11103 let sidebar = !std::mem::replace(&mut s.positioned, true);
11104 (sidebar, take_list_placement(s))
11109 })
11110 });
11111 unsafe {
11112 split.setFrame(r);
11113 split.layoutSubtreeIfNeeded();
11114 }
11115 for wrap in wraps.iter().flatten() {
11118 place_below_strip(wrap, strip);
11119 }
11120 unsafe {
11121 if first.0 {
11122 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
11123 }
11124 if let Some(w) = first.1 {
11129 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
11130 }
11131 }
11132 } else {
11133 BASE_FRAMES.with(|m| {
11134 m.insert(
11135 ptr_of(h),
11136 [
11137 frame.origin.x,
11138 frame.origin.y,
11139 frame.size.width,
11140 frame.size.height,
11141 ],
11142 )
11143 });
11144 match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
11146 Some(t) => apply_geometry(
11147 h,
11148 [
11149 frame.origin.x,
11150 frame.origin.y,
11151 frame.size.width,
11152 frame.size.height,
11153 ],
11154 t,
11155 ),
11156 None => unsafe { h.setFrame(r) },
11157 }
11158 }
11159 }
11160
11161 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
11162 if let Some(sv) = h.downcast_ref::<NSScrollView>()
11163 && let Some(doc) = unsafe { sv.documentView() }
11164 {
11165 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
11166 }
11167 }
11168
11169 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
11171 day_spec::RowMetrics {
11172 insets: day_spec::Insets {
11173 top: 4.0,
11174 leading: 8.0,
11175 bottom: 4.0,
11176 trailing: 8.0,
11177 },
11178 min_height: 28.0,
11179 }
11180 }
11181
11182 fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
11183 if let Some(sv) = h.downcast_ref::<NSScrollView>()
11184 && let Some(doc) = unsafe { sv.documentView() }
11185 {
11186 unsafe {
11187 doc.scrollRectToVisible(NSRect::new(
11188 NSPoint::new(target.origin.x, target.origin.y),
11189 NSSize::new(target.size.width, target.size.height),
11190 ))
11191 };
11192 }
11193 }
11194
11195 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
11196 let Some(window) = h.window() else { return };
11197 let list = list_entry(ptr_of(h));
11199 let responder: &NSResponder = match &list {
11200 Some((table, _)) => table,
11201 None => h,
11202 };
11203 let responder_ptr = std::ptr::from_ref::<NSResponder>(responder) as usize;
11204 if focused {
11205 window.makeFirstResponder(Some(responder));
11206 return;
11207 }
11208 let owns = window
11211 .firstResponder()
11212 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
11213 || owns_first_responder(&window, h);
11214 if owns {
11215 window.makeFirstResponder(None);
11216 }
11217 }
11218
11219 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
11220 if focusable {
11223 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
11224 } else {
11225 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
11226 }
11227 }
11228
11229 fn set_event_sink(&mut self, sink: EventSink) {
11230 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
11231 }
11232
11233 fn set_edit_state(&mut self, state: &day_spec::EditState) {
11234 EDIT_STATE.with(|s| s.set(*state));
11235 }
11236
11237 fn modifiers(&mut self) -> day_spec::Modifiers {
11238 let f = NSEvent::modifierFlags_class();
11239 day_spec::Modifiers {
11240 shift: f.contains(NSEventModifierFlags::Shift),
11241 primary: f.contains(NSEventModifierFlags::Command),
11242 alt: f.contains(NSEventModifierFlags::Option),
11243 }
11244 }
11245
11246 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
11247 let front = undo_front(self.mtm);
11248 *front.ivars().state.borrow_mut() = state.clone();
11249 }
11250
11251 fn attach_list(&mut self, host: &Handle, source: ListSource) {
11252 let key = ptr_of(host);
11253 if let Some((table, data)) = list_entry(key) {
11254 data.ivars().source.replace(Some(source));
11255 unsafe { table.reloadData() };
11257 }
11258 post_realize_visible_rows(key);
11263 }
11264
11265 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
11266 let key = ptr_of(host);
11267 if let Some((outline, data)) = tree_entry(key) {
11268 data.ivars().source.replace(Some(source));
11269 unsafe { outline.reloadData() };
11271 }
11272 <AppKit as Platform>::post(Box::new(move || {
11275 if let Some((outline, _)) = tree_entry(key) {
11276 unsafe { outline.layoutSubtreeIfNeeded() };
11277 }
11278 }));
11279 }
11280
11281 fn adopt(&mut self, raw: RawHandle) -> Handle {
11282 let ptr = raw.cast::<NSView>();
11286 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
11287 }
11288
11289 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
11290 self.edit_toolbar(h, ops)
11291 }
11292
11293 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
11294 Self::patch_toolbar(h, patch);
11295 }
11296
11297 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
11298 let mtm = self.mtm;
11299 if self.menu_escape_monitor.is_none() {
11300 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
11301 ffi_guard::contain(event.as_ptr(), || {
11302 let event_ref = unsafe { event.as_ref() };
11303 let app = NSApplication::sharedApplication(mtm);
11304 if app.modalWindow().is_none()
11307 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
11308 && unsafe { event_ref.charactersIgnoringModifiers() }
11309 .is_some_and(|s| s.to_string() == "\u{1b}")
11310 && app
11311 .mainMenu()
11312 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
11313 {
11314 std::ptr::null_mut()
11315 } else {
11316 event.as_ptr()
11317 }
11318 })
11319 });
11320 self.menu_escape_monitor = unsafe {
11321 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
11322 objc2_app_kit::NSEventMask::KeyDown,
11323 &block,
11324 )
11325 }
11326 .map(MenuEscapeMonitor);
11327 }
11328 let app = NSApplication::sharedApplication(mtm);
11329 let menubar = NSMenu::new(mtm);
11330 let mut items = items.to_vec();
11333 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
11334 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
11335 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
11336 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
11337 let services =
11338 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
11339 let items =
11344 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
11345 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
11346 for item in &items {
11348 match item {
11349 day_spec::MenuItem::Submenu { label, items, role } => {
11350 let sub = build_ns_menu(mtm, label, items);
11351 let it = NSMenuItem::new(mtm);
11352 if *role == Some(day_spec::MenuBarRole::Help)
11356 || *label == day_localization::t(day_localization::key::day_help)
11357 {
11358 help_menu = Some((label.clone(), sub));
11359 continue;
11360 }
11361 it.setTitle(&NSString::from_str(label));
11362 it.setSubmenu(Some(&sub));
11363 menubar.addItem(&it);
11364 }
11365 other => {
11366 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
11368 let it = NSMenuItem::new(mtm);
11369 it.setSubmenu(Some(&sub));
11370 menubar.addItem(&it);
11371 }
11372 }
11373 }
11374 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
11377 install_windows_menu(mtm, &app, &menubar);
11378 }
11379 if let Some((label, help)) = help_menu {
11380 let it = NSMenuItem::new(mtm);
11381 it.setTitle(&NSString::from_str(&label));
11382 it.setSubmenu(Some(&help));
11383 menubar.addItem(&it);
11384 unsafe { app.setHelpMenu(Some(&help)) };
11387 }
11388 app.setMainMenu(Some(&menubar));
11389 unsafe { app.setServicesMenu(Some(&services)) };
11390 }
11391
11392 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
11393 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
11394 for sub in v.subviews() {
11395 unsafe { sub.setMenu(Some(menu)) };
11396 apply_to_subviews(&sub, menu);
11397 }
11398 }
11399 let Some(view) = h.downcast_ref::<NSView>() else {
11400 return;
11401 };
11402 if items.is_empty() {
11403 unsafe { view.setMenu(None) };
11404 return;
11405 }
11406 let menu = build_ns_menu(self.mtm, "", items);
11407 unsafe { view.setMenu(Some(&menu)) };
11413 apply_to_subviews(view, &menu);
11414 }
11415
11416 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
11417 transfer::source(h, source);
11418 }
11419 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
11420 transfer::target(h, target);
11421 }
11422 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11423 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
11426 }
11427
11428 fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11429 let Some(btn) = h.downcast_ref::<NSButton>() else {
11430 return;
11431 };
11432 unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
11436 BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
11437 }
11438
11439 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
11440 let key = ptr_of(h);
11441 if kind == day_spec::GestureKind::Pan {
11445 PAN_NODES.with(|t| t.insert(key, node));
11446 install_container_pan_monitor();
11447 return;
11448 }
11449 if kind == day_spec::GestureKind::Rotate {
11453 ROTATE_NODES.with(|t| t.insert(key, node));
11454 return;
11455 }
11456 if kind == day_spec::GestureKind::Hover {
11460 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
11464 HOVER_NODES.with(|t| t.insert(key, node));
11465 if first {
11466 install_tracking_area(h);
11467 }
11468 return;
11469 }
11470 let already = GESTURES.with(|m| {
11472 m.borrow()
11473 .get(&key)
11474 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
11475 });
11476 if already {
11477 return;
11478 }
11479 let mtm = self.mtm;
11480 let target = DayGesture::new(mtm, node, kind);
11481 let recognizer: Retained<NSGestureRecognizer> = unsafe {
11482 match kind {
11483 day_spec::GestureKind::Drag => {
11484 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
11485 NSPanGestureRecognizer::alloc(mtm),
11486 Some(&target),
11487 Some(sel!(fire:)),
11488 ))
11489 }
11490 day_spec::GestureKind::Pinch => Retained::into_super(
11491 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
11492 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
11493 Some(&target),
11494 Some(sel!(fire:)),
11495 ),
11496 ),
11497 _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
11498 NSClickGestureRecognizer::alloc(mtm),
11499 Some(&target),
11500 Some(sel!(fire:)),
11501 )),
11502 }
11503 };
11504 unsafe { h.addGestureRecognizer(&recognizer) };
11505 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
11506 }
11507
11508 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
11509 unsafe {
11510 if let Some(id) = &a11y.identifier {
11511 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
11512 }
11513 if let Some(label) = &a11y.label {
11514 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
11515 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
11516 } else {
11517 APP_LABELED.with(|t| t.remove(ptr_of(h)));
11518 }
11519 if let Some(hint) = &a11y.hint {
11520 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
11521 }
11522 if let Some(value) = &a11y.value {
11523 let ns = NSString::from_str(value);
11524 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
11525 }
11526 if let Some(role) = ns_role(a11y.role) {
11529 h.setAccessibilityRole(Some(role));
11530 }
11531 if a11y.role == day_spec::Role::Tab {
11532 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
11533 }
11534 if let Some(on) = a11y.selected {
11535 h.setAccessibilitySelected(on);
11536 }
11537 if a11y.hidden {
11543 h.setAccessibilityElement(false);
11544 h.setAccessibilityChildren(Some(&NSArray::new()));
11545 }
11546 }
11547 }
11548
11549 fn announce(&mut self, text: &str, urgent: bool) {
11553 use objc2_app_kit::{
11554 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
11555 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
11556 NSAccessibilityPriorityLevel,
11557 };
11558 let app = NSApplication::sharedApplication(self.mtm());
11559 let window = primary_content().and_then(|content| content.window());
11560 let element: &objc2::runtime::AnyObject = match &window {
11561 Some(window) => window,
11562 None => &app,
11563 };
11564 let priority = if urgent {
11566 NSAccessibilityPriorityLevel::High
11567 } else {
11568 NSAccessibilityPriorityLevel::Medium
11569 };
11570 let announcement = NSString::from_str(text);
11571 let priority = NSNumber::new_isize(priority.0);
11572 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
11573 unsafe {
11576 let user_info = NSDictionary::from_slices::<NSString>(
11577 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
11578 &values,
11579 );
11580 NSAccessibilityPostNotificationWithUserInfo(
11581 element,
11582 NSAccessibilityAnnouncementRequestedNotification,
11583 Some(&user_info),
11584 );
11585 }
11586 }
11587
11588 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
11589 unsafe {
11590 let role = h
11591 .accessibilityRole()
11592 .map_or(day_spec::Role::None, |r| day_role_from_ns(&r.to_string()));
11593 let picker = picker::read_native(h);
11596 day_spec::NativeSnapshot {
11597 found: true,
11598 role,
11599 label: h.accessibilityLabel().map(|s| s.to_string()),
11600 value: h.accessibilityValue().and_then(|v| {
11601 v.downcast_ref::<NSString>()
11602 .map(std::string::ToString::to_string)
11603 }),
11604 identifier: h
11605 .accessibilityIdentifier()
11606 .map(|s| s.to_string())
11607 .filter(|s| !s.is_empty()),
11608 text: match &picker {
11609 Some((text, _)) => text.clone(),
11610 None => native_text(h),
11611 },
11612 number: native_number(h),
11613 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
11614 match sw.state() {
11615 s if s == NSControlStateValueOn => Some(true),
11616 s if s == NSControlStateValueOff => Some(false),
11617 _ => None,
11619 }
11620 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
11621 BUTTON_SELECTED
11624 .with(|m| m.borrow().contains_key(&ptr_of(h)))
11625 .then(|| btn.state() == NSControlStateValueOn)
11626 } else {
11627 None
11628 },
11629 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
11632 (Some((_, on)), _) => *on,
11633 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
11634 (None, Some(c)) => Some(c.isEnabled()),
11635 (None, None) => None,
11636 },
11637 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
11639 frame: native_frame(h),
11640 }
11641 }
11642 }
11643
11644 fn request_frame(
11645 &mut self,
11646 host: &Handle,
11647 cb: day_spec::FrameCallback,
11648 ) -> day_spec::CancelFrame {
11649 frame::request(host, cb)
11650 }
11651
11652 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
11653 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
11654 unsafe { h.setNeedsDisplay(true) };
11655 }
11656 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
11657 NAV_STATE.with(|m| {
11658 let m = m.borrow();
11659 let Some(st) = m.get(&ptr_of(host)) else {
11660 return false;
11661 };
11662 if !matches!(
11665 st.presentation,
11666 NavPresentation::Split | NavPresentation::Rail
11667 ) {
11668 return false;
11669 }
11670 let item = &st.sidebar_item;
11671 let collapsed = unsafe { item.isCollapsed() };
11677 unsafe { item.setCollapsed(!collapsed) };
11678 true
11679 })
11680 }
11681
11682 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11683 let content = self.content.as_ref().ok_or("no window content")?;
11684 match self.shown_document_content(content) {
11685 Some(shown) => snapshot_view(&shown),
11686 None => snapshot_view(content),
11687 }
11688 }
11689
11690 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11696 use objc2::AllocAnyThread as _;
11697 let data = NSData::with_bytes(bytes);
11698 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11699 else {
11700 emit(
11701 WINDOW_NODE,
11702 Event::ImageDecoded {
11703 req,
11704 result: Err(day_spec::ImageError::Decode),
11705 },
11706 );
11707 return;
11708 };
11709 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11710 let info = day_spec::BitmapInfo {
11711 pixels: Size::new(w, h),
11712 scale: 1.0,
11715 format: day_spec::ImageFormat::sniff(bytes),
11716 has_alpha: unsafe { rep.hasAlpha() },
11717 };
11718 let image = unsafe {
11722 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11723 };
11724 unsafe { image.addRepresentation(&rep) };
11725 BITMAPS.with(|m| {
11726 m.borrow_mut().insert(
11727 id.0,
11728 AppKitBitmap {
11729 image,
11730 rep: Some(rep),
11731 info,
11732 },
11733 )
11734 });
11735 emit(
11736 WINDOW_NODE,
11737 Event::ImageDecoded {
11738 req,
11739 result: Ok(info),
11740 },
11741 );
11742 }
11743
11744 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11745 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11746 }
11747
11748 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11755 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11756 let mut out = day_spec::ImageProperties::default();
11757 let size = unsafe { rep.size() };
11758 if size.width > 0.0 {
11759 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11760 if (dpi - 72.0).abs() > 0.5 {
11763 out.dpi = Some(dpi);
11764 }
11765 }
11766 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11770 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11771 for key in &keys {
11772 let value: Option<Retained<objc2::runtime::AnyObject>> =
11773 unsafe { msg_send![&*exif, objectForKey: &*key] };
11774 let Some(value) = value else { continue };
11775 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11776 let (k, v) = (key.to_string(), text.to_string());
11777 match k.as_str() {
11778 "Orientation" => out.orientation = v.parse().ok(),
11779 "DateTimeOriginal" => out.created = Some(v.clone()),
11780 _ => {}
11781 }
11782 out.extra.push((k, v));
11785 }
11786 }
11787 Some(out)
11788 }
11789
11790 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11794 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11795 vec![Png, Jpeg, Tiff, Bmp, Gif]
11796 }
11797
11798 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11799 let result = encode_bitmap(id, spec);
11800 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11801 }
11802
11803 fn release_image(&mut self, id: day_spec::BitmapId) {
11804 release_bitmap(id);
11805 }
11806
11807 fn render_bitmap(
11817 &mut self,
11818 req: u64,
11819 id: day_spec::BitmapId,
11820 ops: &[DrawOp],
11821 size: Size,
11822 scale: f64,
11823 ) {
11824 let resources = Sendable(OffscreenResources::collect(ops));
11825 let ops = ops.to_vec();
11826 day_spec::offscreen::spawn(move || {
11827 let resources = resources;
11829 let painted = day_spec::ffi_guard::contain(
11830 Err(day_spec::ExportError::Failed(
11831 "the offscreen painter panicked".into(),
11832 )),
11833 || {
11834 let started = std::time::Instant::now();
11835 let painted = resources
11836 .0
11837 .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
11838 log::debug!(
11840 "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
11841 size.width * scale,
11842 size.height * scale,
11843 started.elapsed().as_secs_f64() * 1000.0,
11844 ops.len()
11845 );
11846 painted
11847 },
11848 );
11849 let painted = Sendable(painted);
11850 <AppKit as Platform>::post(Box::new(move || {
11851 let painted = painted;
11852 let result = painted.0.map(|cg_image| {
11853 let bitmap = bitmap_from_cgimage(&cg_image, scale);
11854 let info = bitmap.info;
11855 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11856 info
11857 });
11858 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11859 }));
11860 });
11861 }
11862
11863 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11864 let result = render_pdf_bytes(pages, info);
11865 emit(WINDOW_NODE, Event::PdfRendered { req, result });
11866 }
11867
11868 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11872 use day_spec::FontWeight as W;
11873 let mtm =
11874 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11875 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11876 let mut out = Vec::new();
11877 for family in &unsafe { manager.availableFontFamilies() } {
11878 let name = family.to_string();
11879 if name.starts_with('.') {
11880 continue;
11881 }
11882 let mut faces = Vec::new();
11883 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11884 for member in &members {
11885 if member.count() < 4 {
11886 continue;
11887 }
11888 let style = member
11889 .objectAtIndex(1)
11890 .downcast_ref::<NSString>()
11891 .map_or_default(std::string::ToString::to_string);
11892 let weight = member
11893 .objectAtIndex(2)
11894 .downcast_ref::<objc2_foundation::NSNumber>()
11895 .map_or(5, objc2_foundation::NSNumber::integerValue);
11896 let traits = member
11897 .objectAtIndex(3)
11898 .downcast_ref::<objc2_foundation::NSNumber>()
11899 .map_or(0, objc2_foundation::NSNumber::integerValue);
11900 let weight = match weight {
11901 ..=2 => W::UltraLight,
11902 3 => W::Thin,
11903 4 => W::Light,
11904 5 => W::Regular,
11905 6 => W::Medium,
11906 7 | 8 => W::Semibold,
11907 9 => W::Bold,
11908 10 | 11 => W::Heavy,
11909 _ => W::Black,
11910 };
11911 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
11913 name: if style.is_empty() {
11914 day_spec::FontFace::synthesized_name(weight, italic)
11915 } else {
11916 style
11917 },
11918 weight,
11919 italic,
11920 });
11921 }
11922 }
11923 out.push(day_spec::FontFamilyInfo {
11924 family: name,
11925 faces,
11926 });
11927 }
11928 out
11929 }
11930
11931 fn measure_text(
11934 &mut self,
11935 text: &str,
11936 size: f64,
11937 font: &day_spec::CanvasFont,
11938 ) -> Option<day_spec::TextMetrics> {
11939 let nsfont = canvas_nsfont(size, font);
11940 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11941 let ns = NSString::from_str(text);
11942 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11943 let unbounded = NSSize::new(f64::MAX, f64::MAX);
11947 let ink: NSRect = unsafe {
11948 msg_send![
11949 &ns,
11950 boundingRectWithSize: unbounded,
11951 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11952 attributes: &*attrs,
11953 ]
11954 };
11955 Some(day_spec::TextMetrics::from_baseline(
11956 sz.width,
11957 nsfont.ascender(),
11958 sz.height - nsfont.ascender(),
11959 nsfont.capHeight(),
11960 day_spec::Rect::new(
11961 ink.origin.x,
11962 -(ink.origin.y + ink.size.height),
11963 ink.size.width,
11964 ink.size.height,
11965 ),
11966 ))
11967 }
11968
11969 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11970 let content = self.content.as_ref().ok_or("no window content")?;
11971 match self.shown_document_content(content) {
11972 Some(shown) => snapshot_view_chrome(&shown),
11973 None => snapshot_view_chrome(content),
11974 }
11975 }
11976
11977 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11978 snapshot_view(host)
11979 }
11980
11981 fn open_window(
11982 &mut self,
11983 id: NodeId,
11984 options: &WindowOptions,
11985 kind: day_spec::WindowKind,
11986 ) -> day_spec::WindowOpenReply<Handle> {
11987 let prefs = kind.is_panel();
11988 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11989 if prefs {
11990 window.center();
11993 unsafe { window.setExcludedFromWindowsMenu(true) };
11994 } else {
11995 let from = match self.cascade {
12003 Some(p) => p,
12004 None => self.window.as_ref().map_or(NSPoint::new(0.0, 0.0), |w| {
12005 let f = w.frame();
12006 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
12007 unsafe { w.cascadeTopLeftFromPoint(top_left) }
12010 }),
12011 };
12012 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
12013 }
12014 window_chrome::place(&window, options.placement);
12015 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
12020 center_on_screen_of(&window, self.window.as_deref());
12021 }
12022 let _ = pin_below_title_bar(&window);
12025 if !options.start_hidden {
12026 window.makeKeyAndOrderFront(None);
12027 }
12028 mark_tree_needs_display(&content);
12031 self.secondary.push(SecondaryWin {
12032 window,
12033 delegate,
12034 content: content.clone(),
12035 });
12036 day_spec::WindowOpenReply::Open(content)
12037 }
12038
12039 fn native_window_tabs(&self) -> bool {
12040 true
12041 }
12042 fn group_windows(&mut self, hosts: &[Handle]) {
12043 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
12044 let Some(first) = windows.first() else {
12045 return;
12046 };
12047 unsafe {
12048 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
12049 }
12050 for window in windows.iter().skip(1) {
12052 unsafe {
12053 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
12054 }
12055 }
12056 if let Some(group) = first.tabGroup() {
12057 if !group.isTabBarVisible() {
12058 unsafe {
12059 first.toggleTabBar(None);
12060 }
12061 }
12062 for (i, window) in windows.iter().enumerate() {
12063 group.insertWindow_atIndex(window, i as isize);
12064 }
12065 }
12066 for window in &windows {
12069 if let Some(size) = pin_below_title_bar(window) {
12070 let node = window
12071 .delegate()
12072 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
12073 .and_then(|d| d.ivars().node)
12074 .unwrap_or(WINDOW_NODE);
12075 emit(node, Event::WindowResized(size));
12076 }
12077 }
12078 }
12079 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
12080 let Some(window) = self.ns_window_for(host) else {
12081 return Vec::new();
12082 };
12083 let windows = window.tabGroup().map(|g| g.windows());
12084 let Some(windows) = windows else {
12085 return Vec::new();
12086 };
12087 windows
12088 .iter()
12089 .filter_map(|window| {
12090 self.secondary
12091 .iter()
12092 .find(|w| std::ptr::eq(&raw const *w.window, &raw const *window))
12093 .and_then(|w| w.delegate.ivars().node)
12094 })
12095 .collect()
12096 }
12097
12098 fn close_window(&mut self, host: &Handle) {
12099 if let Some(w) = self
12102 .secondary
12103 .iter()
12104 .find(|w| ptr_of(&w.content) == ptr_of(host))
12105 {
12106 w.window.close();
12107 }
12108 }
12109
12110 fn focus_window(&mut self, host: &Handle) {
12111 if let Some(w) = self
12112 .secondary
12113 .iter()
12114 .find(|w| ptr_of(&w.content) == ptr_of(host))
12115 {
12116 w.window.makeKeyAndOrderFront(None);
12117 }
12118 }
12119
12120 fn fit_window(&mut self, host: &Handle, size: Size) {
12121 let Some(w) = self
12122 .secondary
12123 .iter()
12124 .find(|w| ptr_of(&w.content) == ptr_of(host))
12125 else {
12126 return;
12127 };
12128 unsafe {
12129 w.window
12133 .setContentSize(NSSize::new(size.width, size.height));
12134 let mask = w.window.styleMask();
12138 w.window
12139 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
12140 w.window.center();
12141 }
12142 center_on_screen_of(&w.window, self.window.as_deref());
12143 }
12144
12145 fn set_window_title(&mut self, host: &Handle, title: &str) {
12146 if let Some(w) = self
12147 .secondary
12148 .iter()
12149 .find(|w| ptr_of(&w.content) == ptr_of(host))
12150 {
12151 w.window.setTitle(&NSString::from_str(title));
12152 return;
12153 }
12154 if self
12158 .content
12159 .as_ref()
12160 .is_some_and(|c| ptr_of(c) == ptr_of(host))
12161 && let Some(w) = self.window.as_ref()
12162 {
12163 w.setTitle(&NSString::from_str(title));
12164 }
12165 }
12166
12167 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
12168 use day_spec::WindowChange as C;
12169 let Some(window) = self.ns_window_for(host) else {
12170 return;
12171 };
12172 match change {
12173 C::State(state) => set_ns_window_state(&window, *state),
12174 C::ContentProtected(on) => window.setSharingType(if *on {
12176 objc2_app_kit::NSWindowSharingType::None
12177 } else {
12178 objc2_app_kit::NSWindowSharingType::ReadOnly
12179 }),
12180 other => window_chrome::apply_property(&window, other),
12181 }
12182 }
12183
12184 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
12185 self.ns_window_for(host)
12186 .map(|w| window_chrome::frame_of(&w))
12187 }
12188
12189 fn monitors(&self) -> Vec<day_spec::Monitor> {
12190 window_chrome::monitors(self.mtm)
12191 }
12192
12193 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
12196
12197 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
12198 dock::set_app_items(self.mtm, items);
12199 }
12200
12201 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
12202 window_chrome::set_drag_region(h, drag);
12203 }
12204
12205 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
12206 status_item::set_items(self.mtm, items);
12207 }
12208
12209 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
12210 status_item::set_progress(self.mtm, progress);
12211 }
12212
12213 fn set_dock_visible(&mut self, visible: bool) {
12214 status_item::set_dock_visible(self.mtm, visible);
12215 }
12216
12217 fn set_keep_running(&mut self, keep: bool) {
12218 status_item::set_keep_running(keep);
12219 }
12220
12221 fn quit_app(&mut self) {
12222 let app = NSApplication::sharedApplication(self.mtm);
12223 unsafe { app.terminate(None) };
12224 }
12225
12226 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
12227 use present::PresentSpec;
12228 let mtm = self.mtm;
12229 let app = NSApplication::sharedApplication(mtm);
12233 let key = app.keyWindow().filter(|k| {
12234 let mut owner = k.clone();
12235 while let Some(parent) = owner.sheetParent() {
12236 owner = parent;
12237 }
12238 self.window
12239 .as_deref()
12240 .is_some_and(|w| std::ptr::eq(w, &raw const *owner))
12241 || self
12242 .secondary
12243 .iter()
12244 .any(|s| std::ptr::eq(&raw const *s.window, &raw const *owner))
12245 });
12246 let Some(mut window) = key.or_else(|| self.window.clone()) else {
12247 emit(
12248 WINDOW_NODE,
12249 Event::PresentResult {
12250 req,
12251 result: present::PresentResult::Dismissed,
12252 },
12253 );
12254 return;
12255 };
12256 while let Some(sheet) = window.attachedSheet() {
12258 window = sheet;
12259 }
12260 match spec {
12262 PresentSpec::OpenFile {
12263 filters, multiple, ..
12264 } => {
12265 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12266 unsafe {
12267 panel.setCanChooseFiles(true);
12268 panel.setCanChooseDirectories(false);
12269 panel.setAllowsMultipleSelection(*multiple);
12270 panel.setMessage(Some(&NSString::from_str(spec.title())));
12271 }
12272 apply_allowed_file_types(&panel, filters);
12273 let p = panel.clone();
12274 let handler: block2::RcBlock<dyn Fn(isize)> =
12277 block2::RcBlock::new(move |resp: isize| {
12278 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12279 });
12280 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12281 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12282 return;
12283 }
12284 PresentSpec::OpenFolder { .. } => {
12286 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12287 unsafe {
12288 panel.setCanChooseFiles(false);
12289 panel.setCanChooseDirectories(true);
12290 panel.setCanCreateDirectories(true);
12291 panel.setAllowsMultipleSelection(false);
12292 panel.setMessage(Some(&NSString::from_str(spec.title())));
12293 }
12294 let p = panel.clone();
12295 let handler: block2::RcBlock<dyn Fn(isize)> =
12296 block2::RcBlock::new(move |resp: isize| {
12297 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12298 });
12299 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12300 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12301 return;
12302 }
12303 PresentSpec::SaveFile { suggested_name, .. } => {
12304 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
12305 unsafe {
12306 panel.setMessage(Some(&NSString::from_str(spec.title())));
12307 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
12308 }
12309 apply_allowed_file_types(&panel, spec.filters());
12310 let p = panel.clone();
12311 let handler: block2::RcBlock<dyn Fn(isize)> =
12312 block2::RcBlock::new(move |resp: isize| {
12313 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
12315 });
12316 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12317 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
12318 return;
12319 }
12320 _ => {}
12321 }
12322 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
12323 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
12324 if let Some(msg) = spec.message() {
12325 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
12326 }
12327 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
12329 PresentSpec::Dialog { buttons, .. } => {
12330 if buttons
12331 .iter()
12332 .any(|b| b.role == present::ButtonRole::Destructive)
12333 {
12334 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
12335 }
12336 for b in buttons {
12337 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
12338 }
12339 block2::RcBlock::new(move |resp: isize| {
12340 ffi_guard::contain((), || {
12341 let idx = resp - 1000;
12343 emit(
12344 WINDOW_NODE,
12345 Event::PresentResult {
12346 req,
12347 result: present::PresentResult::Button(idx as i64),
12348 },
12349 );
12350 PRESENT_ALERTS.with(|m| {
12351 m.borrow_mut().remove(&req);
12352 });
12353 });
12354 })
12355 }
12356 PresentSpec::Prompt {
12357 placeholder,
12358 initial,
12359 ok,
12360 cancel,
12361 ..
12362 } => {
12363 let tf = unsafe { NSTextField::new(mtm) };
12364 unsafe {
12365 tf.setFrame(NSRect::new(
12366 NSPoint::new(0.0, 0.0),
12367 NSSize::new(260.0, 24.0),
12368 ));
12369 tf.setEditable(true);
12370 tf.setBezeled(true);
12371 tf.setStringValue(&NSString::from_str(initial));
12372 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
12373 alert.setAccessoryView(Some(&tf));
12374 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
12377 block2::RcBlock::new(move |resp: isize| {
12378 ffi_guard::contain((), || {
12379 let result = if resp == 1000 {
12380 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
12381 } else {
12382 present::PresentResult::Dismissed
12383 };
12384 emit(WINDOW_NODE, Event::PresentResult { req, result });
12385 PRESENT_ALERTS.with(|m| {
12386 m.borrow_mut().remove(&req);
12387 });
12388 });
12389 })
12390 }
12391 PresentSpec::OpenFile { .. }
12393 | PresentSpec::OpenFolder { .. }
12394 | PresentSpec::SaveFile { .. } => unreachable!(),
12395 };
12396 unsafe {
12397 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
12398 }
12399 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
12400 }
12401
12402 fn dismiss(&mut self, req: u64) {
12403 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
12406 if let Some(alert) = alert {
12407 let sheet = alert.window();
12408 if let Some(parent) = sheet.sheetParent() {
12409 unsafe { parent.endSheet(&sheet) };
12410 }
12411 }
12412 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
12414 if let Some(panel) = panel
12415 && let Some(parent) = panel.sheetParent()
12416 {
12417 unsafe { parent.endSheet(&panel) };
12418 }
12419 }
12420
12421 fn application_handlers(
12422 &mut self,
12423 query: &day_spec::applications::HandlerQuery,
12424 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
12425 {
12426 applications::handlers(query)
12427 }
12428
12429 fn open_url_with_application(
12430 &mut self,
12431 url: &str,
12432 application: &str,
12433 completion: day_spec::applications::OpenApplicationCompletion,
12434 ) {
12435 applications::open(url, application, completion);
12436 }
12437
12438 fn share_support(&self) -> day_spec::Support {
12439 day_spec::Support::Native
12440 }
12441 fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
12442 use objc2::{msg_send, runtime::AnyObject};
12443 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
12444 let Some(mtm) = objc2::MainThreadMarker::new() else {
12445 return false;
12446 };
12447 let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
12448 return false;
12449 };
12450 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
12451 let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
12452 return false;
12453 };
12454 unsafe {
12455 let items = NSArray::from_retained_slice(&[url]);
12456 let picker: objc2::rc::Allocated<AnyObject> =
12457 msg_send![objc2::class!(NSSharingServicePicker), alloc];
12458 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
12459 let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
12460 actions: spec.actions.clone(),
12461 });
12462 let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
12463 let _: () = msg_send![&*picker, setDelegate: &*delegate];
12464 let (view, rect, edge) = if let Some(view) = anchor {
12467 (view.clone(), view.bounds(), 1usize)
12468 } else {
12469 let bounds = window_view.bounds();
12470 let y = if window_view.isFlipped() {
12471 30.0
12472 } else {
12473 bounds.size.height - 30.0
12474 };
12475 let rect = NSRect::new(
12476 NSPoint::new(bounds.size.width - 30.0, y),
12477 NSSize::new(1.0, 1.0),
12478 );
12479 (window_view, rect, 3usize)
12480 };
12481 let _: () =
12482 msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
12483 self.sharing = Some(picker);
12485 self.sharing_delegate = Some(delegate);
12486 }
12487 true
12488 }
12489 fn open_url(&mut self, url: &str) {
12490 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
12493 if let Some(nsurl) = nsurl {
12494 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
12495 }
12496 }
12497}
12498
12499#[allow(deprecated)]
12502fn apply_allowed_file_types(
12503 panel: &objc2_app_kit::NSSavePanel,
12504 filters: &[day_spec::present::FileFilter],
12505) {
12506 let exts: Vec<Retained<NSString>> = filters
12507 .iter()
12508 .flat_map(|f| f.extensions.iter())
12509 .map(|e| NSString::from_str(e))
12510 .collect();
12511 if !exts.is_empty() {
12512 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
12513 let arr = objc2_foundation::NSArray::from_slice(&refs);
12514 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
12515 }
12516}
12517
12518fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
12522 let mut paths = Vec::new();
12523 if resp == 1 {
12524 for url in &unsafe { panel.URLs() } {
12525 if let Some(p) = unsafe { url.path() } {
12526 paths.push(p.to_string());
12527 }
12528 }
12529 }
12530 let result = if paths.is_empty() {
12531 present::PresentResult::Dismissed
12532 } else {
12533 present::PresentResult::Files(paths)
12534 };
12535 emit(WINDOW_NODE, Event::PresentResult { req, result });
12536 PRESENT_PANELS.with(|m| {
12537 m.borrow_mut().remove(&req);
12538 });
12539}
12540
12541fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
12543 let result = if resp == 1 {
12544 unsafe { panel.URL() }
12545 .and_then(|url| unsafe { url.path() })
12546 .map_or(present::PresentResult::Dismissed, |p| {
12547 present::PresentResult::Files(vec![p.to_string()])
12548 })
12549 } else {
12550 present::PresentResult::Dismissed
12551 };
12552 emit(WINDOW_NODE, Event::PresentResult { req, result });
12553 PRESENT_PANELS.with(|m| {
12554 m.borrow_mut().remove(&req);
12555 });
12556}
12557
12558impl Platform for AppKit {
12559 const TARGET: &'static str = "macos-appkit";
12560 const TOOLKIT: &'static str = "appkit";
12561
12562 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
12563 let mtm = self.mtm;
12564 self.app_name = options
12568 .app_name
12569 .clone()
12570 .unwrap_or_else(|| options.title.clone());
12571 unsafe {
12580 objc2_foundation::NSProcessInfo::processInfo()
12581 .setProcessName(&NSString::from_str(&self.app_name));
12582 let bundle = objc2_foundation::NSBundle::mainBundle();
12583 let info: Option<Retained<objc2_foundation::NSDictionary>> =
12584 msg_send![&bundle, infoDictionary];
12585 if let Some(info) = info {
12586 let key = NSString::from_str("CFBundleName");
12587 let value = NSString::from_str(&self.app_name);
12588 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
12592 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
12593 }
12594 }
12595 }
12596 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
12601 unsafe {
12602 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
12603 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
12604 .into_super()
12605 .into_super()
12606 .into_super();
12607 let dict = NSDictionary::from_retained_objects(
12608 &[
12609 &*NSString::from_str("AppleTextDirection"),
12610 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
12611 ],
12612 &[yes.clone(), yes],
12613 );
12614 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
12615 }
12616 }
12617 let app = NSApplication::sharedApplication(mtm);
12618 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
12621 || unsafe {
12622 let bundle = objc2_foundation::NSBundle::mainBundle();
12623 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
12624 &bundle,
12625 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
12626 ];
12627 value.is_some_and(|v| {
12628 let on: bool = msg_send![&v, boolValue];
12629 on
12630 })
12631 };
12632 app.setActivationPolicy(if menu_bar_app {
12633 NSApplicationActivationPolicy::Accessory
12634 } else {
12635 NSApplicationActivationPolicy::Regular
12636 });
12637 let document_delegate = documents::delegate(mtm);
12638 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
12639 if let Ok(theme) = std::env::var("DAY_THEME") {
12642 let name = match theme.as_str() {
12643 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12644 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12645 _ => None,
12646 };
12647 if let Some(name) = name {
12648 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
12649 unsafe { app.setAppearance(appearance.as_deref()) };
12650 }
12651 }
12652 register_bundled_fonts();
12654
12655 let app_name = self.app_name.clone();
12659 install_main_menu(mtm, &app, &app_name);
12660 install_lifecycle_observers();
12662 install_appearance_observer();
12663 install_reduce_motion_observer();
12664
12665 let (window, delegate, content) = self.make_window(&options, false, None);
12666 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
12670 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12671 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12672 _ => None,
12673 };
12674 if let Some(name) = appearance_name
12675 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
12676 {
12677 window.setAppearance(Some(&appearance));
12678 }
12679 std::mem::forget(delegate);
12682
12683 self.window = Some(window.clone());
12684 self.content = Some(content.clone());
12685 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
12686
12687 let layout = pin_below_title_bar(&window)
12689 .unwrap_or(Size::new(options.size.width, options.size.height));
12690 ready(self, content, layout);
12691
12692 if day_core::windows::new_window_action_id() == 0
12696 && options.tabbing == day_spec::WindowTabbing::Automatic
12697 {
12698 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
12699 }
12700 if !day_core::has_app_menu() {
12705 install_main_menu(mtm, &app, &app_name);
12706 }
12707
12708 let deterministic =
12716 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
12717 let autosave = NSString::from_str("day.main");
12718 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
12719 window.center();
12720 window_chrome::place(&window, options.placement);
12722 }
12723 if let Some(screen) = capture_screen(mtm) {
12727 let (visible, frame) = (screen.visibleFrame(), window.frame());
12728 window.setFrameOrigin(NSPoint::new(
12729 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12730 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12731 ));
12732 }
12733 if !deterministic {
12734 unsafe { window.setFrameAutosaveName(&autosave) };
12735 }
12736 if !options.start_hidden {
12737 window.makeKeyAndOrderFront(None);
12738 app.activate();
12739 }
12740 if let Some(content) = window.contentView() {
12745 mark_tree_needs_display(&content);
12746 }
12747 if std::env::var_os("DAY_DUMP").is_some() {
12748 std::thread::spawn(|| {
12749 std::thread::sleep(std::time::Duration::from_millis(2000));
12750 Self::post(Box::new(|| {
12751 if let Some(content) = primary_content() {
12753 let desc: Retained<NSString> =
12754 unsafe { msg_send![&*content, _subtreeDescription] };
12755 log::warn!("{desc}");
12756 }
12757 }));
12758 });
12759 }
12760 app.run();
12761 }
12762
12763 fn post(f: Box<dyn FnOnce() + Send>) {
12764 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12767 }
12768
12769 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12770 let when =
12774 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12775 .unwrap_or(dispatch2::DispatchTime::FOREVER);
12776 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12777 ffi_guard::contain((), f);
12778 }) {
12779 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12780 }
12781 }
12782
12783 fn locale_hints(&self) -> Vec<String> {
12784 objc2_foundation::NSLocale::preferredLanguages()
12787 .iter()
12788 .map(|s| s.to_string())
12789 .collect()
12790 }
12791}
12792
12793unsafe extern "C" {
12798 fn CGWindowListCreateImage(
12799 bounds: objc2_core_foundation::CGRect,
12800 list_option: u32,
12801 window_id: u32,
12802 image_option: u32,
12803 ) -> *mut objc2_core_graphics::CGImage;
12804}
12805
12806const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12809const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12812
12813fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12820 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12821 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12822 objc2_app_kit::NSColorRenderingIntent::Default,
12823 );
12824 let rep = srgb.as_deref().unwrap_or(rep);
12825 let data = unsafe {
12826 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12827 }
12828 .ok_or("png encode failed")?;
12829 Ok(data.to_vec())
12830}
12831
12832fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12845 let window = content.window().ok_or("view is not in a window")?;
12846 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12849 return snapshot_via_window_server(&sheet, chrome);
12850 }
12851 let number = window.windowNumber();
12852 if number <= 0 {
12853 return Err(format!("window {number} is not on screen"));
12854 }
12855 unsafe { content.layoutSubtreeIfNeeded() };
12862 window.displayIfNeeded();
12863 CATransaction::flush();
12864 let null_rect = objc2_core_foundation::CGRect::new(
12866 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12867 objc2_core_foundation::CGSize::new(0.0, 0.0),
12868 );
12869 let shot = unsafe {
12870 CGWindowListCreateImage(
12871 null_rect,
12872 CG_WINDOW_LIST_INCLUDING_WINDOW,
12873 number as u32,
12874 CG_WINDOW_IMAGE_IGNORE_FRAMING,
12875 )
12876 };
12877 if shot.is_null() {
12878 return Err("the window server has no image for this window".into());
12879 }
12880 let shot = unsafe {
12883 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12884 };
12885
12886 if chrome {
12889 let rep = unsafe {
12890 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12891 objc2_app_kit::NSBitmapImageRep::alloc(),
12892 &shot,
12893 )
12894 };
12895 return png_of_rep(&rep);
12896 }
12897
12898 let frame = window.frame();
12902 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12903 return Err("zero-size window".into());
12904 }
12905 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12906 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12909 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12910 let crop = objc2_core_foundation::CGRect::new(
12911 objc2_core_foundation::CGPoint::new(
12912 (in_window.origin.x * scale).round(),
12913 (from_top * scale).round(),
12914 ),
12915 objc2_core_foundation::CGSize::new(
12916 (in_window.size.width * scale).round(),
12917 (in_window.size.height * scale).round(),
12918 ),
12919 );
12920 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12921 .ok_or("crop to the content view failed")?;
12922 let rep = unsafe {
12923 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12924 objc2_app_kit::NSBitmapImageRep::alloc(),
12925 &cropped,
12926 )
12927 };
12928 png_of_rep(&rep)
12929}
12930
12931fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12941 let [x, y, w, h] = base;
12942 let (sw, sh) = (w * t.sx, h * t.sy);
12943 let frame = NSRect::new(
12944 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12945 NSSize::new(sw, sh),
12946 );
12947 unsafe {
12948 v.setFrameCenterRotation(0.0);
12951 v.setFrame(frame);
12952 v.setBoundsSize(NSSize::new(w, h));
12953 if t.rotate_deg != 0.0 {
12954 v.setFrameCenterRotation(t.rotate_deg);
12955 }
12956 }
12957}
12958
12959fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12960 let modal = content
12961 .window()
12962 .and_then(|w| w.attachedSheet())
12963 .and_then(|s| s.contentView());
12964 let content = modal.as_deref().unwrap_or(content);
12965 match snapshot_via_window_server(content, false) {
12966 Ok(bytes) => Ok(bytes),
12967 Err(_) => snapshot_view_cache(content),
12968 }
12969}
12970
12971fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12979 let modal = content
12980 .window()
12981 .and_then(|w| w.attachedSheet())
12982 .and_then(|s| s.contentView());
12983 let content = modal.as_deref().unwrap_or(content);
12984 match snapshot_via_window_server(content, true) {
12985 Ok(bytes) => Ok(bytes),
12986 Err(_) => snapshot_view_cache(content),
12987 }
12988}
12989
12990fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12994 let bounds = content.bounds();
12995 let rep =
12996 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12997 let ctx =
13001 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
13002 NSGraphicsContext::saveGraphicsState_class();
13003 NSGraphicsContext::setCurrentContext(Some(&ctx));
13004 content
13005 .effectiveAppearance()
13006 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
13007 NSColor::windowBackgroundColor().setFill();
13008 objc2_app_kit::NSRectFill(bounds);
13009 }));
13010 NSGraphicsContext::restoreGraphicsState_class();
13011 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
13012 png_of_rep(&rep)
13013}
13014
13015fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
13021 let Some(screen) = primary.and_then(objc2_app_kit::NSWindow::screen) else {
13022 return;
13023 };
13024 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
13025 return;
13026 }
13027 let (visible, frame) = (screen.visibleFrame(), window.frame());
13028 window.setFrameOrigin(NSPoint::new(
13029 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
13030 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
13031 ));
13032}
13033
13034fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
13035 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
13036 .ok()?
13037 .trim()
13038 .parse()
13039 .ok()?;
13040 let key = NSString::from_str("NSScreenNumber");
13041 objc2_app_kit::NSScreen::screens(mtm)
13042 .into_iter()
13043 .find(|screen| {
13044 let number: Option<Retained<objc2_foundation::NSNumber>> =
13045 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
13046 number.is_some_and(|n| n.unsignedIntValue() == wanted)
13047 })
13048}
13049
13050fn mark_tree_needs_display(view: &NSView) {
13052 view.setNeedsDisplay(true);
13053 for sub in view.subviews() {
13054 mark_tree_needs_display(&sub);
13055 }
13056}
13057
13058#[must_use]
13063pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
13064 phase.is_universal()
13065}
13066
13067fn install_appearance_observer() {
13073 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
13074 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
13075 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13076 dispatch2::DispatchQueue::main()
13077 .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
13078 });
13079 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
13080 let token = unsafe {
13081 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13082 };
13083 std::mem::forget(token);
13084 let center = objc2_foundation::NSNotificationCenter::defaultCenter();
13086 let name = NSString::from_str("NSSystemColorsDidChangeNotification");
13087 let token = unsafe {
13088 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13089 };
13090 std::mem::forget(token);
13091}
13092
13093fn install_reduce_motion_observer() {
13101 use objc2_foundation::NSNotification;
13102 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
13103 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13104 dispatch2::DispatchQueue::main()
13105 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
13106 });
13107 let token = unsafe {
13108 center.addObserverForName_object_queue_usingBlock(
13109 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
13110 None,
13111 None,
13112 &block,
13113 )
13114 };
13115 std::mem::forget(token);
13116}
13117
13118fn install_lifecycle_observers() {
13121 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
13122 let center = unsafe { NSNotificationCenter::defaultCenter() };
13123 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
13124 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13125 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
13126 });
13127 let token = unsafe {
13128 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
13129 };
13130 std::mem::forget(token); };
13132 unsafe {
13133 observe(
13134 NSApplicationDidBecomeActiveNotification,
13135 day_spec::Lifecycle::DidBecomeActive,
13136 );
13137 observe(
13138 NSApplicationWillResignActiveNotification,
13139 day_spec::Lifecycle::WillResignActive,
13140 );
13141 observe(
13142 NSApplicationWillTerminateNotification,
13143 day_spec::Lifecycle::WillTerminate,
13144 );
13145 observe(
13149 NSApplicationWillTerminateNotification,
13150 day_spec::Lifecycle::DidExit,
13151 );
13152 }
13153}
13154
13155day_localization_ui::locales!();
13156
13157fn install_application_menu(
13160 mtm: MainThreadMarker,
13161 menubar: &NSMenu,
13162 title: &str,
13163 about: Option<day_spec::MenuItem>,
13164 updates: Option<day_spec::MenuItem>,
13165 prefs: Option<day_spec::MenuItem>,
13166 quit: Option<day_spec::MenuItem>,
13167) -> Retained<NSMenu> {
13168 use day_spec::{MenuItem as M, MenuRole as R};
13169 let app = NSApplication::sharedApplication(mtm);
13170 let standard = |role, label| M::Action {
13171 id: None,
13172 action: 0,
13173 label,
13174 shortcut: None,
13175 enabled: true,
13176 checked: None,
13177 role: Some(role),
13178 icon: None,
13179 };
13180 let mut about =
13181 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
13182 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
13183 for (item, title) in [
13184 (&mut about, res::str::about_app(title).format()),
13185 (&mut quit, res::str::quit_app(title).format()),
13186 ] {
13187 if let M::Action { label, .. } = item {
13188 *label = title;
13189 }
13190 }
13191 if let M::Action { action, .. } = &mut about
13194 && *action == 0
13195 {
13196 *action = day_core::windows::about_action_id();
13197 }
13198 let updates_id = day_core::windows::check_for_updates_action_id();
13201 let updates = updates.or_else(|| {
13202 (updates_id != 0).then(|| {
13203 standard(
13204 R::CheckForUpdates,
13205 day_localization::t(day_localization::key::day_check_for_updates),
13206 )
13207 })
13208 });
13209 let mut head = vec![about];
13210 if let Some(mut updates) = updates {
13211 if let M::Action { action, .. } = &mut updates
13212 && *action == 0
13213 {
13214 *action = updates_id;
13215 }
13216 head.push(updates);
13217 }
13218 head.push(M::Separator);
13219 let menu = build_ns_menu(mtm, title, &head);
13220 if let Some(mut prefs) = prefs {
13221 if let M::Action { label, .. } = &mut prefs {
13222 *label = res::str::settings().format();
13223 }
13224 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
13225 for item in section.itemArray() {
13226 section.removeItem(&item);
13227 menu.addItem(&item);
13228 }
13229 }
13230 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
13233 if let Some(parent) = unsafe { services.supermenu() } {
13234 let index = parent.indexOfItemWithSubmenu(Some(&services));
13235 if index >= 0 {
13236 parent.itemAtIndex(index).unwrap().setSubmenu(None);
13237 }
13238 }
13239 let services_item = NSMenuItem::new(mtm);
13240 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
13241 services_item.setSubmenu(Some(&services));
13242 menu.addItem(&services_item);
13243 menu.addItem(&NSMenuItem::separatorItem(mtm));
13244 for (label, selector, shortcut) in [
13245 (
13246 res::str::hide_app(title).format(),
13247 sel!(hide:),
13248 Some(day_spec::Shortcut::primary("h")),
13249 ),
13250 (
13251 res::str::hide_others().format(),
13252 sel!(hideOtherApplications:),
13253 Some(day_spec::Shortcut::primary("h").alt()),
13254 ),
13255 (
13256 res::str::show_all().format(),
13257 sel!(unhideAllApplications:),
13258 None,
13259 ),
13260 ] {
13261 let item = unsafe {
13262 NSMenuItem::initWithTitle_action_keyEquivalent(
13263 NSMenuItem::alloc(mtm),
13264 &NSString::from_str(&label),
13265 Some(selector),
13266 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
13267 )
13268 };
13269 if let Some(shortcut) = shortcut {
13270 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
13271 }
13272 unsafe { item.setTarget(Some(&app)) };
13274 menu.addItem(&item);
13275 }
13276 menu.addItem(&NSMenuItem::separatorItem(mtm));
13277 let section = build_ns_menu(mtm, title, &[quit]);
13278 let quit = section.itemAtIndex(0).unwrap();
13279 section.removeItem(&quit);
13280 menu.addItem(&quit);
13281 let item = NSMenuItem::new(mtm);
13282 item.setSubmenu(Some(&menu));
13283 menubar.addItem(&item);
13284 services
13285}
13286
13287fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
13290 let menubar = NSMenu::new(mtm);
13291
13292 let prefs_id = day_core::windows::preferences_action_id();
13293 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
13294 id: None,
13295 action: prefs_id,
13296 label: res::str::settings().format(),
13297 shortcut: None,
13298 enabled: true,
13299 checked: None,
13300 role: Some(day_spec::MenuRole::Preferences),
13301 icon: None,
13302 });
13303 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
13304
13305 let new_window_id = day_core::windows::new_window_action_id();
13310 if new_window_id != 0 {
13311 let file_item = NSMenuItem::new(mtm);
13312 let file_menu = unsafe {
13313 NSMenu::initWithTitle(
13314 NSMenu::alloc(mtm),
13315 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
13316 )
13317 };
13318 let new_window = unsafe {
13319 NSMenuItem::initWithTitle_action_keyEquivalent(
13320 NSMenuItem::alloc(mtm),
13321 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
13322 Some(sel!(fire:)),
13323 &NSString::from_str("n"),
13324 )
13325 };
13326 let target = menu_target(mtm);
13327 let tobj: &objc2::runtime::AnyObject = target.as_ref();
13328 unsafe { new_window.setTarget(Some(tobj)) };
13329 new_window.setTag(new_window_id as isize);
13330 file_menu.addItem(&new_window);
13331 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
13332 let close = unsafe {
13334 NSMenuItem::initWithTitle_action_keyEquivalent(
13335 NSMenuItem::alloc(mtm),
13336 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
13337 Some(sel!(performClose:)),
13338 &NSString::from_str("w"),
13339 )
13340 };
13341 file_menu.addItem(&close);
13342 file_item.setSubmenu(Some(&file_menu));
13343 menubar.addItem(&file_item);
13344 }
13345
13346 let edit_item = NSMenuItem::new(mtm);
13347 let edit_menu = unsafe {
13348 NSMenu::initWithTitle(
13349 NSMenu::alloc(mtm),
13350 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
13351 )
13352 };
13353 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13354 let item = unsafe {
13355 NSMenuItem::initWithTitle_action_keyEquivalent(
13356 NSMenuItem::alloc(mtm),
13357 &NSString::from_str(&day_localization::t(key)),
13358 Some(action),
13359 &NSString::from_str(accel),
13360 )
13361 };
13362 edit_menu.addItem(&item);
13363 };
13364 add("day_undo", sel!(undo:), "z");
13365 add("day_redo", sel!(redo:), "Z");
13366 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
13367 add("day_cut", sel!(cut:), "x");
13368 add("day_copy", sel!(copy:), "c");
13369 add("day_paste", sel!(paste:), "v");
13370 add("day_select_all", sel!(selectAll:), "a");
13371 edit_item.setSubmenu(Some(&edit_menu));
13372 menubar.addItem(&edit_item);
13373
13374 install_windows_menu(mtm, app, &menubar);
13375
13376 app.setMainMenu(Some(&menubar));
13377 unsafe { app.setServicesMenu(Some(&services)) };
13378}
13379
13380fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
13385 let menu = unsafe {
13386 NSMenu::initWithTitle(
13387 NSMenu::alloc(mtm),
13388 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
13389 )
13390 };
13391 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13392 let item = unsafe {
13393 NSMenuItem::initWithTitle_action_keyEquivalent(
13394 NSMenuItem::alloc(mtm),
13395 &NSString::from_str(&day_localization::t(key)),
13396 Some(action),
13397 &NSString::from_str(accel),
13398 )
13399 };
13400 menu.addItem(&item);
13401 };
13402 add("day_minimize", sel!(performMiniaturize:), "m");
13403 add("day_zoom", sel!(performZoom:), "");
13404 menu.addItem(&NSMenuItem::separatorItem(mtm));
13405 add("day_bring_all_front", sel!(arrangeInFront:), "");
13406 let item = NSMenuItem::new(mtm);
13407 item.setTitle(&NSString::from_str(&day_localization::t(
13408 day_localization::key::day_window,
13409 )));
13410 item.setSubmenu(Some(&menu));
13411 menubar.addItem(&item);
13412 unsafe { app.setWindowsMenu(Some(&menu)) };
13413}
13414
13415fn extract_app_role(
13418 items: &mut Vec<day_spec::MenuItem>,
13419 role: day_spec::MenuRole,
13420) -> Option<day_spec::MenuItem> {
13421 use day_spec::MenuItem as M;
13422 let mut found = None;
13423 let mut remaining = Vec::new();
13424 for mut item in items.drain(..) {
13425 match &mut item {
13426 M::Action { role: Some(r), .. } if *r == role => {
13427 found.get_or_insert(item);
13428 continue;
13429 }
13430 M::Submenu { items, .. } => {
13431 let nested = extract_app_role(items, role);
13432 if found.is_none() {
13433 found = nested;
13434 }
13435 if items.is_empty() {
13436 continue;
13437 }
13438 }
13439 M::Separator
13440 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
13441 {
13442 continue;
13443 }
13444 _ => {}
13445 }
13446 remaining.push(item);
13447 }
13448 while matches!(remaining.last(), Some(M::Separator)) {
13449 remaining.pop();
13450 }
13451 *items = remaining;
13452 found
13453}
13454
13455fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
13457 items.iter().any(|it| match it {
13458 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
13459 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
13460 day_spec::MenuItem::Separator => false,
13461 })
13462}
13463
13464define_class!(
13470 #[unsafe(super(NSObject))]
13471 #[thread_kind = MainThreadOnly]
13472 #[name = "DayMenuTarget"]
13473 #[ivars = ()]
13474 struct DayMenuTarget;
13475
13476 unsafe impl NSObjectProtocol for DayMenuTarget {}
13477
13478 impl DayMenuTarget {
13479 #[unsafe(method(fire:))]
13480 fn fire(&self, sender: &NSMenuItem) {
13481 ffi_guard::contain((), || {
13482 let id = sender.tag() as u64;
13483 if id != 0 {
13484 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
13485 }
13486 });
13487 }
13488 }
13489);
13490
13491pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
13500 let content = window.contentView()?;
13501 let full = content.frame().size;
13502 let layout = unsafe { window.contentLayoutRect() }.size;
13503 let top = (full.height - layout.height).max(0.0);
13504 if window_chrome::is_overlay(window) {
13508 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
13509 window_chrome::report_title_bar_inset(window, top);
13510 return Some(Size::new(full.width, full.height));
13511 }
13512 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
13513 Some(Size::new(full.width, (full.height - top).max(0.0)))
13514}
13515
13516fn native_text(h: &NSView) -> Option<String> {
13520 if h.downcast_ref::<NSSecureTextField>().is_some() {
13521 return None;
13522 }
13523 if let Some(tf) = h.downcast_ref::<NSTextField>() {
13524 return Some(tf.stringValue().to_string());
13526 }
13527 if let Some(btn) = h.downcast_ref::<NSButton>() {
13528 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
13529 return None;
13530 }
13531 return Some(btn.title().to_string());
13532 }
13533 let sv = h.downcast_ref::<NSScrollView>()?;
13535 let doc = sv.documentView()?;
13536 let tv = doc.downcast_ref::<NSTextView>()?;
13537 Some(tv.string().to_string())
13538}
13539
13540fn native_number(h: &NSView) -> Option<f64> {
13543 if let Some(sl) = h.downcast_ref::<NSSlider>() {
13544 return Some(sl.doubleValue());
13545 }
13546 let pi = h.downcast_ref::<NSProgressIndicator>()?;
13547 (!pi.isIndeterminate()).then(|| pi.doubleValue())
13548}
13549
13550fn native_frame(h: &NSView) -> Option<Rect> {
13554 let content = h.window()?.contentView()?;
13555 let r = h.convertRect_toView(h.bounds(), Some(&content));
13556 let y = if content.isFlipped() {
13557 r.origin.y
13558 } else {
13559 let b = content.bounds();
13560 b.origin.y + b.size.height - (r.origin.y + r.size.height)
13561 };
13562 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
13563}
13564
13565fn title_bar_inset(content: &NSView) -> f64 {
13567 (-content.bounds().origin.y).max(0.0)
13568}
13569
13570fn primary_content() -> Option<Retained<NSView>> {
13571 PRIMARY_CONTENT.with(|c| c.borrow().clone())
13572}
13573
13574fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
13575 MENU_TARGET.with(|t| {
13576 t.borrow_mut()
13577 .get_or_insert_with(|| {
13578 let this = DayMenuTarget::alloc(mtm).set_ivars(());
13579 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
13580 obj
13581 })
13582 .clone()
13583 })
13584}
13585
13586fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
13587 use objc2_app_kit::NSEventModifierFlags as F;
13588 let mut m = F::empty();
13589 if s.primary {
13590 m |= F::Command;
13591 }
13592 if s.shift {
13593 m |= F::Shift;
13594 }
13595 if s.alt {
13596 m |= F::Option;
13597 }
13598 if s.control {
13599 m |= F::Control;
13600 }
13601 m
13602}
13603
13604fn ns_key_equivalent(key: &str) -> String {
13607 match key {
13608 "Return" | "Enter" => "\r".into(),
13609 "Tab" => "\t".into(),
13610 "Delete" | "Backspace" => "\u{8}".into(),
13611 "Escape" => "\u{1b}".into(),
13612 "Space" => " ".into(),
13613 k if k.chars().count() == 1 => k.to_lowercase(),
13614 _ => String::new(), }
13616}
13617
13618fn role_spec(
13621 role: day_spec::MenuRole,
13622) -> (
13623 &'static str,
13624 Option<objc2::runtime::Sel>,
13625 Option<day_spec::Shortcut>,
13626) {
13627 use day_spec::MenuRole as R;
13628 use day_spec::Shortcut as S;
13629 match role {
13630 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
13631 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
13632 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
13633 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
13634 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
13635 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
13636 R::Delete => ("Delete", Some(sel!(delete:)), None),
13637 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
13638 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
13639 R::Preferences => ("Settings…", None, Some(S::primary(","))),
13640 R::Minimize => (
13641 "Minimize",
13642 Some(sel!(performMiniaturize:)),
13643 Some(S::primary("m")),
13644 ),
13645 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
13646 R::Fullscreen => (
13647 "Enter Full Screen",
13648 Some(sel!(toggleFullScreen:)),
13649 Some(S::primary("f").control()),
13650 ),
13651 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
13654 R::CheckForUpdates => ("Check for Updates…", None, None),
13656 }
13657}
13658
13659pub(crate) fn build_ns_menu(
13660 mtm: MainThreadMarker,
13661 title: &str,
13662 items: &[day_spec::MenuItem],
13663) -> Retained<NSMenu> {
13664 use day_spec::MenuItem as MI;
13665 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
13666 let target = menu_target(mtm);
13667 for item in items {
13668 match item {
13669 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
13670 MI::Submenu { label, items, .. } => {
13671 let sub = build_ns_menu(mtm, label, items);
13672 let it = NSMenuItem::new(mtm);
13673 it.setTitle(&NSString::from_str(label));
13674 it.setSubmenu(Some(&sub));
13675 menu.addItem(&it);
13676 }
13677 MI::Action {
13678 action,
13679 label,
13680 shortcut,
13681 enabled,
13682 checked,
13683 role,
13684 icon,
13685 ..
13686 } => {
13687 let (mut lbl, sel, mut sc) = match role {
13689 Some(r) => {
13690 let (dl, ds, dsc) = role_spec(*r);
13691 (dl.to_string(), ds, dsc)
13692 }
13693 None => (String::new(), None, None),
13694 };
13695 if !label.is_empty() {
13696 lbl.clone_from(label);
13697 }
13698 if shortcut.is_some() {
13699 sc.clone_from(shortcut);
13700 }
13701 let responder_role = matches!(
13707 role,
13708 Some(
13709 day_spec::MenuRole::Undo
13710 | day_spec::MenuRole::Redo
13711 | day_spec::MenuRole::Cut
13712 | day_spec::MenuRole::Copy
13713 | day_spec::MenuRole::Paste
13714 | day_spec::MenuRole::SelectAll
13715 )
13716 );
13717 let custom = *action != 0 && !responder_role;
13718 let key = sc.as_ref().map_or_default(|s| ns_key_equivalent(&s.key));
13719 let it = unsafe {
13720 NSMenuItem::initWithTitle_action_keyEquivalent(
13721 NSMenuItem::alloc(mtm),
13722 &NSString::from_str(&lbl),
13723 if custom { Some(sel!(fire:)) } else { sel },
13724 &NSString::from_str(&key),
13725 )
13726 };
13727 if let Some(s) = &sc {
13728 it.setKeyEquivalentModifierMask(ns_modifiers(s));
13729 it.setAllowsAutomaticKeyEquivalentLocalization(true);
13735 it.setAllowsAutomaticKeyEquivalentMirroring(true);
13736 }
13737 if custom {
13738 let tobj: &objc2::runtime::AnyObject = target.as_ref();
13739 unsafe { it.setTarget(Some(tobj)) };
13740 it.setTag(*action as isize);
13741 }
13742 it.setEnabled(*enabled);
13743 if let Some(on) = checked {
13746 it.setState(if *on {
13747 NSControlStateValueOn
13748 } else {
13749 NSControlStateValueOff
13750 });
13751 }
13752 if let Some(icon) = icon
13755 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13756 {
13757 img.setSize(NSSize::new(16.0, 16.0));
13758 it.setImage(Some(&img));
13759 }
13760 menu.addItem(&it);
13761 }
13762 }
13763 }
13764 menu
13765}
13766
13767fn release_bitmap(id: day_spec::BitmapId) {
13770 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13771}
13772
13773#[cfg(test)]
13774mod bitmap_teardown_tests {
13775 use super::*;
13776
13777 #[test]
13778 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13779 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13781 if std::env::var_os(CHILD).is_some() {
13782 struct LateRelease;
13783 impl Drop for LateRelease {
13784 fn drop(&mut self) {
13785 assert!(BITMAPS.try_with(|_| ()).is_err());
13786 release_bitmap(day_spec::BitmapId(1));
13788 }
13789 }
13790 std::thread_local! {
13791 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13792 }
13793 std::thread::spawn(|| {
13794 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13795 BITMAPS.with(|_| ()); })
13797 .join()
13798 .unwrap();
13799 return;
13800 }
13801 let output = std::process::Command::new(std::env::current_exe().unwrap())
13802 .args([
13803 "--exact",
13804 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13805 "--nocapture",
13806 ])
13807 .env(CHILD, "1")
13808 .output()
13809 .unwrap();
13810 assert!(
13811 output.status.success(),
13812 "{}",
13813 String::from_utf8_lossy(&output.stderr)
13814 );
13815 }
13816}