1#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod color;
17mod nav_progress;
18
19use std::any::Any;
20use std::cell::{Cell, RefCell};
21use std::collections::HashMap;
22use std::rc::Rc;
23
24use linkme::distributed_slice;
25use objc2::Message as _;
26use objc2::rc::Retained;
27use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
28use objc2::{
29 AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
30};
31use objc2_app_kit::NSAccessibility as _;
32use objc2_app_kit::NSAppearanceCustomization as _;
33use objc2_app_kit::NSDraggingInfo as _;
34use objc2_app_kit::NSSplitViewDelegate;
35use objc2_app_kit::NSTextContent as _;
36use objc2_app_kit::NSTextInputClient;
37use objc2_app_kit::NSUserInterfaceItemIdentification as _;
38use objc2_app_kit::{
39 NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
40 NSGestureRecognizerDelegate, NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
41 NSPressGestureRecognizer,
42};
43use objc2_app_kit::{
44 NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
45 NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
46 NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
47 NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
48 NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
49 NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
50 NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
51 NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
52 NSWindowDelegate, NSWindowStyleMask,
53};
54use objc2_app_kit::{
55 NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
56 NSApplicationWillTerminateNotification,
57};
58use objc2_app_kit::{
59 NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
60};
61use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
62use objc2_core_foundation::CGAffineTransform;
63use objc2_foundation::{
64 NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
65 NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
66};
67use objc2_quartz_core::CATransaction;
68
69use day_spec::ffi_guard;
70use day_spec::present;
71use day_spec::props::*;
72use day_spec::sidetable::SideTable;
73use day_spec::{
74 A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
75 InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
76 Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
77 WindowOptions, kinds, props_of,
78};
79
80pub type Handle = Retained<NSView>;
81
82pub use toolbar::image_for as toolbar_image;
84
85mod dock;
87mod documents;
88mod frame;
89mod input;
90mod motion;
91mod picker;
92mod scroll;
93mod status_item;
94mod textarea;
95mod toolbar;
96mod transfer;
97mod window_chrome;
98use objc2_app_kit::NSDraggingSource;
99
100pub mod ext;
101pub use color::nsink;
102pub use ext::*;
103
104type Sink = Rc<dyn Fn(NodeId, Event)>;
110
111day_core::tls_group! {
112 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
113 static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
115 static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
120 RefCell::new(HashMap::new());
121 static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
123 static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
127
128 static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
131 static APP_LABELED: SideTable<()> = SideTable::new();
134 static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
140 static TRANSFORMS: SideTable<Transform> = SideTable::new();
144 static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
147 static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
148 static SHEET_NODES: SideTable<NodeId> = SideTable::new();
150 static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
151 static PAN_NODES: SideTable<NodeId> = SideTable::new();
154 static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
155 static HOVER_NODES: SideTable<NodeId> = SideTable::new();
159 static ROTATE_NODES: SideTable<NodeId> = SideTable::new();
164 static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
167 static KEY_NODES: SideTable<NodeId> = SideTable::new();
171 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
176 static MARKED: SideTable<String> = SideTable::new();
180 static INTERPRETING: RefCell<Option<Interpreting>> = const { RefCell::new(None) };
183
184 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
186 RefCell::new(HashMap::new());
187
188 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
189 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
191 RefCell::new(std::collections::HashSet::new());
192 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
198
199 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
200 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
203
204 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
206 static SPLIT_PANES: SideTable<bool> = SideTable::new();
208
209 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
213
214 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
215 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
217
218 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
223 static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
227 const { RefCell::new(Vec::new()) };
228 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
231 static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
234
235 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
237
238 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
240 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
241 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
242 const { std::cell::RefCell::new(None) };
243
244 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
246 RefCell::new(HashMap::new());
247 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
249 RefCell::new(HashMap::new());
250
251 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
254 const { std::cell::RefCell::new(None) };
255 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
259 const { std::cell::RefCell::new(None) };
260
261}
262
263pub fn emit(id: NodeId, ev: Event) {
265 let sink = SINK.with(|s| s.borrow().clone());
266 if let Some(sink) = sink {
267 sink(id, ev);
268 }
269}
270
271fn ptr_of(v: &NSView) -> usize {
272 std::ptr::from_ref::<NSView>(v).cast::<()>() as usize
273}
274
275fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
280 ffi_guard::contain((), || {
281 let key = ptr_of(btn);
283 let Some(items) =
284 day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(key)).is_some())
285 else {
286 return;
287 };
288 let menu = build_ns_menu(btn.mtm(), "", &items);
289 let bounds = btn.bounds();
290 let y = if btn.isFlipped() {
291 bounds.size.height + 2.0
292 } else {
293 -2.0
294 };
295 unsafe {
296 btn.highlight(true);
297 menu.popUpMenuPositioningItem_atLocation_inView(
299 None,
300 objc2_foundation::NSPoint::new(0.0, y),
301 Some(btn),
302 );
303 btn.highlight(false);
304 }
305 });
306}
307
308#[derive(Clone, Copy)]
310struct ImageMode {
311 template: bool,
312 tinted: bool,
313}
314
315impl ImageMode {
316 fn renders_template(self) -> bool {
319 self.template || self.tinted
320 }
321}
322
323struct AppKitBitmap {
330 image: Retained<objc2_app_kit::NSImage>,
331 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
332 info: day_spec::BitmapInfo,
333}
334
335fn scaled_rep(
341 image: &objc2_app_kit::NSImage,
342 pixels: Size,
343 scale: f64,
344) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
345 use objc2::AllocAnyThread as _;
346 let w = (pixels.width * scale).round().max(1.0);
347 let h = (pixels.height * scale).round().max(1.0);
348 let rep = unsafe {
349 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
350 objc2_app_kit::NSBitmapImageRep::alloc(),
351 std::ptr::null_mut(),
352 w as isize,
353 h as isize,
354 8,
355 4,
356 true,
357 false,
358 objc2_app_kit::NSDeviceRGBColorSpace,
359 0,
360 0,
361 )
362 }?;
363 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
364 NSGraphicsContext::saveGraphicsState_class();
365 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
366 unsafe {
367 image.drawInRect_fromRect_operation_fraction(
368 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
369 NSRect::ZERO,
370 objc2_app_kit::NSCompositingOperation::SourceOver,
371 1.0,
372 );
373 }
374 NSGraphicsContext::restoreGraphicsState_class();
375 Some(rep)
376}
377
378fn encode_bitmap(
383 id: day_spec::BitmapId,
384 spec: &day_spec::EncodeSpec,
385) -> Result<Vec<u8>, day_spec::ImageError> {
386 use day_spec::ImageFormat as F;
387 use objc2_app_kit::NSBitmapImageFileType as T;
388 let file_type = match spec.format {
389 F::Png => T::PNG,
390 F::Jpeg => T::JPEG,
391 F::Tiff => T::TIFF,
392 F::Bmp => T::BMP,
393 F::Gif => T::GIF,
394 _ => return Err(day_spec::ImageError::Encode),
398 };
399 let held = BITMAPS.with(|m| {
400 m.borrow()
401 .get(&id.0)
402 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
403 });
404 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
405 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
406
407 let rep = match spec.fit {
410 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
411 let scale = (fit.width / info.pixels.width)
412 .min(fit.height / info.pixels.height)
413 .min(1.0);
414 if scale < 1.0 {
415 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
416 } else {
417 rep
418 }
419 }
420 _ => rep,
421 };
422
423 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
424 Some(q) => {
426 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
427 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
428 let value: &objc2::runtime::AnyObject = &number;
429 NSDictionary::from_slices::<NSString>(&[key], &[value])
430 }
431 None => NSDictionary::new(),
432 };
433 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
434 .ok_or(day_spec::ImageError::Encode)?;
435 Ok(data.to_vec())
436}
437
438fn paint_ops(ops: &[DrawOp], base_scale: f64) {
447 use objc2_core_graphics::CGContext;
448 let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
450 let mut replay = Replay::new(base_scale);
451 let Some(cg) = cg else {
452 for op in ops {
453 draw_op(op, &mut replay);
454 }
455 return;
456 };
457 cg_begin_replay(&cg);
458 let grouped = ops
463 .iter()
464 .any(|op| matches!(op, DrawOp::Blend(mode) if *mode != day_spec::BlendMode::Normal));
465 if grouped {
466 CGContext::save_g_state(Some(&cg));
467 unsafe { CGContext::begin_transparency_layer(Some(&cg), None) };
469 }
470 for op in ops {
471 if !cg_fast_op(&cg, op) {
472 draw_op(op, &mut replay);
473 }
474 }
475 while replay.restore() {
478 NSGraphicsContext::restoreGraphicsState_class();
479 }
480 if grouped {
481 CGContext::end_transparency_layer(Some(&cg));
482 CGContext::restore_g_state(Some(&cg));
483 }
484}
485
486#[derive(Clone, Copy, Debug, Default, PartialEq)]
490struct Ink {
491 shadow: bool,
492 blend: day_spec::BlendMode,
493}
494
495struct Replay {
497 base_scale: f64,
498 ink: Ink,
499 saved: Vec<Ink>,
500}
501
502impl Replay {
503 fn new(base_scale: f64) -> Self {
504 Replay {
505 base_scale,
506 ink: Ink::default(),
507 saved: Vec::new(),
508 }
509 }
510
511 fn save(&mut self) {
512 self.saved.push(self.ink);
513 }
514
515 fn restore(&mut self) -> bool {
519 match self.saved.pop() {
520 Some(ink) => {
521 self.ink = ink;
522 true
523 }
524 None => false,
525 }
526 }
527}
528
529fn pdf_ops(ops: &[DrawOp]) -> std::borrow::Cow<'_, [DrawOp]> {
535 use day_spec::BlendMode;
536 if !ops
537 .iter()
538 .any(|op| matches!(op, DrawOp::Blend(BlendMode::Erase)))
539 {
540 return std::borrow::Cow::Borrowed(ops);
541 }
542 let (mut blend, mut saved) = (BlendMode::Normal, Vec::new());
543 let mut kept = Vec::with_capacity(ops.len());
544 for op in ops {
545 match op {
546 DrawOp::Blend(mode) => blend = *mode,
547 DrawOp::Save => saved.push(blend),
548 DrawOp::Restore => blend = saved.pop().unwrap_or(blend),
549 DrawOp::Fill(..)
550 | DrawOp::Stroke(..)
551 | DrawOp::Text { .. }
552 | DrawOp::Stamp(_)
553 | DrawOp::Image { .. }
554 if blend == BlendMode::Erase =>
555 {
556 continue;
557 }
558 _ => {}
559 }
560 kept.push(op.clone());
561 }
562 std::borrow::Cow::Owned(kept)
563}
564
565fn cg_blend_mode(mode: day_spec::BlendMode) -> objc2_core_graphics::CGBlendMode {
567 use day_spec::BlendMode as B;
568 use objc2_core_graphics::CGBlendMode as M;
569 match mode {
570 B::Normal => M::Normal,
571 B::Multiply => M::Multiply,
572 B::Screen => M::Screen,
573 B::Overlay => M::Overlay,
574 B::Darken => M::Darken,
575 B::Lighten => M::Lighten,
576 B::Add => M::PlusLighter,
577 B::Erase => M::DestinationOut,
578 }
579}
580
581fn ns_compositing(mode: day_spec::BlendMode) -> objc2_app_kit::NSCompositingOperation {
583 use day_spec::BlendMode as B;
584 use objc2_app_kit::NSCompositingOperation as O;
585 match mode {
586 B::Normal => O::SourceOver,
587 B::Multiply => O::Multiply,
588 B::Screen => O::Screen,
589 B::Overlay => O::Overlay,
590 B::Darken => O::Darken,
591 B::Lighten => O::Lighten,
592 B::Add => O::PlusLighter,
593 B::Erase => O::DestinationOut,
594 }
595}
596
597fn cg_set_shadow(
603 cg: &objc2_core_graphics::CGContext,
604 shadow: Option<&day_spec::Shadow>,
605 base_scale: f64,
606) {
607 use objc2_core_graphics::{CGColor, CGContext};
608 match shadow {
609 Some(s) => {
610 let c = s.color.resolved();
611 let color = CGColor::new_srgb(c.r, c.g, c.b, c.a);
612 CGContext::set_shadow_with_color(
613 Some(cg),
614 NSSize::new(s.dx * base_scale, -s.dy * base_scale),
615 s.blur.max(0.0) * base_scale,
616 Some(&color),
617 );
618 }
619 None => CGContext::set_shadow_with_color(Some(cg), NSSize::new(0.0, 0.0), 0.0, None),
620 }
621}
622
623fn draw_grouped(replay: &Replay, draw: impl FnOnce()) {
628 use objc2_core_graphics::CGContext;
629 let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
631 let layer = cg.filter(|_| replay.ink.shadow);
632 NSGraphicsContext::saveGraphicsState_class();
633 if let Some(cg) = &layer {
634 unsafe { CGContext::begin_transparency_layer(Some(cg), None) };
636 }
637 draw();
638 if let Some(cg) = &layer {
639 CGContext::end_transparency_layer(Some(cg));
640 }
641 NSGraphicsContext::restoreGraphicsState_class();
642}
643
644fn native_conic() -> Option<ConicFn> {
648 unsafe extern "C" {
649 fn dlsym(
650 handle: *mut std::ffi::c_void,
651 symbol: *const std::ffi::c_char,
652 ) -> *mut std::ffi::c_void;
653 }
654 static FOUND: std::sync::OnceLock<Option<ConicFn>> = std::sync::OnceLock::new();
655 *FOUND.get_or_init(|| {
656 let default = -2isize as *mut std::ffi::c_void;
658 let symbol = unsafe { dlsym(default, c"CGContextDrawConicGradient".as_ptr()) };
660 (!symbol.is_null())
663 .then(|| unsafe { std::mem::transmute::<*mut std::ffi::c_void, ConicFn>(symbol) })
664 })
665}
666
667type ConicFn = unsafe extern "C-unwind" fn(
669 &objc2_core_graphics::CGContext,
670 Option<&objc2_core_graphics::CGGradient>,
671 NSPoint,
672 objc2_core_foundation::CGFloat,
673);
674
675fn conic_pixels(
681 gradient: &day_spec::ConicGradient,
682 center: Point,
683 origin: Point,
684 step: f64,
685 width: usize,
686 height: usize,
687) -> Vec<u8> {
688 let mut pixels = Vec::with_capacity(width * height * 4);
689 let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
690 for j in 0..height {
691 let dy = origin.y + (j as f64 + 0.5) * step - center.y;
692 for i in 0..width {
693 let dx = origin.x + (i as f64 + 0.5) * step - center.x;
694 let c = gradient.color_at(day_spec::Angle::rad(dy.atan2(dx)));
696 pixels.extend_from_slice(&[
697 byte(c.r * c.a),
698 byte(c.g * c.a),
699 byte(c.b * c.a),
700 byte(c.a),
701 ]);
702 }
703 }
704 pixels
705}
706
707const CONIC_PIXEL_BUDGET: f64 = 4_000_000.0;
710
711fn draw_conic(
714 cg: &objc2_core_graphics::CGContext,
715 gradient: &day_spec::ConicGradient,
716 bounds: day_spec::Rect,
717) {
718 use objc2_core_graphics::{CGColorSpace, CGGradient};
719 if gradient.stops.is_empty() {
720 return;
721 }
722 let center = gradient.center.resolve(bounds);
723 if let Some(draw) = native_conic() {
724 let components: Vec<objc2_core_foundation::CGFloat> = stops_now(&gradient.stops)
725 .into_iter()
726 .flat_map(|(_, c)| [c.r, c.g, c.b, c.a])
727 .collect();
728 let locations: Vec<objc2_core_foundation::CGFloat> =
729 gradient.stops.iter().map(|(at, _)| *at).collect();
730 let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
732 let native = unsafe {
734 CGGradient::with_color_components(
735 srgb.as_deref(),
736 components.as_ptr(),
737 locations.as_ptr(),
738 locations.len(),
739 )
740 };
741 if let Some(native) = native {
742 unsafe {
745 draw(
746 cg,
747 Some(&native),
748 NSPoint::new(center.x, center.y),
749 gradient.start.radians(),
750 );
751 };
752 return;
753 }
754 }
755 draw_conic_pixels(cg, gradient, center);
756}
757
758fn draw_conic_pixels(
763 cg: &objc2_core_graphics::CGContext,
764 gradient: &day_spec::ConicGradient,
765 center: Point,
766) {
767 use objc2_core_graphics::{
768 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGContext,
769 CGImageAlphaInfo,
770 };
771 let clip = CGContext::clip_bounding_box(Some(cg));
772 let (w, h) = (clip.size.width, clip.size.height);
773 if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
774 return;
775 }
776 let device = CGContext::user_space_to_device_space_transform(Some(cg));
777 let density = device
778 .a
779 .hypot(device.b)
780 .max(device.c.hypot(device.d))
781 .clamp(2.0, 16.0)
782 .min((CONIC_PIXEL_BUDGET / (w * h)).sqrt());
783 let (pw, ph) = (
784 ((w * density).ceil() as usize).max(1),
785 ((h * density).ceil() as usize).max(1),
786 );
787 let origin = Point::new(clip.origin.x, clip.origin.y);
788 let mut pixels = conic_pixels(gradient, center, origin, 1.0 / density, pw, ph);
789 let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
791 let image = unsafe {
795 CGBitmapContextCreate(
796 pixels.as_mut_ptr().cast(),
797 pw,
798 ph,
799 8,
800 pw * 4,
801 srgb.as_deref(),
802 CGImageAlphaInfo::PremultipliedLast.0,
803 )
804 }
805 .and_then(|bitmap| CGBitmapContextCreateImage(Some(&bitmap)));
806 let Some(image) = image else {
807 return;
808 };
809 CGContext::save_g_state(Some(cg));
812 CGContext::translate_ctm(Some(cg), origin.x, origin.y + ph as f64 / density);
813 CGContext::scale_ctm(Some(cg), 1.0, -1.0);
814 CGContext::draw_image(
815 Some(cg),
816 NSRect::new(
817 NSPoint::new(0.0, 0.0),
818 NSSize::new(pw as f64 / density, ph as f64 / density),
819 ),
820 Some(&image),
821 );
822 CGContext::restore_g_state(Some(cg));
823}
824
825fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
834 use objc2_core_graphics::{CGContext, CGImage};
835 match op {
836 DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
837 let Some(even_odd) = cg_add_shape(cg, shape) else {
838 return false;
839 };
840 let c = color.resolved();
841 let c = [c.r, c.g, c.b, c.a];
842 unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
844 if even_odd {
845 CGContext::eo_fill_path(Some(cg));
846 } else {
847 CGContext::fill_path(Some(cg));
848 }
849 true
850 }
851 DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
852 if cg_add_shape(cg, shape).is_none() {
853 return false;
854 }
855 let c = color.resolved();
856 let c = [c.r, c.g, c.b, c.a];
857 unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
859 cg_stroke_style(cg, style);
860 CGContext::stroke_path(Some(cg));
861 true
862 }
863 DrawOp::Clip(shape) => {
864 let Some(even_odd) = cg_add_shape(cg, shape) else {
865 return false;
866 };
867 if even_odd {
868 CGContext::eo_clip(Some(cg));
869 } else {
870 CGContext::clip(Some(cg));
871 }
872 true
873 }
874 DrawOp::Image {
875 image,
876 rect,
877 opacity,
878 source,
879 } => {
880 let Some((cg_image, pixels)) = BITMAPS.with(|m| {
883 m.borrow().get(&image.0).and_then(|b| {
884 let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
886 Some((cg, b.info.pixels))
887 })
888 }) else {
889 return false;
890 };
891 let (cropped, dest) = match source {
895 None => (None, *rect),
896 Some(src) => {
897 let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
898 else {
899 return true;
900 };
901 let crop = CGImage::with_image_in_rect(
902 Some(&cg_image),
903 NSRect::new(
904 NSPoint::new(src.origin.x, src.origin.y),
905 NSSize::new(src.size.width, src.size.height),
906 ),
907 );
908 let Some(crop) = crop else {
909 return true;
910 };
911 (Some(crop), dest)
912 }
913 };
914 if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
915 return true;
916 }
917 CGContext::save_g_state(Some(cg));
920 CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
921 CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
922 CGContext::scale_ctm(Some(cg), 1.0, -1.0);
923 CGContext::draw_image(
924 Some(cg),
925 NSRect::new(
926 NSPoint::new(0.0, 0.0),
927 NSSize::new(dest.size.width, dest.size.height),
928 ),
929 Some(cropped.as_deref().unwrap_or(&cg_image)),
930 );
931 CGContext::restore_g_state(Some(cg));
932 true
933 }
934 _ => false,
935 }
936}
937
938fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
940 use objc2_core_graphics::{CGColorSpace, CGContext};
941 let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
943 CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
944 CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
945}
946
947fn cg_add_shape(cg: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
950 use day_spec::{PathSeg, Shape};
951 use objc2_core_graphics::CGContext;
952 CGContext::begin_path(Some(cg));
953 match shape {
954 Shape::Rect(r) => CGContext::add_rect(Some(cg), ns_rect(*r)),
955 Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(cg), ns_rect(*r)),
956 Shape::Line(a, b) => {
957 CGContext::move_to_point(Some(cg), a.x, a.y);
958 CGContext::add_line_to_point(Some(cg), b.x, b.y);
959 }
960 Shape::Polygon(pts) => {
961 let (first, rest) = pts.split_first()?;
962 if rest.is_empty() {
963 return None;
964 }
965 CGContext::move_to_point(Some(cg), first.x, first.y);
966 for p in rest {
967 CGContext::add_line_to_point(Some(cg), p.x, p.y);
968 }
969 CGContext::close_path(Some(cg));
970 }
971 Shape::Path(path) => {
972 if path.segs.is_empty() {
973 return None;
974 }
975 for seg in &path.segs {
976 match seg {
977 PathSeg::Move(a) => CGContext::move_to_point(Some(cg), a.x, a.y),
978 PathSeg::Line(a) => CGContext::add_line_to_point(Some(cg), a.x, a.y),
979 PathSeg::Quad(c, a) => {
980 CGContext::add_quad_curve_to_point(Some(cg), c.x, c.y, a.x, a.y);
981 }
982 PathSeg::Cubic(c1, c2, a) => {
983 CGContext::add_curve_to_point(Some(cg), c1.x, c1.y, c2.x, c2.y, a.x, a.y);
984 }
985 PathSeg::Close => CGContext::close_path(Some(cg)),
986 }
987 }
988 return Some(path.rule == day_spec::FillRule::EvenOdd);
989 }
990 Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
991 }
992 Some(false)
993}
994
995fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
999 use day_spec::{LineCap, LineJoin};
1000 use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
1001 CGContext::set_line_width(Some(cg), style.width);
1002 CGContext::set_line_cap(
1003 Some(cg),
1004 match style.cap {
1005 LineCap::Butt => CGLineCap::Butt,
1006 LineCap::Round => CGLineCap::Round,
1007 LineCap::Square => CGLineCap::Square,
1008 },
1009 );
1010 CGContext::set_line_join(
1011 Some(cg),
1012 match style.join {
1013 LineJoin::Miter => CGLineJoin::Miter,
1014 LineJoin::Round => CGLineJoin::Round,
1015 LineJoin::Bevel => CGLineJoin::Bevel,
1016 },
1017 );
1018 CGContext::set_miter_limit(Some(cg), style.miter_limit);
1019 if style.dash.is_empty() {
1020 unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
1022 } else {
1023 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
1024 unsafe {
1026 CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len());
1027 };
1028 }
1029}
1030
1031fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
1039 use objc2_core_graphics::CGContext;
1040 CGContext::save_g_state(Some(cg));
1041 CGContext::translate_ctm(Some(cg), 0.0, height);
1042 CGContext::scale_ctm(Some(cg), scale, -scale);
1043 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
1044 NSGraphicsContext::saveGraphicsState_class();
1045 NSGraphicsContext::setCurrentContext(Some(&ns));
1046 paint_ops(ops, scale);
1047 NSGraphicsContext::restoreGraphicsState_class();
1048 CGContext::restore_g_state(Some(cg));
1049}
1050
1051struct Sendable<T>(T);
1053
1054unsafe impl<T> Send for Sendable<T> {}
1060
1061struct OffscreenResources {
1066 images: Vec<(u64, AppKitBitmap)>,
1067 fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
1068}
1069
1070impl OffscreenResources {
1071 fn collect(ops: &[DrawOp]) -> Self {
1074 let mut images: Vec<(u64, AppKitBitmap)> = Vec::new();
1075 let mut fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)> = Vec::new();
1076 for op in ops {
1077 match op {
1078 DrawOp::Image { image, .. } => {
1079 if images.iter().any(|(id, _)| *id == image.0) {
1080 continue;
1081 }
1082 let held = BITMAPS.with(|m| {
1083 m.borrow().get(&image.0).map(|b| AppKitBitmap {
1084 image: b.image.clone(),
1085 rep: b.rep.clone(),
1086 info: b.info,
1087 })
1088 });
1089 if let Some(bitmap) = held {
1090 images.push((image.0, bitmap));
1091 }
1092 }
1093 DrawOp::Text { size, font, .. } => {
1094 let key = (size.to_bits(), font.clone());
1095 if fonts.iter().any(|(k, _)| *k == key) {
1096 continue;
1097 }
1098 let resolved = canvas_nsfont(*size, font);
1099 fonts.push((key, resolved));
1100 }
1101 _ => {}
1102 }
1103 }
1104 Self { images, fonts }
1105 }
1106
1107 fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
1111 let mut added_images = Vec::with_capacity(self.images.len());
1112 BITMAPS.with(|m| {
1113 let mut m = m.borrow_mut();
1114 for (id, bitmap) in self.images {
1115 if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
1116 slot.insert(bitmap);
1117 added_images.push(id);
1118 }
1119 }
1120 });
1121 let added_fonts = self.fonts.len();
1122 OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
1123 let out = paint();
1124 OFFSCREEN_FONTS.with(|t| {
1125 let mut t = t.borrow_mut();
1126 let keep = t.len().saturating_sub(added_fonts);
1127 t.truncate(keep);
1128 });
1129 BITMAPS.with(|m| {
1130 let mut m = m.borrow_mut();
1131 for id in added_images {
1132 m.remove(&id);
1133 }
1134 });
1135 out
1136 }
1137}
1138
1139fn render_bitmap_cgimage(
1150 ops: &[DrawOp],
1151 size: Size,
1152 scale: f64,
1153) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, day_spec::ExportError>
1154{
1155 use objc2_core_graphics::{
1156 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
1157 };
1158 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
1159 let (pw, ph) = day_spec::export_pixels(size, scale);
1160 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
1162 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
1163 let cg = unsafe {
1166 CGBitmapContextCreate(
1167 std::ptr::null_mut(),
1168 pw as usize,
1169 ph as usize,
1170 8,
1171 0,
1172 Some(&space),
1173 CGImageAlphaInfo::PremultipliedLast.0,
1174 )
1175 }
1176 .ok_or_else(|| {
1177 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
1178 })?;
1179 paint_flipped(&cg, f64::from(ph), scale, ops);
1181 CGBitmapContextCreateImage(Some(&cg))
1182 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
1183}
1184
1185fn bitmap_from_cgimage(cg_image: &objc2_core_graphics::CGImage, scale: f64) -> AppKitBitmap {
1189 use objc2::AllocAnyThread as _;
1190 let rep = unsafe {
1191 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
1192 objc2_app_kit::NSBitmapImageRep::alloc(),
1193 cg_image,
1194 )
1195 };
1196 let (pw, ph) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
1197 let points = NSSize::new(pw / scale, ph / scale);
1200 unsafe { rep.setSize(points) };
1201 let image =
1202 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
1203 unsafe { image.addRepresentation(&rep) };
1204 AppKitBitmap {
1205 image,
1206 rep: Some(rep),
1207 info: day_spec::BitmapInfo {
1208 pixels: Size::new(pw, ph),
1209 scale,
1210 format: None,
1211 has_alpha: true,
1212 },
1213 }
1214}
1215
1216fn render_pdf_bytes(
1221 pages: &[day_spec::PdfPage],
1222 info: &day_spec::PdfInfo,
1223) -> Result<Vec<u8>, day_spec::ExportError> {
1224 use objc2_core_foundation::{
1225 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
1226 };
1227 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
1228 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
1229 let media =
1230 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
1231 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
1232 let data = CFMutableData::new(None, 0)
1233 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
1234 let consumer = CGDataConsumer::with_cf_data(Some(&data))
1235 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
1236
1237 let mut keys: Vec<&CFString> = Vec::new();
1238 let mut values: Vec<CFRetained<CFString>> = Vec::new();
1239 let (title_key, author_key) = unsafe {
1241 (
1242 objc2_core_graphics::kCGPDFContextTitle,
1243 objc2_core_graphics::kCGPDFContextAuthor,
1244 )
1245 };
1246 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
1247 if let Some(value) = value {
1248 keys.push(key);
1249 values.push(CFString::from_str(value));
1250 }
1251 }
1252 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
1253 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
1254
1255 let first_box = media(first.size);
1256 let pdf =
1259 unsafe { CGPDFContextCreate(Some(&consumer), &raw const first_box, Some(aux.as_opaque())) }
1260 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
1261 for page in pages {
1262 let page_box = media(page.size);
1263 unsafe { CGContext::begin_page(Some(&pdf), &raw const page_box) };
1265 paint_flipped(&pdf, page.size.height, 1.0, &pdf_ops(&page.ops));
1266 CGContext::end_page(Some(&pdf));
1267 }
1268 CGPDFContextClose(Some(&pdf));
1270 drop(pdf);
1271 drop(consumer);
1272 Ok(data.to_vec())
1273}
1274
1275thread_local! {
1276 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
1279 std::cell::RefCell::new(std::collections::HashMap::new());
1280}
1281
1282fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
1295 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
1296 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
1297 const STRETCH: f32 = 1.0;
1300 const HOLD: f32 = 750.0;
1301 use objc2_app_kit::{
1302 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
1303 };
1304 let label = |text: &str, size: f64, secondary: bool| {
1305 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
1306 unsafe {
1307 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
1308 if secondary {
1309 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
1310 }
1311 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
1312 }
1313 tf
1314 };
1315 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
1316 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
1317 let stack = NSStackView::new(mtm);
1318 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
1319 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
1320 stack.setAlignment(NSLayoutAttribute::CenterY);
1321 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
1322 stack.setSpacing(6.0);
1323 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
1325 top: 4.0,
1326 left: 0.0,
1327 bottom: 4.0,
1328 right: 0.0,
1329 });
1330 let icon = unsafe { NSImageView::new(mtm) };
1331 unsafe {
1332 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
1333 icon.widthAnchor()
1334 .constraintEqualToConstant(16.0)
1335 .setActive(true);
1336 icon.heightAnchor()
1337 .constraintEqualToConstant(16.0)
1338 .setActive(true);
1339 }
1340 stack.addArrangedSubview(&icon);
1341 let texts = NSStackView::new(mtm);
1344 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
1345 texts.setAlignment(NSLayoutAttribute::Width);
1346 texts.setSpacing(1.0);
1347 texts.setHuggingPriority_forOrientation(
1350 HOLD,
1351 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
1352 );
1353 let title = label("", size, false);
1354 let subtitle = label("", small, true);
1355 for line in [&title, &subtitle] {
1357 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
1358 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
1359 }
1360 texts.addArrangedSubview(&title);
1361 texts.addArrangedSubview(&subtitle);
1362 stack.addArrangedSubview(&texts);
1363 let detail = label("", size, true);
1364 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1365 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1366 stack.addArrangedSubview(&detail);
1367 let check = unsafe { NSImageView::new(mtm) };
1368 unsafe {
1369 check.setImage(
1370 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1371 &NSString::from_str("checkmark"),
1372 None,
1373 )
1374 .as_deref(),
1375 );
1376 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1377 }
1378 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1379 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1380 stack.addArrangedSubview(&check);
1381 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1382 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1383 dress_list_item(&view, p, mtm);
1384 view
1385}
1386
1387fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1389 use objc2_app_kit::{NSImageView, NSStackView};
1390 let Some(stack) = view.downcast_ref::<NSStackView>() else {
1391 return;
1392 };
1393 let parts = stack.arrangedSubviews();
1394 if parts.len() < 4 {
1395 return;
1396 }
1397 let icon = parts.objectAtIndex(0);
1398 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1399 let image = p
1400 .icon
1401 .as_ref()
1402 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1403 unsafe {
1404 iv.setImage(image.as_deref());
1405 iv.setContentTintColor(p.icon_tint.map(color::nsink).as_deref());
1406 }
1407 }
1408 icon.setHidden(p.icon.is_none());
1409 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1410 let lines = texts.arrangedSubviews();
1411 if lines.len() == 2 {
1412 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1413 tf.setStringValue(&NSString::from_str(&p.title));
1414 }
1415 let sub = lines.objectAtIndex(1);
1416 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1417 tf.setStringValue(&NSString::from_str(&p.subtitle));
1418 }
1419 sub.setHidden(p.subtitle.is_empty());
1420 }
1421 }
1422 let detail = parts.objectAtIndex(2);
1423 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1424 tf.setStringValue(&NSString::from_str(&p.detail));
1425 }
1426 detail.setHidden(p.detail.is_empty());
1427 parts.objectAtIndex(3).setHidden(!p.checked);
1428 let words = [&p.title, &p.subtitle, &p.detail]
1429 .into_iter()
1430 .filter(|w| !w.is_empty())
1431 .map(String::as_str)
1432 .collect::<Vec<_>>()
1433 .join(", ");
1434 unsafe {
1435 view.setAccessibilityElement(true);
1436 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1437 view.setAccessibilitySelected(p.checked);
1438 }
1439}
1440
1441fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1447 use objc2::AllocAnyThread as _;
1448 match source {
1449 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1454 .or_else(|| day_spec::resource::resolve_image_file(name))
1455 .and_then(|path| unsafe {
1456 objc2_app_kit::NSImage::initWithContentsOfFile(
1457 objc2_app_kit::NSImage::alloc(),
1458 &NSString::from_str(&path.to_string_lossy()),
1459 )
1460 }),
1461 day_spec::ImageSource::Bytes(bytes) => unsafe {
1464 objc2_app_kit::NSImage::initWithData(
1465 objc2_app_kit::NSImage::alloc(),
1466 &NSData::with_bytes(bytes),
1467 )
1468 },
1469 day_spec::ImageSource::Decoded(id) => {
1471 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1472 }
1473 }
1474}
1475
1476fn image_rendered(
1483 image: Retained<objc2_app_kit::NSImage>,
1484 template: bool,
1485) -> Retained<objc2_app_kit::NSImage> {
1486 use objc2_foundation::NSCopying as _;
1487 if image.isTemplate() == template {
1488 return image;
1489 }
1490 let image = image.copy();
1491 image.setTemplate(template);
1492 image
1493}
1494
1495fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1498 use day_spec::Role;
1499 use objc2_app_kit::{
1500 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1501 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1502 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1503 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1504 };
1505 unsafe {
1506 Some(match role {
1507 Role::Button => NSAccessibilityButtonRole,
1508 Role::Toggle => NSAccessibilityCheckBoxRole,
1509 Role::Tab => NSAccessibilityRadioButtonRole,
1512 Role::TabList => NSAccessibilityTabGroupRole,
1513 Role::Slider => NSAccessibilitySliderRole,
1514 Role::TextInput => NSAccessibilityTextFieldRole,
1515 Role::Heading(_) => NSAccessibilityHeadingRole,
1520 Role::Image => NSAccessibilityImageRole,
1521 Role::Meter => NSAccessibilityLevelIndicatorRole,
1522 Role::Group => NSAccessibilityGroupRole,
1523 Role::Tree => NSAccessibilityOutlineRole,
1526 Role::TreeItem => NSAccessibilityRowRole,
1527 Role::None => return None,
1528 })
1529 }
1530}
1531
1532fn day_role_from_ns(ax: &str) -> day_spec::Role {
1534 use day_spec::Role;
1535 match ax {
1536 "AXButton" => Role::Button,
1537 "AXCheckBox" => Role::Toggle,
1538 "AXSlider" => Role::Slider,
1539 "AXTextField" => Role::TextInput,
1540 "AXStaticText" | "AXHeading" => Role::Heading(0),
1543 "AXOutline" => Role::Tree,
1544 "AXImage" => Role::Image,
1545 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1546 "AXGroup" => Role::Group,
1547 "AXRadioButton" => Role::Tab,
1548 "AXTabGroup" => Role::TabList,
1549 _ => Role::None,
1550 }
1551}
1552
1553struct TargetIvars {
1558 node: NodeId,
1559}
1560
1561define_class!(
1562 #[unsafe(super(NSObject))]
1563 #[thread_kind = MainThreadOnly]
1564 #[name = "DayTarget"]
1565 #[ivars = TargetIvars]
1566 struct DayTarget;
1567
1568 unsafe impl NSObjectProtocol for DayTarget {}
1569 unsafe impl NSTextFieldDelegate for DayTarget {}
1570
1571 unsafe impl NSTabViewDelegate for DayTarget {
1576 #[unsafe(method(tabView:didSelectTabViewItem:))]
1577 fn tab_view_did_select(
1578 &self,
1579 tab_view: &objc2_app_kit::NSTabView,
1580 item: Option<&objc2_app_kit::NSTabViewItem>,
1581 ) {
1582 ffi_guard::contain((), || {
1583 if TAB_PICK_SUPPRESS.with(std::cell::Cell::get) {
1584 return;
1585 }
1586 if let Some(item) = item {
1587 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1588 if idx >= 0 {
1589 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1590 }
1591 }
1592 });
1593 }
1594 }
1595
1596 impl DayTarget {
1597 #[unsafe(method(action:))]
1602 fn action(&self, sender: &NSControl) {
1603 ffi_guard::contain((), || {
1604 let node = self.ivars().node;
1605 if sender.downcast_ref::<NSSwitch>().is_some() {
1606 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1607 } else if sender.downcast_ref::<NSSlider>().is_some() {
1608 let value = unsafe { sender.doubleValue() };
1609 emit(node, Event::ValueChanged(value));
1611 if slider_value_settled() {
1617 emit(node, Event::ValueCommitted(value));
1618 }
1619 } else if let (Some(f), Some(btn)) = (
1620 BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1621 sender.downcast_ref::<NSButton>(),
1622 ) {
1623 pop_button_menu(btn, &f);
1625 } else {
1626 emit(node, Event::Pressed);
1627 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1630 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1631 unsafe {
1632 btn.setState(if on {
1633 NSControlStateValueOn
1634 } else {
1635 NSControlStateValueOff
1636 });
1637 };
1638 }
1639 }
1640 });
1641 }
1642
1643 #[unsafe(method(navBack:))]
1646 fn nav_back(&self, _sender: &NSControl) {
1647 ffi_guard::contain((), || {
1648 emit(
1649 self.ivars().node,
1650 Event::NavBack {
1651 already_popped: false,
1652 },
1653 );
1654 });
1655 }
1656 }
1657
1658 unsafe impl NSControlTextEditingDelegate for DayTarget {
1659 #[unsafe(method(controlTextDidChange:))]
1660 fn control_text_did_change(&self, notification: &NSNotification) {
1661 ffi_guard::contain((), || {
1662 let node = self.ivars().node;
1663 if let Some(obj) = unsafe { notification.object() }
1664 && let Ok(tf) = obj.downcast::<NSTextField>() {
1665 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1666 }
1667 });
1668 }
1669
1670 #[unsafe(method(control:textView:doCommandBySelector:))]
1676 fn control_do_command(
1677 &self,
1678 _control: &NSControl,
1679 _tv: &NSTextView,
1680 command: objc2::runtime::Sel,
1681 ) -> objc2::runtime::Bool {
1682 ffi_guard::contain(objc2::runtime::Bool::NO, || {
1683 let node = self.ivars().node;
1684 let key = if command == sel!(moveUp:) {
1685 "ArrowUp"
1686 } else if command == sel!(moveDown:) {
1687 "ArrowDown"
1688 } else if command == sel!(cancelOperation:) {
1689 "Escape"
1690 } else {
1691 return objc2::runtime::Bool::NO;
1692 };
1693 let press = NSApplication::sharedApplication(self.mtm())
1697 .currentEvent()
1698 .filter(|e| e.r#type() == NSEventType::KeyDown);
1699 if let Some(press) = press.as_deref()
1700 && press.isARepeat()
1701 {
1702 if !input::owns_repeat(press) {
1703 return objc2::runtime::Bool::NO;
1704 }
1705 emit(
1706 node,
1707 Event::Key(
1708 day_spec::KeyEvent::named(key, 0)
1709 .with_phase(day_spec::KeyPhase::Repeat),
1710 ),
1711 );
1712 return objc2::runtime::Bool::YES;
1713 }
1714 if !day_spec::keys::field_claims(node, key, 0) {
1715 return objc2::runtime::Bool::NO;
1716 }
1717 emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1718 if let Some(press) = press.as_deref() {
1719 input::claim_key(press, node, key.to_string());
1720 }
1721 objc2::runtime::Bool::YES
1722 })
1723 }
1724
1725 #[unsafe(method(controlTextDidEndEditing:))]
1729 fn control_text_did_end_editing(&self, notification: &NSNotification) {
1730 ffi_guard::contain((), || {
1731 let node = self.ivars().node;
1732 let movement = unsafe { notification.userInfo() }
1733 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1734 .and_then(|n| n.downcast::<NSNumber>().ok())
1735 .map_or(NSTextMovement::Other, |n| NSTextMovement(n.integerValue()));
1736 if movement == NSTextMovement::Return {
1737 emit(node, Event::Submitted);
1738 } else {
1739 input::forget_keys(node);
1740 emit(node, Event::FocusChanged(false));
1741 }
1742 });
1743 }
1744 }
1745);
1746
1747impl DayTarget {
1748 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1749 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1750 unsafe { msg_send![super(this), init] }
1751 }
1752}
1753
1754struct CursorIvars {
1759 cursor: RefCell<Option<Retained<NSCursor>>>,
1761 hidden: Cell<bool>,
1763 hiding: Cell<bool>,
1765}
1766
1767define_class!(
1773 #[unsafe(super(NSObject))]
1774 #[thread_kind = MainThreadOnly]
1775 #[name = "DayCursorOwner"]
1776 #[ivars = CursorIvars]
1777 struct DayCursorOwner;
1778
1779 unsafe impl NSObjectProtocol for DayCursorOwner {}
1780
1781 impl DayCursorOwner {
1782 #[unsafe(method(cursorUpdate:))]
1783 fn cursor_update(&self, _event: &NSEvent) {
1784 let iv = self.ivars();
1785 if iv.hidden.get() {
1786 if !iv.hiding.replace(true) {
1787 NSCursor::hide();
1788 }
1789 return;
1790 }
1791 if let Some(c) = iv.cursor.borrow().as_ref() {
1792 c.set();
1793 }
1794 }
1795
1796 #[unsafe(method(mouseExited:))]
1797 fn mouse_exited(&self, _event: &NSEvent) {
1798 if self.ivars().hiding.replace(false) {
1799 NSCursor::unhide();
1800 }
1801 }
1802 }
1803);
1804
1805impl DayCursorOwner {
1806 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1807 let this = Self::alloc(mtm).set_ivars(CursorIvars {
1808 cursor: RefCell::new(None),
1809 hidden: Cell::new(false),
1810 hiding: Cell::new(false),
1811 });
1812 unsafe { msg_send![super(this), init] }
1813 }
1814}
1815
1816#[allow(deprecated)]
1824#[expect(
1825 clippy::match_same_arms,
1826 reason = "each macOS 15 cursor keeps its older fallback arm directly below its probe"
1827)]
1828fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1829 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1830 Some(match c {
1831 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1832 Cursor::Pointer => NSCursor::pointingHandCursor(),
1833 Cursor::Text => NSCursor::IBeamCursor(),
1834 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1835 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1836 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1837 Cursor::Grabbing => NSCursor::closedHandCursor(),
1838 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1839 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1840 Cursor::Copy => NSCursor::dragCopyCursor(),
1841 Cursor::Alias => NSCursor::dragLinkCursor(),
1842 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1843 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1844 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1845 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1846 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1847 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1848 NSCursor::frameResizeCursorFromPosition_inDirections(
1849 NSCursorFrameResizePosition::TopRight,
1850 NSCursorFrameResizeDirections::All,
1851 )
1852 }
1853 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1854 NSCursor::frameResizeCursorFromPosition_inDirections(
1855 NSCursorFrameResizePosition::TopLeft,
1856 NSCursorFrameResizeDirections::All,
1857 )
1858 }
1859 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1860 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1861 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1862 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1863 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1864 Cursor::None => return None,
1865 Cursor::Native(name) => match &**name {
1866 "disappearingItem" => NSCursor::disappearingItemCursor(),
1867 "dragCopy" => NSCursor::dragCopyCursor(),
1868 "dragLink" => NSCursor::dragLinkCursor(),
1869 "contextualMenu" => NSCursor::contextualMenuCursor(),
1870 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1871 _ => return None,
1872 },
1873 })
1874}
1875
1876fn slider_value_settled() -> bool {
1883 let Some(mtm) = MainThreadMarker::new() else {
1884 return false;
1885 };
1886 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1887 return false;
1888 };
1889 matches!(
1890 unsafe { event.r#type() },
1891 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1892 )
1893}
1894
1895struct FieldIvars {
1900 node: NodeId,
1901}
1902
1903struct SharePickerIvars {
1906 actions: Vec<day_spec::share::ShareAction>,
1907}
1908
1909define_class!(
1910 #[unsafe(super(NSObject))]
1911 #[thread_kind = MainThreadOnly]
1912 #[name = "DaySharePickerDelegate"]
1913 #[ivars = SharePickerIvars]
1914 struct DaySharePickerDelegate;
1915
1916 unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1917
1918 impl DaySharePickerDelegate {
1919 #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1920 fn services(
1921 &self,
1922 _picker: &AnyObject,
1923 _items: &AnyObject,
1924 proposed: &objc2_foundation::NSArray<AnyObject>,
1925 ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1926 let mut services: Vec<Retained<AnyObject>> = Vec::new();
1927 for action in &self.ivars().actions {
1928 let id = action.id;
1929 let handler = block2::RcBlock::new(move || {
1930 ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1931 });
1932 let image = action.symbol.and_then(|s| {
1933 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1934 &NSString::from_str(day_spec::sf_symbol_name(s)),
1935 None,
1936 )
1937 });
1938 let service: Option<Retained<AnyObject>> = unsafe {
1941 let alloc: objc2::rc::Allocated<AnyObject> =
1942 msg_send![objc2::class!(NSSharingService), alloc];
1943 msg_send![
1944 alloc,
1945 initWithTitle: &*NSString::from_str(&action.title),
1946 image: image.as_deref(),
1947 alternateImage: None::<&AnyObject>,
1948 handler: &*handler
1949 ]
1950 };
1951 services.extend(service);
1952 }
1953 let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1956 all.extend(services);
1957 objc2_foundation::NSArray::from_retained_slice(&all)
1958 }
1959 }
1960);
1961
1962define_class!(
1963 #[unsafe(super(NSTextField))]
1964 #[thread_kind = MainThreadOnly]
1965 #[name = "DayTextField"]
1966 #[ivars = FieldIvars]
1967 struct DayTextField;
1968
1969 impl DayTextField {
1970 #[unsafe(method(becomeFirstResponder))]
1975 fn become_first_responder(&self) -> bool {
1976 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1977 if ok {
1978 field_gained_focus(self.ivars().node);
1979 }
1980 ok
1981 }
1982 }
1983);
1984
1985impl DayTextField {
1986 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1987 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1988 unsafe { msg_send![super(this), init] }
1989 }
1990}
1991
1992define_class!(
1997 #[unsafe(super(NSSecureTextField))]
1998 #[thread_kind = MainThreadOnly]
1999 #[name = "DaySecureTextField"]
2000 #[ivars = FieldIvars]
2001 struct DaySecureTextField;
2002
2003 impl DaySecureTextField {
2004 #[unsafe(method(becomeFirstResponder))]
2006 fn become_first_responder(&self) -> bool {
2007 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
2008 if ok {
2009 field_gained_focus(self.ivars().node);
2010 }
2011 ok
2012 }
2013 }
2014);
2015
2016impl DaySecureTextField {
2017 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2018 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
2019 unsafe { msg_send![super(this), init] }
2020 }
2021}
2022
2023thread_local! {
2024 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
2027}
2028
2029fn field_gained_focus(node: NodeId) {
2032 if FIELD_SWAP.with(std::cell::Cell::get) {
2033 return;
2034 }
2035 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2038}
2039
2040fn text_field_node(v: &NSView) -> Option<NodeId> {
2043 v.downcast_ref::<DayTextField>()
2044 .map(|f| f.ivars().node)
2045 .or_else(|| {
2046 v.downcast_ref::<DaySecureTextField>()
2047 .map(|f| f.ivars().node)
2048 })
2049}
2050
2051fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
2055 let target = DayTarget::new(mtm, node);
2056 let tf: Retained<NSTextField> = if secure {
2059 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
2060 } else {
2061 Retained::into_super(DayTextField::new(mtm, node))
2062 };
2063 unsafe {
2064 tf.setEditable(true);
2065 tf.setBezeled(true);
2066 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
2067 }
2068 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
2069 tf
2070}
2071
2072fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
2076 window.firstResponder().is_some_and(|fr| {
2077 if Retained::as_ptr(&fr).cast::<()>() as usize == ptr_of(h) {
2078 return true;
2079 }
2080 fr.downcast::<NSText>().is_ok_and(|text| {
2081 unsafe { text.delegate() }
2082 .is_some_and(|d| Retained::as_ptr(&d).cast::<()>() as usize == ptr_of(h))
2083 })
2084 })
2085}
2086
2087fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
2092 unsafe extern "C" {
2093 fn dlsym(
2094 handle: *mut std::ffi::c_void,
2095 symbol: *const std::ffi::c_char,
2096 ) -> *mut std::ffi::c_void;
2097 }
2098 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
2100 unsafe {
2104 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
2105 if slot.is_null() {
2106 None
2107 } else {
2108 (*slot).as_ref()
2109 }
2110 }
2111}
2112
2113fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
2115 if let Some(v) = table.take(old) {
2116 table.insert(new, v);
2117 }
2118}
2119
2120struct LabelIvars {
2125 node: NodeId,
2126 has_links: Cell<bool>,
2127 has_runs: Cell<bool>,
2128 selectable: Cell<bool>,
2129 wraps: Cell<bool>,
2131 paragraph: Cell<day_spec::props::LabelParagraph>,
2134 align: Cell<day_spec::props::TextAlign>,
2135 direction: Cell<Option<day_spec::LayoutDirection>>,
2137 stamped: Cell<bool>,
2140 reports_selection: Cell<bool>,
2142 selection: Cell<Option<(usize, usize)>>,
2143 color: Cell<Option<day_spec::Ink>>,
2146 role: Cell<TextRole>,
2147}
2148
2149define_class!(
2150 #[unsafe(super(NSTextField))]
2151 #[thread_kind = MainThreadOnly]
2152 #[name = "DayLabel"]
2153 #[ivars = LabelIvars]
2154 struct DayLabel;
2155
2156 impl DayLabel {
2157 #[unsafe(method_id(hitTest:))]
2161 fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
2162 let hit: Option<Retained<NSView>> = unsafe { msg_send![super(self), hitTest: point] };
2163 ffi_guard::contain(None, || {
2164 let takes = self.isSelectable() || input::takes_pointer(self);
2165 input::leaf_hit_test(self, hit, takes)
2166 })
2167 }
2168
2169 #[unsafe(method(mouseEntered:))]
2172 fn mouse_entered(&self, event: &NSEvent) {
2173 ffi_guard::contain(false, || {
2174 input::report_hover(self, event, day_spec::DragPhase::Began)
2175 });
2176 let _: () = unsafe { msg_send![super(self), mouseEntered: event] };
2177 }
2178
2179 #[unsafe(method(mouseMoved:))]
2180 fn mouse_moved(&self, event: &NSEvent) {
2181 ffi_guard::contain(false, || {
2182 input::report_hover(self, event, day_spec::DragPhase::Changed)
2183 });
2184 let _: () = unsafe { msg_send![super(self), mouseMoved: event] };
2185 }
2186
2187 #[unsafe(method(mouseExited:))]
2188 fn mouse_exited(&self, event: &NSEvent) {
2189 ffi_guard::contain(false, || {
2190 input::report_hover(self, event, day_spec::DragPhase::Ended)
2191 });
2192 let _: () = unsafe { msg_send![super(self), mouseExited: event] };
2193 }
2194
2195 #[unsafe(method(updateTrackingAreas))]
2196 fn update_tracking_areas(&self) {
2197 let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
2198 ffi_guard::contain((), || input::refresh_hover_area(self));
2199 }
2200
2201 #[unsafe(method_id(menuForEvent:))]
2202 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
2203 ffi_guard::contain(None, || {
2204 if !self.isSelectable()
2205 && let Some(menu) = inherited_context_menu(self, event)
2206 {
2207 return menu;
2208 }
2209 unsafe { msg_send![super(self), menuForEvent: event] }
2210 })
2211 }
2212
2213 #[unsafe(method(drawRect:))]
2214 fn draw_rect(&self, dirty: NSRect) {
2215 let mut ancestor = unsafe { self.superview() };
2219 let mut selection_color = None;
2220 if !self.ivars().has_runs.get() {
2221 while let Some(view) = ancestor {
2222 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
2223 if unsafe { row.isSelected() } {
2224 selection_color = Some(unsafe {
2225 if row.isEmphasized() {
2226 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
2227 } else {
2228 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
2229 }
2230 });
2231 }
2232 break;
2233 }
2234 ancestor = unsafe { view.superview() };
2235 }
2236 }
2237 let cell = unsafe { self.cell() }
2238 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
2239 if let (Some(color), Some(cell)) = (selection_color, cell) {
2240 let original = unsafe { cell.textColor() };
2241 unsafe {
2244 cell.setTextColor(Some(&color));
2245 let _: () = msg_send![super(self), drawRect: dirty];
2246 cell.setTextColor(original.as_deref());
2247 }
2248 } else {
2249 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
2250 }
2251 }
2252 }
2253
2254 unsafe impl NSObjectProtocol for DayLabel {}
2255 unsafe impl NSTextDelegate for DayLabel {
2256 #[unsafe(method(textDidEndEditing:))]
2260 fn text_did_end_editing(&self, notification: &NSNotification) {
2261 let _: () = unsafe { msg_send![super(self), textDidEndEditing: notification] };
2262 ffi_guard::contain((), || self.clear_selection());
2263 }
2264 }
2265
2266 unsafe impl NSTextViewDelegate for DayLabel {
2267 #[unsafe(method(textViewDidChangeSelection:))]
2272 fn text_view_did_change_selection(&self, notification: &NSNotification) {
2273 if <NSTextField as objc2::ClassType>::class()
2274 .instance_method(sel!(textViewDidChangeSelection:))
2275 .is_some()
2276 {
2277 let _: () =
2278 unsafe { msg_send![super(self), textViewDidChangeSelection: notification] };
2279 }
2280 ffi_guard::contain((), || self.report_selection(notification));
2281 }
2282
2283 #[unsafe(method(textView:clickedOnLink:atIndex:))]
2284 fn clicked_on_link(
2285 &self,
2286 _tv: &NSTextView,
2287 link: &objc2::runtime::AnyObject,
2288 _index: usize,
2289 ) -> bool {
2290 ffi_guard::contain(true, || {
2291 let url: Retained<NSString> = unsafe { msg_send![link, description] };
2293 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
2294 true })
2296 }
2297 }
2298);
2299
2300impl DayLabel {
2301 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
2302 let this = Self::alloc(mtm).set_ivars(LabelIvars {
2303 node,
2304 has_links: Cell::new(false),
2305 has_runs: Cell::new(false),
2306 selectable: Cell::new(false),
2307 wraps: Cell::new(true),
2308 paragraph: Cell::new(day_spec::props::LabelParagraph::default()),
2309 align: Cell::new(day_spec::props::TextAlign::Leading),
2310 direction: Cell::new(None),
2311 stamped: Cell::new(false),
2312 reports_selection: Cell::new(false),
2313 selection: Cell::new(None),
2314 color: Cell::new(None),
2315 role: Cell::new(TextRole::default()),
2316 });
2317 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
2318 unsafe {
2319 this.setStringValue(&NSString::from_str(text));
2320 this.setEditable(false);
2321 this.setSelectable(false);
2322 this.setBordered(false);
2323 this.setBezeled(false);
2324 this.setDrawsBackground(false);
2325 }
2326 this
2327 }
2328
2329 fn set_links(&self, has_links: bool) {
2330 self.ivars().has_links.set(has_links);
2331 unsafe {
2332 self.setSelectable(has_links || self.ivars().selectable.get());
2333 self.setAllowsEditingTextAttributes(has_links);
2334 }
2335 }
2336
2337 fn report_selection(&self, notification: &NSNotification) {
2340 if !self.ivars().reports_selection.get() {
2341 return;
2342 }
2343 let Some(editor) = notification
2344 .object()
2345 .and_then(|o| o.downcast::<NSTextView>().ok())
2346 else {
2347 return;
2348 };
2349 let range = unsafe { editor.selectedRange() };
2350 let text = self.stringValue().to_string();
2351 let now = utf16_span_to_bytes(&text, range.location, range.location + range.length);
2352 if let Some((last, (start, end))) = selection_change(self.ivars().selection.get(), now) {
2353 self.ivars().selection.set(last);
2354 emit(self.ivars().node, Event::TextSelected { start, end });
2355 }
2356 }
2357
2358 fn clear_selection(&self) {
2361 if let Some((_, end)) = self.ivars().selection.take()
2362 && self.ivars().reports_selection.get()
2363 {
2364 let at = end.min(self.stringValue().len());
2365 emit(
2366 self.ivars().node,
2367 Event::TextSelected { start: at, end: at },
2368 );
2369 }
2370 }
2371}
2372
2373fn utf16_span_to_bytes(text: &str, start16: usize, end16: usize) -> ByteSpan {
2377 let (start16, end16) = (start16.min(end16), start16.max(end16));
2378 let mut start = text.len();
2379 let mut end = text.len();
2380 let mut at16 = 0;
2381 let mut found_start = false;
2382 for (byte, ch) in text.char_indices() {
2383 let next16 = at16 + ch.len_utf16();
2384 if !found_start && next16 > start16 {
2385 start = byte;
2386 found_start = true;
2387 }
2388 if next16 > end16 {
2389 end = if at16 >= end16 {
2390 byte
2391 } else {
2392 byte + ch.len_utf8()
2393 };
2394 break;
2395 }
2396 at16 = next16;
2397 }
2398 (start.min(end), end)
2399}
2400
2401type ByteSpan = (usize, usize);
2403
2404fn selection_change(last: Option<ByteSpan>, now: ByteSpan) -> Option<(Option<ByteSpan>, ByteSpan)> {
2409 let now_set = (now.0 != now.1).then_some(now);
2410 if now_set == last {
2411 return None;
2412 }
2413 match now_set {
2414 Some(range) => Some((Some(range), range)),
2415 None => Some((None, (now.0, now.0))),
2416 }
2417}
2418
2419#[cfg(test)]
2420mod label_text_tests {
2421 use super::{
2422 label_line_break, label_line_limit, label_line_points, nstextalign, selection_change,
2423 utf16_span_to_bytes,
2424 };
2425 use day_spec::props::{TextAlign, Truncation};
2426 use objc2_app_kit::{NSLineBreakMode, NSTextAlignment};
2427
2428 #[test]
2429 fn utf16_spans_land_on_character_boundaries() {
2430 let text = "Say déjà vu 🌅 now";
2431 let deja = text.find("déjà").unwrap();
2432 assert_eq!(utf16_span_to_bytes(text, 4, 8), (deja, deja + "déjà".len()));
2433 let sun = text.find('🌅').unwrap();
2434 assert_eq!(utf16_span_to_bytes(text, 12, 14), (sun, sun + 4));
2435 assert_eq!(utf16_span_to_bytes(text, 13, 14), (sun, sun + 4));
2437 assert_eq!(utf16_span_to_bytes(text, 12, 13), (sun, sun + 4));
2438 assert_eq!(utf16_span_to_bytes(text, 8, 4), (deja, deja + "déjà".len()));
2440 assert_eq!(utf16_span_to_bytes(text, 2, 2), (2, 2));
2441 assert_eq!(utf16_span_to_bytes(text, 99, 120), (text.len(), text.len()));
2442 assert_eq!(utf16_span_to_bytes("", 0, 0), (0, 0));
2443 }
2444
2445 #[test]
2446 fn selection_reports_once_per_change() {
2447 assert_eq!(selection_change(None, (3, 3)), None);
2449 assert_eq!(selection_change(None, (2, 5)), Some((Some((2, 5)), (2, 5))));
2451 assert_eq!(selection_change(Some((2, 5)), (2, 5)), None);
2452 assert_eq!(
2453 selection_change(Some((2, 5)), (2, 6)),
2454 Some((Some((2, 6)), (2, 6)))
2455 );
2456 assert_eq!(selection_change(Some((2, 6)), (4, 4)), Some((None, (4, 4))));
2457 }
2458
2459 #[test]
2460 fn paragraph_rules() {
2461 assert_eq!(label_line_limit(false, 3), 1);
2462 assert_eq!(label_line_limit(true, 3), 3);
2463 assert_eq!(label_line_limit(true, 0), 0);
2464 assert_eq!(
2465 label_line_break(1, Truncation::Middle),
2466 NSLineBreakMode::ByTruncatingMiddle
2467 );
2468 assert_eq!(
2469 label_line_break(1, Truncation::Head),
2470 NSLineBreakMode::ByTruncatingHead
2471 );
2472 assert_eq!(
2474 label_line_break(2, Truncation::Head),
2475 NSLineBreakMode::ByWordWrapping
2476 );
2477 assert_eq!(
2478 label_line_break(0, Truncation::Tail),
2479 NSLineBreakMode::ByWordWrapping
2480 );
2481 assert_eq!(label_line_points(2.0, 20.0), Some(40.0));
2482 assert_eq!(label_line_points(0.0, 20.0), None);
2483 assert_eq!(label_line_points(-1.0, 20.0), None);
2484 assert_eq!(label_line_points(f64::NAN, 20.0), None);
2485 assert_eq!(
2486 nstextalign(TextAlign::Trailing, false),
2487 NSTextAlignment::Right
2488 );
2489 assert_eq!(
2490 nstextalign(TextAlign::Trailing, true),
2491 NSTextAlignment::Left
2492 );
2493 assert_eq!(
2494 nstextalign(TextAlign::Leading, true),
2495 NSTextAlignment::Natural
2496 );
2497 assert_eq!(
2498 nstextalign(TextAlign::Justified, false),
2499 NSTextAlignment::Justified
2500 );
2501 }
2502}
2503
2504struct PanMonitor(Retained<objc2::runtime::AnyObject>);
2505impl Drop for PanMonitor {
2506 fn drop(&mut self) {
2507 unsafe { NSEvent::removeMonitor(&self.0) };
2508 }
2509}
2510
2511fn install_sheet_escape_monitor() {
2516 SHEET_ESCAPE_MONITOR.with(|slot| {
2517 if slot.borrow().is_some() {
2518 return;
2519 }
2520 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
2521 let event = unsafe { raw.as_ref() };
2522 ffi_guard::contain(raw.as_ptr(), || {
2523 let Some(mtm) = MainThreadMarker::new() else {
2524 return raw.as_ptr();
2525 };
2526 let escape = unsafe { event.charactersIgnoringModifiers() }
2527 .is_some_and(|s| s.to_string() == "\u{1b}");
2528 let Some(window) = event.window(mtm).filter(|_| escape) else {
2529 return raw.as_ptr();
2530 };
2531 let app = NSApplication::sharedApplication(mtm);
2532 if app.modalWindow().is_some() || window.attachedSheet().is_some() {
2533 return raw.as_ptr();
2534 }
2535 match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
2536 Some(node) => {
2537 emit(
2538 node,
2539 Event::NavBack {
2540 already_popped: false,
2541 },
2542 );
2543 std::ptr::null_mut()
2544 }
2545 None => raw.as_ptr(),
2546 }
2547 })
2548 });
2549 let monitor = unsafe {
2550 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
2551 objc2_app_kit::NSEventMask::KeyDown,
2552 &block,
2553 )
2554 };
2555 *slot.borrow_mut() = monitor.map(PanMonitor);
2556 });
2557}
2558
2559fn install_container_pan_monitor() {
2562 PAN_MONITOR.with(|slot| {
2563 if slot.borrow().is_some() {
2564 return;
2565 }
2566 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
2567 let event = unsafe { raw.as_ref() };
2568 ffi_guard::contain(raw.as_ptr(), || {
2569 let dx = unsafe { event.scrollingDeltaX() };
2570 let dy = unsafe { event.scrollingDeltaY() };
2571 if dx.abs() <= dy.abs() {
2572 return raw.as_ptr();
2573 }
2574 let Some(mtm) = MainThreadMarker::new() else {
2575 return raw.as_ptr();
2576 };
2577 let Some(window) = event.window(mtm) else {
2578 return raw.as_ptr();
2579 };
2580 let Some(content) = window.contentView() else {
2581 return raw.as_ptr();
2582 };
2583 let point =
2584 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2585 let mut view = content.hitTest(point);
2586 while let Some(v) = view {
2587 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
2588 if v.downcast_ref::<DayCanvas>().is_some() {
2589 return raw.as_ptr();
2590 }
2591 let raw_phase = unsafe { event.phase() };
2592 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
2593 day_spec::DragPhase::Began
2594 } else if raw_phase.intersects(
2595 objc2_app_kit::NSEventPhase::Ended
2596 | objc2_app_kit::NSEventPhase::Cancelled,
2597 ) {
2598 day_spec::DragPhase::Ended
2599 } else {
2600 day_spec::DragPhase::Changed
2601 };
2602 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2603 emit(
2604 node,
2605 Event::Pan {
2606 phase,
2607 delta: Point::new(dx, dy),
2608 location: Point::new(p.x, p.y),
2609 },
2610 );
2611 return std::ptr::null_mut();
2612 }
2613 view = unsafe { v.superview() };
2614 }
2615 raw.as_ptr()
2616 })
2617 });
2618 *slot.borrow_mut() = unsafe {
2619 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
2620 objc2_app_kit::NSEventMask::ScrollWheel,
2621 &block,
2622 )
2623 }
2624 .map(PanMonitor);
2625 });
2626}
2627
2628#[derive(Clone, Default)]
2640struct SurfaceStyle {
2641 fill: Option<day_spec::Paint>,
2642 radius: f64,
2643 corners: day_spec::Corners,
2644 border: Option<day_spec::Border>,
2645 shadow: Option<day_spec::Shadow>,
2646 clips: bool,
2647}
2648
2649impl SurfaceStyle {
2650 fn solid(&self) -> Option<day_spec::Ink> {
2652 match self.fill {
2653 Some(day_spec::Paint::Solid(ink)) => Some(ink),
2654 _ => None,
2655 }
2656 }
2657
2658 fn masks(&self) -> bool {
2661 (self.clips || self.radius > 0.0) && self.shadow.is_none()
2662 }
2663
2664 fn outline(&self, rect: NSRect, inset: f64) -> Retained<objc2_app_kit::NSBezierPath> {
2668 use objc2_app_kit::NSBezierPath;
2669 let rect = NSRect::new(
2670 NSPoint::new(rect.origin.x + inset, rect.origin.y + inset),
2671 NSSize::new(
2672 (rect.size.width - 2.0 * inset).max(0.0),
2673 (rect.size.height - 2.0 * inset).max(0.0),
2674 ),
2675 );
2676 let radius = (self.radius - inset).max(0.0);
2677 if radius <= 0.0 || self.corners == day_spec::Corners::NONE {
2678 return NSBezierPath::bezierPathWithRect(rect);
2679 }
2680 if self.corners == day_spec::Corners::ALL {
2681 return NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(rect, radius, radius);
2682 }
2683 let shape = day_spec::Shape::rounded_rect(
2685 day_spec::Rect::new(
2686 rect.origin.x,
2687 rect.origin.y,
2688 rect.size.width,
2689 rect.size.height,
2690 ),
2691 self.corners.radii(radius),
2692 );
2693 bezier(&shape).unwrap_or_else(|| NSBezierPath::bezierPathWithRect(rect))
2694 }
2695}
2696
2697#[derive(Default)]
2698struct FlippedIvars {
2699 surface: RefCell<Option<SurfaceStyle>>,
2700 section_card: Cell<Option<f64>>,
2703 pane_backdrop: Cell<bool>,
2710 keyboard_focus: Cell<bool>,
2713 layer_fill: Cell<bool>,
2716 fill_run: Cell<u64>,
2719}
2720
2721define_class!(
2722 #[unsafe(super(NSView))]
2723 #[thread_kind = MainThreadOnly]
2724 #[name = "DayFlipped"]
2725 #[ivars = FlippedIvars]
2726 struct DayFlipped;
2727
2728 impl DayFlipped {
2729 #[unsafe(method_id(menuForEvent:))]
2730 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
2731 ffi_guard::contain(None, || {
2732 inherited_context_menu(self, event)
2733 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
2734 })
2735 }
2736
2737 #[unsafe(method(isFlipped))]
2738 fn is_flipped(&self) -> bool {
2739 true
2740 }
2741
2742 #[unsafe(method(acceptsFirstResponder))]
2746 fn accepts_first_responder(&self) -> bool {
2747 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2748 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2749 && !ffi_guard::contain(true, || input::subtree_disabled(self))
2750 }
2751
2752 #[unsafe(method(canBecomeKeyView))]
2755 fn can_become_key_view(&self) -> bool {
2756 self.acceptsFirstResponder() && !self.isHiddenOrHasHiddenAncestor()
2757 }
2758
2759 #[unsafe(method_id(hitTest:))]
2764 fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
2765 ffi_guard::contain(None, || input::container_hit_test(self, point))
2766 }
2767
2768 #[unsafe(method(mouseEntered:))]
2771 fn mouse_entered(&self, event: &NSEvent) {
2772 if !ffi_guard::contain(true, || {
2773 input::report_hover(self, event, day_spec::DragPhase::Began)
2774 }) {
2775 let _: () = unsafe { msg_send![super(self), mouseEntered: event] };
2776 }
2777 }
2778
2779 #[unsafe(method(mouseMoved:))]
2780 fn mouse_moved(&self, event: &NSEvent) {
2781 if !ffi_guard::contain(true, || {
2782 input::report_hover(self, event, day_spec::DragPhase::Changed)
2783 }) {
2784 let _: () = unsafe { msg_send![super(self), mouseMoved: event] };
2785 }
2786 }
2787
2788 #[unsafe(method(mouseExited:))]
2789 fn mouse_exited(&self, event: &NSEvent) {
2790 if !ffi_guard::contain(true, || {
2791 input::report_hover(self, event, day_spec::DragPhase::Ended)
2792 }) {
2793 let _: () = unsafe { msg_send![super(self), mouseExited: event] };
2794 }
2795 }
2796
2797 #[unsafe(method(updateTrackingAreas))]
2798 fn update_tracking_areas(&self) {
2799 let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
2800 ffi_guard::contain((), || input::refresh_hover_area(self));
2801 }
2802
2803 #[unsafe(method(drawFocusRingMask))]
2806 fn draw_focus_ring_mask(&self) {
2807 let bounds = self.bounds();
2808 let outline = match self.ivars().surface.borrow().as_ref() {
2809 Some(surface) => surface.outline(bounds, 0.0),
2810 None => objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds),
2811 };
2812 outline.fill();
2813 }
2814
2815 #[unsafe(method(focusRingMaskBounds))]
2816 fn focus_ring_mask_bounds(&self) -> NSRect {
2817 if self.ivars().keyboard_focus.get() {
2818 self.bounds()
2819 } else {
2820 NSRect::ZERO
2821 }
2822 }
2823
2824 #[unsafe(method(mouseDown:))]
2828 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2829 if transfer::pressed(self, event) { return; }
2830 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2831 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2832 && let Some(window) = self.window()
2833 {
2834 window.makeFirstResponder(Some(self));
2835 }
2836 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2837 }
2838
2839 #[unsafe(method(becomeFirstResponder))]
2840 fn become_first_responder(&self) -> bool {
2841 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2842 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2843 let by_key = NSApplication::sharedApplication(self.mtm())
2845 .currentEvent()
2846 .is_some_and(|e| e.r#type() == NSEventType::KeyDown);
2847 self.ivars().keyboard_focus.set(by_key);
2848 self.noteFocusRingMaskChanged();
2849 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2850 }
2851 true
2852 }
2853
2854 #[unsafe(method(resignFirstResponder))]
2855 fn resign_first_responder(&self) -> bool {
2856 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2857 if self.ivars().keyboard_focus.replace(false) {
2858 self.noteFocusRingMaskChanged();
2859 }
2860 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2861 ffi_guard::contain((), || {
2862 input::forget_keys(node);
2863 emit(node, Event::FocusChanged(false));
2864 });
2865 }
2866 true
2867 }
2868
2869 #[unsafe(method(keyDown:))]
2875 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2876 let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2877 let handled = ffi_guard::contain(false, || {
2878 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2879 return false;
2880 };
2881 short_route_key_down(node, event)
2882 });
2883 if !handled {
2884 let _: () = unsafe { msg_send![super(self), keyDown: event] };
2885 }
2886 }
2887
2888 #[unsafe(method(rightMouseDown:))]
2892 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2893 if let Some(menu) = self.menuForEvent(event) {
2894 unsafe {
2895 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self);
2896 };
2897 } else {
2898 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2899 }
2900 }
2901
2902 #[unsafe(method(drawRect:))]
2903 fn draw_rect(&self, _dirty: NSRect) {
2904 let paint = || {
2905 if self.ivars().pane_backdrop.get() {
2906 let bounds = self.bounds();
2907 unsafe {
2908 NSColor::windowBackgroundColor().setFill();
2911 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2912 }
2913 }
2914 if let Some(radius) = self.ivars().section_card.get() {
2915 let bounds = self.bounds();
2916 unsafe {
2917 let cls = objc2::class!(NSColor);
2920 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2921 let color: objc2::rc::Retained<NSColor> = if has {
2922 msg_send![cls, quaternarySystemFillColor]
2923 } else {
2924 msg_send![cls, controlBackgroundColor]
2925 };
2926 color.setFill();
2927 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2928 bounds, radius, radius,
2929 );
2930 path.fill();
2931 }
2932 }
2933 if let Some(surface) = self.ivars().surface.borrow().as_ref() {
2934 let bounds = self.bounds();
2935 let outline = surface.outline(bounds, 0.0);
2936 match &surface.fill {
2937 Some(day_spec::Paint::Solid(ink)) => {
2939 if !self.ivars().layer_fill.get() {
2940 color::nsink(*ink).setFill();
2941 outline.fill();
2942 }
2943 }
2944 Some(paint) => {
2945 let area = day_spec::Rect::new(
2948 bounds.origin.x,
2949 bounds.origin.y,
2950 bounds.size.width,
2951 bounds.size.height,
2952 );
2953 NSGraphicsContext::saveGraphicsState_class();
2954 outline.addClip();
2955 draw_gradient_in(paint, area);
2956 NSGraphicsContext::restoreGraphicsState_class();
2957 }
2958 None => {}
2959 }
2960 }
2961 };
2962 match color::standard_appearance(&self.effectiveAppearance()) {
2971 Some(appearance) => {
2972 let block = block2::StackBlock::new(paint);
2973 appearance.performAsCurrentDrawingAppearance(&block);
2974 }
2975 None => paint(),
2976 }
2977 }
2978
2979 #[unsafe(method(viewDidChangeEffectiveAppearance))]
2983 fn view_did_change_effective_appearance(&self) {
2984 let _: () = unsafe { msg_send![super(self), viewDidChangeEffectiveAppearance] };
2985 ffi_guard::contain((), || {
2986 self.sync_layer();
2987 NSView::setNeedsDisplay(self, true);
2988 });
2989 }
2990 }
2991 unsafe impl NSObjectProtocol for DayFlipped {}
2992 unsafe impl NSDraggingSource for DayFlipped {
2993 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2994 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2995 }
2996 impl DayFlipped {
2997 #[unsafe(method(mouseDragged:))]
2998 fn transfer_dragged(&self, event: &NSEvent) {
2999 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
3000 }
3001 #[unsafe(method(draggingEntered:))]
3002 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
3003 #[unsafe(method(draggingUpdated:))]
3004 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
3005 #[unsafe(method(performDragOperation:))]
3006 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
3007 #[unsafe(method(draggingExited:))]
3009 fn transfer_exited(&self, _info: Option<&ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>>) {
3010 ffi_guard::contain((), || transfer::leave(self));
3011 }
3012 #[unsafe(method(draggingEnded:))]
3015 fn transfer_ended(&self, _info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) {
3016 ffi_guard::contain((), || transfer::leave(self));
3017 }
3018
3019 #[unsafe(method(setFrameSize:))]
3022 fn set_frame_size(&self, size: NSSize) {
3023 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3024 if self.ivars().surface.borrow().is_some() {
3025 NSView::setNeedsDisplay(self, true);
3026 self.sync_layer();
3027 }
3028 }
3029
3030 #[unsafe(method(setBoundsSize:))]
3033 fn set_bounds_size(&self, size: NSSize) {
3034 let _: () = unsafe { msg_send![super(self), setBoundsSize: size] };
3035 self.sync_layer();
3036 }
3037 }
3038
3039);
3040
3041impl DayFlipped {
3042 fn new(mtm: MainThreadMarker) -> Retained<Self> {
3043 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
3044 unsafe { msg_send![super(this), init] }
3045 }
3046
3047 fn set_section_card(&self, corner_radius: f64) {
3049 self.ivars().section_card.set(Some(corner_radius));
3050 unsafe {
3051 let _: () = msg_send![self, setNeedsDisplay: true];
3052 }
3053 }
3054
3055 fn set_pane_backdrop(&self) {
3057 self.ivars().pane_backdrop.set(true);
3058 unsafe {
3059 let _: () = msg_send![self, setNeedsDisplay: true];
3060 }
3061 }
3062
3063 fn set_surface(&self, p: &ContainerProps) {
3069 let shadow = p
3071 .shadow
3072 .filter(|s| !matches!(s.color, day_spec::Ink::Fixed(c) if c.a <= 0.0));
3073 *self.ivars().surface.borrow_mut() = Some(SurfaceStyle {
3074 fill: p.fill.clone(),
3075 radius: p.corner_radius,
3076 corners: p.corners,
3077 border: p.border,
3078 shadow,
3079 clips: p.clips,
3080 });
3081 NSView::setNeedsDisplay(self, true);
3082 self.sync_layer();
3083 }
3084
3085 fn sync_layer(&self) {
3102 let Some(s) = self.ivars().surface.borrow().clone() else {
3103 return;
3104 };
3105 let border = s.border.filter(|b| b.width > 0.0);
3106 let masks = s.masks();
3107 if self.layer().is_none() {
3108 if !masks && border.is_none() && s.shadow.is_none() {
3109 return;
3110 }
3111 self.setWantsLayer(true);
3112 }
3113 let Some(layer) = self.layer() else {
3114 return;
3115 };
3116 let size = layer.bounds().size;
3117 let half = (size.width.min(size.height) / 2.0).max(0.0);
3118 layer.setCornerRadius(s.radius.min(half));
3119 layer.setMaskedCorners(corner_mask(s.corners));
3120 layer.setMasksToBounds(masks);
3121 if let Some(b) = border {
3122 layer.setBorderWidth(b.width.min(half));
3123 layer.setBorderColor(Some(&color::cg_for(self, b.color)));
3124 } else {
3125 layer.setBorderWidth(0.0);
3126 layer.setBorderColor(None);
3127 }
3128 match s.shadow {
3129 Some(sh) => {
3130 let native = objc2_app_kit::NSShadow::new();
3131 native.setShadowColor(Some(&nscolor(color::color_for(self, sh.color))));
3132 native.setShadowOffset(NSSize::new(sh.dx, sh.dy));
3133 native.setShadowBlurRadius(sh.blur.max(0.0) / 2.0);
3134 self.setShadow(Some(&native));
3135 let outline = s.outline(self.bounds(), 0.0);
3136 layer.setShadowPath(Some(&*unsafe { outline.CGPath() }));
3138 }
3139 None => {
3140 if self.shadow().is_some() {
3141 self.setShadow(None);
3142 layer.setShadowPath(None);
3143 }
3144 }
3145 }
3146 }
3147
3148 fn set_background(&self, fill: Option<day_spec::Paint>) {
3151 self.ivars()
3152 .surface
3153 .borrow_mut()
3154 .get_or_insert_default()
3155 .fill = fill;
3156 NSView::setNeedsDisplay(self, true);
3157 }
3158}
3159
3160fn corner_mask(corners: day_spec::Corners) -> objc2_quartz_core::CACornerMask {
3163 use objc2_quartz_core::CACornerMask;
3164 let mut mask = CACornerMask::empty();
3165 for (corner, layer_corner) in [
3166 (
3167 day_spec::Corners::TOP_LEFT,
3168 CACornerMask::LayerMinXMinYCorner,
3169 ),
3170 (
3171 day_spec::Corners::TOP_RIGHT,
3172 CACornerMask::LayerMaxXMinYCorner,
3173 ),
3174 (
3175 day_spec::Corners::BOTTOM_RIGHT,
3176 CACornerMask::LayerMaxXMaxYCorner,
3177 ),
3178 (
3179 day_spec::Corners::BOTTOM_LEFT,
3180 CACornerMask::LayerMinXMaxYCorner,
3181 ),
3182 ] {
3183 if corners.contains(corner) {
3184 mask |= layer_corner;
3185 }
3186 }
3187 mask
3188}
3189
3190struct CanvasIvars;
3195
3196define_class!(
3197 #[unsafe(super(NSView))]
3198 #[thread_kind = MainThreadOnly]
3199 #[name = "DayCanvas"]
3200 #[ivars = CanvasIvars]
3201 struct DayCanvas;
3202
3203 impl DayCanvas {
3204 #[unsafe(method(isFlipped))]
3205 fn is_flipped(&self) -> bool {
3206 true
3207 }
3208
3209 #[unsafe(method_id(menuForEvent:))]
3213 fn menu_for_event(
3214 &self,
3215 event: &objc2_app_kit::NSEvent,
3216 ) -> Option<Retained<NSMenu>> {
3217 let f = CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<Self>(self) as usize));
3218 let Some(f) = f else {
3219 return unsafe { msg_send![super(self), menuForEvent: event] };
3220 };
3221 ffi_guard::contain(None, || {
3223 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3224 let items = f(day_spec::Point::new(p.x, p.y));
3225 if items.is_empty() {
3226 return None;
3227 }
3228 Some(build_ns_menu(self.mtm(), "", &items))
3229 })
3230 }
3231
3232 #[unsafe(method(acceptsFirstResponder))]
3237 fn accepts_first_responder(&self) -> bool {
3238 !ffi_guard::contain(true, || input::subtree_disabled(self))
3239 }
3240
3241 #[unsafe(method_id(hitTest:))]
3245 fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
3246 let hit: Option<Retained<NSView>> = unsafe { msg_send![super(self), hitTest: point] };
3247 ffi_guard::contain(None, || {
3248 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3249 let keys = KEY_NODES
3250 .with(|t| t.get(ptr))
3251 .is_some_and(day_spec::keys::handled);
3252 input::leaf_hit_test(self, hit, keys || input::takes_pointer(self))
3253 })
3254 }
3255
3256 #[unsafe(method(updateTrackingAreas))]
3259 fn update_tracking_areas(&self) {
3260 let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
3261 ffi_guard::contain((), || input::refresh_hover_area(self));
3262 }
3263
3264 #[unsafe(method(mouseDown:))]
3268 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
3269 if let Some(window) = self.window() {
3270 window.makeFirstResponder(Some(self));
3271 }
3272 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
3273 }
3274
3275 #[unsafe(method(becomeFirstResponder))]
3278 fn become_first_responder(&self) -> bool {
3279 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3280 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
3281 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
3282 }
3283 true
3284 }
3285
3286 #[unsafe(method(resignFirstResponder))]
3287 fn resign_first_responder(&self) -> bool {
3288 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3289 if MARKED.with(|t| t.remove(ptr)).is_some()
3292 && let Some(context) = self.inputContext()
3293 {
3294 context.discardMarkedText();
3295 }
3296 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
3297 ffi_guard::contain((), || {
3298 input::forget_keys(node);
3299 emit(node, Event::FocusChanged(false));
3300 });
3301 }
3302 true
3303 }
3304
3305 #[unsafe(method(keyDown:))]
3311 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
3312 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3313 let handled = ffi_guard::contain(false, || {
3314 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
3315 return false;
3316 };
3317 if !day_spec::keys::handled(node) {
3321 return false;
3322 }
3323 if day_spec::keys::text(node) {
3324 return full_route_key_down(self, node, event);
3325 }
3326 short_route_key_down(node, event)
3327 });
3328 if !handled {
3329 let _: () = unsafe { msg_send![super(self), keyDown: event] };
3330 }
3331 }
3332
3333 #[unsafe(method_id(inputContext))]
3338 fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
3339 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3340 let takes_keyboard = KEY_NODES
3341 .with(|t| t.get(ptr))
3342 .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
3343 if takes_keyboard {
3344 unsafe { msg_send![super(self), inputContext] }
3345 } else {
3346 None
3347 }
3348 }
3349
3350 #[unsafe(method(drawRect:))]
3351 fn draw_rect(&self, _dirty: NSRect) {
3352 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3353 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
3354 paint_ops(&ops, 1.0);
3355 }
3356
3357 #[unsafe(method(mouseEntered:))]
3360 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
3361 self.report_hover(event, day_spec::DragPhase::Began);
3362 }
3363
3364 #[unsafe(method(mouseMoved:))]
3365 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
3366 self.report_hover(event, day_spec::DragPhase::Changed);
3367 }
3368
3369 #[unsafe(method(mouseExited:))]
3370 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
3371 self.report_hover(event, day_spec::DragPhase::Ended);
3372 }
3373
3374 #[unsafe(method(rotateWithEvent:))]
3379 fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
3380 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3381 let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
3382 let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
3383 return;
3384 };
3385 ffi_guard::contain((), || {
3386 let tick = -f64::from(event.rotation()).to_radians();
3387 let raw = event.phase();
3388 let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
3389 ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
3390 (day_spec::DragPhase::Began, tick)
3391 } else if raw.intersects(
3392 objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
3393 ) {
3394 let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
3395 (day_spec::DragPhase::Ended, total)
3396 } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
3397 let total = ROTATE_ANGLE
3398 .with(|t| {
3399 t.with(ptr, |a| {
3400 *a += tick;
3401 *a
3402 })
3403 })
3404 .unwrap_or(tick);
3405 (day_spec::DragPhase::Changed, total)
3406 } else {
3407 (day_spec::DragPhase::Changed, tick)
3408 };
3409 let win = event.locationInWindow();
3410 let loc = self.convertPoint_fromView(win, None);
3411 emit(
3412 node,
3413 Event::Rotate {
3414 phase,
3415 rotation,
3416 location: Point::new(loc.x, loc.y),
3417 },
3418 );
3419 });
3420 }
3421
3422 #[unsafe(method(scrollWheel:))]
3423 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
3424 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3425 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
3426 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
3427 return;
3428 };
3429 ffi_guard::contain((), || {
3430 let raw = unsafe { event.phase() };
3433 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
3434 day_spec::DragPhase::Began
3435 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
3436 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
3437 {
3438 day_spec::DragPhase::Ended
3439 } else {
3440 day_spec::DragPhase::Changed
3441 };
3442 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
3443 event.scrollingDeltaY()
3444 });
3445 let win = unsafe { event.locationInWindow() };
3446 let loc = self.convertPoint_fromView(win, None);
3447 emit(
3448 node,
3449 Event::Pan {
3450 phase,
3451 delta,
3452 location: Point::new(loc.x, loc.y),
3453 },
3454 );
3455 });
3456 }
3457 }
3458
3459 unsafe impl NSObjectProtocol for DayCanvas {}
3460
3461 unsafe impl NSTextInputClient for DayCanvas {
3465 #[unsafe(method(insertText:replacementRange:))]
3466 unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
3467 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3468 MARKED.with(|t| t.remove(ptr));
3469 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
3470 return;
3471 };
3472 let text = text_of_input_string(string);
3473 if text.is_empty() {
3474 return;
3475 }
3476 ffi_guard::contain((), || {
3477 let interpreting = INTERPRETING.with(|i| {
3478 i.borrow()
3479 .as_ref()
3480 .map(|i| (i.key.clone(), i.mods, i.phase, i.event.clone()))
3481 });
3482 let event = match interpreting {
3483 Some((key, mods, phase, press)) if text.chars().count() == 1 => {
3486 if phase == day_spec::KeyPhase::Down {
3487 input::claim_key(&press, node, key.clone());
3488 }
3489 day_spec::KeyEvent::typed_by(key, text, mods).with_phase(phase)
3490 }
3491 Some((_, mods, _, _)) => day_spec::KeyEvent::typed_text(text, mods),
3493 None => day_spec::KeyEvent::typed_text(text, 0),
3495 };
3496 emit(node, Event::Key(event));
3497 });
3498 }
3499
3500 #[unsafe(method(doCommandBySelector:))]
3505 unsafe fn do_command_by_selector(&self, _selector: Sel) {}
3506
3507 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
3508 unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
3509 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3510 let text = text_of_input_string(string);
3511 if text.is_empty() {
3512 MARKED.with(|t| t.remove(ptr));
3513 } else {
3514 MARKED.with(|t| t.insert(ptr, text));
3515 }
3516 }
3517
3518 #[unsafe(method(unmarkText))]
3519 fn unmark_text(&self) {
3520 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3521 MARKED.with(|t| t.remove(ptr));
3522 }
3523
3524 #[unsafe(method(selectedRange))]
3525 fn selected_range(&self) -> NSRange {
3526 NSRange::new(objc2_foundation::NSNotFound as usize, 0)
3527 }
3528
3529 #[unsafe(method(markedRange))]
3530 fn marked_range(&self) -> NSRange {
3531 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3532 match MARKED.with(|t| t.get(ptr)) {
3533 Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
3534 None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
3535 }
3536 }
3537
3538 #[unsafe(method(hasMarkedText))]
3539 fn has_marked_text(&self) -> bool {
3540 let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3541 MARKED.with(|t| t.contains(ptr))
3542 }
3543
3544 #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
3545 unsafe fn attributed_substring(
3546 &self,
3547 _range: NSRange,
3548 _actual: objc2_foundation::NSRangePointer,
3549 ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
3550 None
3551 }
3552
3553 #[unsafe(method_id(validAttributesForMarkedText))]
3554 fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
3555 NSArray::new()
3556 }
3557
3558 #[unsafe(method(firstRectForCharacterRange:actualRange:))]
3561 unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
3562 let bounds = self.bounds();
3563 let in_window = self.convertRect_toView(bounds, None);
3564 match self.window() {
3565 Some(window) => window.convertRectToScreen(in_window),
3566 None => in_window,
3567 }
3568 }
3569
3570 #[unsafe(method(characterIndexForPoint:))]
3571 fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
3572 objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
3573 }
3574 }
3575);
3576
3577impl DayCanvas {
3578 fn new(mtm: MainThreadMarker) -> Retained<Self> {
3579 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
3580 unsafe { msg_send![super(this), init] }
3581 }
3582
3583 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
3591 ffi_guard::contain(false, || input::report_hover(self, event, phase));
3592 }
3593}
3594
3595struct GestureIvars {
3600 node: NodeId,
3601 kind: day_spec::GestureKind,
3602}
3603
3604define_class!(
3605 #[unsafe(super(NSObject))]
3606 #[thread_kind = MainThreadOnly]
3607 #[name = "DayGesture"]
3608 #[ivars = GestureIvars]
3609 struct DayGesture;
3610
3611 unsafe impl NSObjectProtocol for DayGesture {}
3612
3613 unsafe impl NSGestureRecognizerDelegate for DayGesture {
3616 #[unsafe(method(gestureRecognizer:shouldAttemptToRecognizeWithEvent:))]
3619 fn should_attempt(&self, _g: &NSGestureRecognizer, event: &NSEvent) -> bool {
3620 !(self.ivars().kind == day_spec::GestureKind::LongPress
3621 && event.modifierFlags().contains(NSEventModifierFlags::Control))
3622 }
3623
3624 #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))]
3628 fn simultaneous(&self, _g: &NSGestureRecognizer, other: &NSGestureRecognizer) -> bool {
3629 use day_spec::GestureKind::{DoubleTap, Tap};
3630 let mine = self.ivars().kind;
3631 let theirs = unsafe { other.delegate() }.and_then(|d| {
3632 let obj: &AnyObject = d.as_ref();
3633 obj.downcast_ref::<DayGesture>().map(|g| g.ivars().kind)
3634 });
3635 matches!((mine, theirs), (Tap, Some(DoubleTap)) | (DoubleTap, Some(Tap)))
3636 }
3637 }
3638
3639 impl DayGesture {
3640 #[unsafe(method(fire:))]
3641 fn fire(&self, g: &NSGestureRecognizer) {
3642 ffi_guard::contain((), || {
3643 let node = self.ivars().node;
3644 let view = g.view();
3645 let loc = g.locationInView(view.as_deref());
3646 let at = match view.as_deref() {
3648 Some(v) => input::top_left(v, loc),
3649 None => Point::new(loc.x, loc.y),
3650 };
3651 let up = view.as_deref().is_some_and(|v| !v.isFlipped());
3652 let phase = match g.state() {
3653 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
3654 NSGestureRecognizerState::Ended
3655 | NSGestureRecognizerState::Cancelled
3656 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
3657 _ => day_spec::DragPhase::Changed,
3658 };
3659 let obj: &objc2::runtime::AnyObject = g.as_ref();
3660 match self.ivars().kind {
3661 day_spec::GestureKind::Drag => {
3662 let pan = obj.downcast_ref::<NSPanGestureRecognizer>();
3663 let flip = |p: NSPoint| Point::new(p.x, if up { -p.y } else { p.y });
3664 let translation = pan.map_or(Point::ZERO, |pan| {
3665 flip(unsafe { pan.translationInView(view.as_deref()) })
3666 });
3667 if g.state() == NSGestureRecognizerState::Ended
3671 && let Some(pan) = pan
3672 {
3673 let velocity = flip(unsafe { pan.velocityInView(view.as_deref()) });
3674 emit(
3675 node,
3676 Event::GestureVelocity {
3677 kind: day_spec::GestureKind::Drag,
3678 velocity,
3679 },
3680 );
3681 }
3682 emit(node, Event::Drag { phase, location: at, translation });
3683 }
3684 day_spec::GestureKind::LongPress => {
3685 let key = view.as_deref().map_or(0, ptr_of);
3688 match g.state() {
3689 NSGestureRecognizerState::Began => {
3690 input::LONG_HELD.with(|t| t.insert(key, ()));
3691 emit(node, Event::LongPress(at));
3692 }
3693 NSGestureRecognizerState::Ended
3694 | NSGestureRecognizerState::Cancelled
3695 | NSGestureRecognizerState::Failed => {
3696 <AppKit as Platform>::post(Box::new(move || {
3698 input::LONG_HELD.with(|t| t.take(key));
3699 }));
3700 }
3701 _ => {}
3702 }
3703 }
3704 day_spec::GestureKind::DoubleTap => {
3705 if let Some(v) = view.as_deref() {
3706 input::cancel_held_tap(v);
3707 }
3708 emit(node, Event::DoubleTap(at));
3709 }
3710 day_spec::GestureKind::Pinch => {
3711 let scale = if let Some(m) =
3714 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
3715 {
3716 1.0 + unsafe { m.magnification() }
3717 } else {
3718 1.0
3719 };
3720 emit(node, Event::Pinch { phase, scale, location: at });
3721 }
3722 _ => {
3723 let Some(v) = view.as_deref() else {
3724 emit(node, Event::Tap(at));
3725 return;
3726 };
3727 if input::LONG_HELD.with(|t| t.take(ptr_of(v))).is_some() {
3728 return;
3729 }
3730 let double = GESTURES.with(|m| {
3731 m.borrow().get(&ptr_of(v)).is_some_and(|targets| {
3732 targets
3733 .iter()
3734 .any(|t| t.ivars().kind == day_spec::GestureKind::DoubleTap)
3735 })
3736 });
3737 let clicks = NSApplication::sharedApplication(self.mtm())
3738 .currentEvent()
3739 .map_or(1, |e| {
3740 if matches!(
3741 e.r#type(),
3742 NSEventType::LeftMouseUp | NSEventType::LeftMouseDown
3743 ) {
3744 e.clickCount()
3745 } else {
3746 1
3747 }
3748 });
3749 match input::tap_disposition(double, clicks) {
3750 input::TapDisposition::Immediate => emit(node, Event::Tap(at)),
3751 input::TapDisposition::Pending => input::hold_tap(v, node, at),
3752 input::TapDisposition::Drop => {}
3753 }
3754 }
3755 }
3756 });
3757 }
3758 }
3759);
3760
3761impl DayGesture {
3762 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
3763 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
3764 unsafe { msg_send![super(this), init] }
3765 }
3766}
3767
3768struct NavHeader {
3777 bar: Retained<NSView>,
3778 title: Retained<NSTextField>,
3779 titles: Vec<String>,
3781 _target: Retained<DayTarget>,
3782}
3783
3784const NAV_HEADER_H: f64 = 34.0;
3786
3787use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
3791
3792fn take_list_placement(state: &mut NavState) -> Option<f64> {
3796 if !state.list_visible || state.list_positioned {
3797 return None;
3798 }
3799 state.list_positioned = true;
3800 state.list_width
3801}
3802
3803const NAV_TABVIEW_INSET: f64 = 12.0;
3806const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
3807
3808struct TabHost {
3820 view: Retained<objc2_app_kit::NSTabView>,
3821 target: Option<Retained<DayTarget>>,
3824}
3825
3826thread_local! {
3827 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3830}
3831
3832fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
3836 unsafe {
3837 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
3838 for (i, title) in titles.iter().enumerate().take(n) {
3839 tabs.view
3840 .tabViewItemAtIndex(i as isize)
3841 .setLabel(&NSString::from_str(title));
3842 }
3843 if n > 0 {
3844 TAB_PICK_SUPPRESS.with(|s| s.set(true));
3845 tabs.view
3846 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
3847 TAB_PICK_SUPPRESS.with(|s| s.set(false));
3848 }
3849 }
3850}
3851
3852fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
3856 let Some((titles, node)) = NAV_MENUS.with(|m| {
3857 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
3858 let ivars = d.ivars();
3859 (
3860 ivars
3861 .items
3862 .borrow()
3863 .iter()
3864 .map(std::string::ToString::to_string)
3865 .collect::<Vec<String>>(),
3866 ivars.node,
3867 )
3868 })
3869 }) else {
3870 return;
3871 };
3872 let mut up = unsafe { menu.superview() };
3873 while let Some(v) = up {
3874 let reached = NAV_STATE.with(|m| {
3875 let mut m = m.borrow_mut();
3876 let Some(s) = m.get_mut(&ptr_of(&v)) else {
3877 return false;
3878 };
3879 let selected = s.selected;
3880 if let Some(tabs) = s.tabs.as_mut() {
3881 if tabs.target.is_none() {
3882 let target = DayTarget::new(mtm, node);
3883 unsafe {
3884 tabs.view
3885 .setDelegate(Some(ProtocolObject::from_ref(&*target)));
3886 };
3887 tabs.target = Some(target);
3888 }
3889 sync_tab_labels(tabs, &titles, selected);
3890 }
3891 true
3892 });
3893 if reached {
3894 return;
3895 }
3896 up = unsafe { v.superview() };
3897 }
3898}
3899
3900struct NavState {
3901 sidebar_wrap: Retained<NSView>,
3902 detail_wrap: Retained<NSView>,
3903 split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3908 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
3912 list_wrap: Option<Retained<NSView>>,
3918 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
3919 list_width: Option<f64>,
3922 list_visible: bool,
3926 list_positioned: bool,
3932 pages: Vec<Retained<NSView>>,
3935 sidebar_page: Option<Retained<NSView>>,
3938 list_page: Option<Retained<NSView>>,
3941 positioned: bool,
3942 presentation: NavPresentation,
3946 selected: usize,
3949 tabs: Option<TabHost>,
3953 header: Option<NavHeader>,
3955 root_title: String,
3958 node: NodeId,
3960 title_strip: f64,
3964}
3965
3966fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
3978 let pane = view_of(&DayFlipped::new(mtm));
3979 unsafe {
3980 wrap.setFrame(pane.bounds());
3981 wrap.setAutoresizingMask(
3982 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
3983 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
3984 );
3985 pane.addSubview(wrap);
3986 }
3987 pane
3988}
3989
3990fn place_below_strip(wrap: &NSView, strip: f64) {
3992 let Some(pane) = (unsafe { wrap.superview() }) else {
3993 return;
3994 };
3995 let b = pane.bounds();
3996 unsafe {
3997 wrap.setFrame(NSRect::new(
3998 NSPoint::new(0.0, strip),
3999 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
4000 ));
4001 };
4002}
4003
4004fn build_nav_header(
4012 mtm: MainThreadMarker,
4013 id: NodeId,
4014 detail_wrap: &NSView,
4015 root_title: &str,
4016) -> NavHeader {
4017 let bar = view_of(&DayFlipped::new(mtm));
4018 let target = DayTarget::new(mtm, id);
4019 let back = unsafe {
4020 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
4023 .expect("NSGoBackTemplate");
4024 let tobj: &objc2::runtime::AnyObject = target.as_ref();
4025 objc2_app_kit::NSButton::buttonWithImage_target_action(
4026 &img,
4027 Some(tobj),
4028 Some(sel!(navBack:)),
4029 mtm,
4030 )
4031 };
4032 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
4033 unsafe {
4034 back.setFrame(NSRect::new(
4035 NSPoint::new(6.0, 4.0),
4036 NSSize::new(30.0, NAV_HEADER_H - 8.0),
4037 ));
4038 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
4039 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
4040 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
4041 title.setFrame(NSRect::new(
4042 NSPoint::new(44.0, 9.0),
4043 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
4044 ));
4045 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
4046 bar.setFrame(NSRect::new(
4047 NSPoint::new(0.0, 0.0),
4048 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
4049 ));
4050 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
4051 bar.addSubview(&back);
4052 bar.addSubview(&title);
4053 bar.setHidden(true);
4054 detail_wrap.addSubview(&bar);
4055 }
4056 NavHeader {
4057 bar,
4058 title,
4059 titles: vec![root_title.to_string()],
4060 _target: target,
4061 }
4062}
4063
4064fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
4068 let b = wrap.bounds();
4069 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
4070 NSRect::new(
4071 NSPoint::new(0.0, top),
4072 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
4073 )
4074}
4075
4076fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
4083 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
4084 if out.is_some() {
4085 return;
4086 }
4087 let found = NAV_MENUS.with(|m| {
4088 m.borrow()
4089 .get(&(std::ptr::from_ref::<NSView>(v) as usize))
4090 .map(|(_, d)| {
4091 let ivars = d.ivars();
4092 (
4093 ivars
4094 .items
4095 .borrow()
4096 .iter()
4097 .map(std::string::ToString::to_string)
4098 .collect(),
4099 ivars.node,
4100 )
4101 })
4102 });
4103 if found.is_some() {
4104 *out = found;
4105 return;
4106 }
4107 for sub in &unsafe { v.subviews() } {
4108 walk(&sub, out);
4109 }
4110 }
4111 let mut out = None;
4112 walk(page, &mut out);
4113 out
4114}
4115
4116fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
4119 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
4120 unsafe {
4121 item.setCanCollapse(shown);
4122 item.setCollapsed(!shown);
4123 match pres {
4124 NavPresentation::Split | NavPresentation::Rail => {
4130 item.setAllowsFullHeightLayout(true);
4131 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
4132 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
4133 }
4134 NavPresentation::Stack | NavPresentation::Tabs => {
4137 item.setMinimumThickness(0.0);
4138 item.setMaximumThickness(0.0);
4139 }
4140 }
4141 }
4142}
4143
4144pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
4150 NAV_STATE.with(|m| {
4151 m.borrow()
4152 .values()
4153 .find(|st| {
4154 st.list_item.is_some()
4155 && st
4156 .sidebar_wrap
4157 .window()
4158 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
4159 })
4160 .map(|st| unsafe { st.split_vc.splitView() })
4161 })
4162}
4163
4164fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
4165 let visible = pages.len() >= 2;
4166 hdr.bar.setHidden(!visible);
4167 unsafe {
4168 hdr.title.setStringValue(&NSString::from_str(
4169 hdr.titles.last().map_or("", String::as_str),
4170 ));
4171 }
4172 let frame = nav_page_frame(wrap, visible);
4173 for page in pages {
4174 unsafe { page.setFrame(frame) };
4175 }
4176}
4177
4178fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
4193 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
4194 NAV_STATE.with(|m| {
4195 let st = m.borrow();
4196 let s = st.get(&ptr_of(host))?;
4197 Some((
4198 s.sidebar_page.clone(),
4199 s.detail_wrap.clone(),
4200 s.sidebar_wrap.clone(),
4201 s.sidebar_item.clone(),
4202 s.presentation,
4203 s.root_title.clone(),
4204 s.node,
4205 s.selected,
4206 ))
4207 })
4208 else {
4209 return;
4210 };
4211 if was == next {
4212 return;
4213 }
4214 apply_sidebar_item(&sidebar_item, next);
4215 NAV_STATE.with(|m| {
4220 if let Some(s) = m.borrow().get(&ptr_of(host)) {
4221 unsafe { s.split_vc.splitView().layoutSubtreeIfNeeded() };
4222 }
4223 });
4224 let stacked = next == NavPresentation::Stack;
4227 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
4228 if stacked && header.is_none() {
4229 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
4230 }
4231 if let Some(hdr) = header.as_ref() {
4232 hdr.bar.setHidden(true);
4233 }
4234 let mut pages = NAV_STATE.with(|m| {
4240 m.borrow()
4241 .get(&ptr_of(host))
4242 .map_or_default(|s| s.pages.clone())
4243 });
4244 let shown_page = pages.get(sel).cloned();
4245 if let Some(page) = sidebar_page {
4248 pages.retain(|p| ptr_of(p) != ptr_of(&page));
4249 unsafe {
4250 if stacked {
4251 detail_wrap.addSubview(&page);
4252 pages.insert(0, page.clone());
4253 } else {
4254 page.setFrame(sidebar_wrap.bounds());
4255 sidebar_wrap.addSubview(&page);
4256 }
4257 }
4258 page.setHidden(false);
4260 }
4261 let shown = shown_page
4262 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
4263 .unwrap_or_else(|| pages.len().saturating_sub(1));
4264 for (i, page) in pages.iter().enumerate() {
4265 page.setHidden(i != shown);
4266 }
4267 NAV_STATE.with(|m| {
4268 let mut m = m.borrow_mut();
4269 if let Some(s) = m.get_mut(&ptr_of(host)) {
4270 s.presentation = next;
4271 s.pages = pages;
4272 s.selected = shown;
4273 s.header = header;
4274 if let Some(hdr) = s.header.as_ref() {
4275 if stacked {
4277 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
4278 } else {
4279 hdr.bar.setHidden(true);
4280 }
4281 }
4282 if !stacked {
4283 let frame = nav_page_frame(&s.detail_wrap, false);
4286 for page in &s.pages {
4287 unsafe { page.setFrame(frame) };
4288 }
4289 }
4290 }
4291 });
4292}
4293
4294struct CoverSheet(Retained<NSWindow>);
4303impl Drop for CoverSheet {
4304 fn drop(&mut self) {
4305 let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
4307 let raw = Retained::into_raw(self.0.clone()) as usize;
4310 dispatch2::DispatchQueue::main().exec_async(move || {
4311 ffi_guard::contain((), || unsafe {
4312 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
4313 if let Some(parent) = window.sheetParent() {
4314 parent.endSheet(&window);
4315 }
4316 window.orderOut(None);
4317 window.setContentView(None);
4318 });
4319 });
4320 }
4321}
4322struct NavPageIvars {
4323 node: NodeId,
4324 top_inset: Cell<f64>,
4328 sheet: Cell<bool>,
4329 half: Cell<bool>,
4331 large: Cell<bool>,
4334 fill: Cell<Option<day_spec::Ink>>,
4336}
4337
4338define_class!(
4339 #[unsafe(super(NSView))]
4340 #[thread_kind = MainThreadOnly]
4341 #[name = "DayNavPage"]
4342 #[ivars = NavPageIvars]
4343 struct DayNavPage;
4344
4345 impl DayNavPage {
4346 #[unsafe(method(isFlipped))]
4347 fn is_flipped(&self) -> bool {
4348 true
4349 }
4350
4351 #[unsafe(method(setFrameSize:))]
4352 fn set_frame_size(&self, size: NSSize) {
4353 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
4354 ffi_guard::contain((), || {
4357 let inset = self.ivars().top_inset.get();
4358 emit(
4359 self.ivars().node,
4360 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
4361 );
4362 });
4363 }
4364
4365 #[unsafe(method(viewDidChangeEffectiveAppearance))]
4367 fn view_did_change_effective_appearance(&self) {
4368 let _: () = unsafe { msg_send![super(self), viewDidChangeEffectiveAppearance] };
4369 ffi_guard::contain((), || self.paint_fill());
4370 }
4371 }
4372);
4373
4374impl DayNavPage {
4375 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
4376 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
4377 node,
4378 top_inset: Cell::new(0.0),
4379 sheet: Cell::new(false),
4380 half: Cell::new(false),
4381 large: Cell::new(false),
4382 fill: Cell::new(None),
4383 });
4384 unsafe { msg_send![super(this), init] }
4385 }
4386
4387 fn set_fill(&self, ink: day_spec::Ink) {
4390 self.ivars().fill.set(Some(ink));
4391 self.setWantsLayer(true);
4392 self.paint_fill();
4393 }
4394
4395 fn paint_fill(&self) {
4396 if let (Some(ink), Some(layer)) = (self.ivars().fill.get(), self.layer()) {
4397 layer.setBackgroundColor(Some(&color::cg_for(self, ink)));
4398 }
4399 }
4400}
4401
4402struct InspectorState {
4411 content_wrap: Handle,
4412 panel_wrap: Handle,
4413 split_vc: Retained<objc2_app_kit::NSSplitViewController>,
4415 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
4416}
4417
4418struct SplitState {
4426 split: Retained<objc2_app_kit::NSSplitView>,
4427 first_wrap: Handle,
4428 second_wrap: Handle,
4429 delegate: Retained<DaySplitDelegate>,
4430}
4431
4432struct SplitDelegateIvars {
4433 node: NodeId,
4434 min_pane: f64,
4435 share: Cell<f64>,
4438 positioned: Cell<bool>,
4440 suppress: Cell<bool>,
4442}
4443
4444define_class!(
4445 #[unsafe(super(NSObject))]
4446 #[thread_kind = MainThreadOnly]
4447 #[name = "DaySplitDelegate"]
4448 #[ivars = SplitDelegateIvars]
4449 struct DaySplitDelegate;
4450
4451 unsafe impl NSObjectProtocol for DaySplitDelegate {}
4452
4453 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
4454 #[unsafe(method(splitViewDidResizeSubviews:))]
4455 fn did_resize(&self, notification: &NSNotification) {
4456 ffi_guard::contain((), || {
4457 let Some(obj) = notification.object() else {
4458 return;
4459 };
4460 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
4461 return;
4462 };
4463 let iv = self.ivars();
4464 let usable = split_usable(&sv);
4465 if usable <= 0.0 {
4466 return;
4467 }
4468 if !iv.positioned.replace(true) {
4470 split_place(&sv, iv);
4471 return;
4472 }
4473 if iv.suppress.get() {
4474 return;
4475 }
4476 let Some(first) = sv.subviews().iter().next() else {
4477 return;
4478 };
4479 let f = first.frame();
4480 let a = if sv.isVertical() {
4481 f.size.width
4482 } else {
4483 f.size.height
4484 };
4485 let share = (a / usable).clamp(0.0, 1.0);
4486 if (share - iv.share.get()).abs() > 1e-4 {
4487 iv.share.set(share);
4488 emit(iv.node, Event::ValueChanged(share));
4489 }
4490 });
4491 }
4492
4493 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
4494 fn constrain_min(
4495 &self,
4496 _sv: &objc2_app_kit::NSSplitView,
4497 proposed: f64,
4498 _index: isize,
4499 ) -> f64 {
4500 proposed.max(self.ivars().min_pane)
4501 }
4502
4503 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
4504 fn constrain_max(
4505 &self,
4506 sv: &objc2_app_kit::NSSplitView,
4507 proposed: f64,
4508 _index: isize,
4509 ) -> f64 {
4510 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
4511 }
4512 }
4513);
4514
4515impl DaySplitDelegate {
4516 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
4517 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
4518 node,
4519 min_pane,
4520 share: Cell::new(share.clamp(0.0, 1.0)),
4521 positioned: Cell::new(false),
4522 suppress: Cell::new(false),
4523 });
4524 unsafe { msg_send![super(this), init] }
4525 }
4526}
4527
4528fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
4530 let frame = sv.frame();
4531 let len = if sv.isVertical() {
4532 frame.size.width
4533 } else {
4534 frame.size.height
4535 };
4536 (len - sv.dividerThickness()).max(0.0)
4537}
4538
4539fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
4541 let usable = split_usable(sv);
4542 if usable <= 0.0 {
4543 return;
4544 }
4545 iv.suppress.set(true);
4546 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
4547 iv.suppress.set(false);
4548}
4549
4550struct NavMenuIvars {
4557 node: NodeId,
4558 items: RefCell<Vec<Retained<NSString>>>,
4559 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
4563 icon_fills: RefCell<Vec<f64>>,
4566 tints: RefCell<Vec<Option<day_spec::Ink>>>,
4569 badges: RefCell<Vec<Option<Retained<NSString>>>>,
4571 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
4574 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
4575 badge_tints: RefCell<Vec<Option<day_spec::Ink>>>,
4577 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
4580 movable: RefCell<Vec<bool>>,
4582 regroup: std::cell::Cell<bool>,
4584 sorted: RefCell<Vec<bool>>,
4586 rows: RefCell<Vec<Option<usize>>>,
4590 row_objects: RefCell<Vec<Retained<NSString>>>,
4592 row_ids: RefCell<Vec<Retained<NSNumber>>>,
4597 suppress: std::cell::Cell<bool>,
4599}
4600
4601struct NavCellIvars {
4602 accessory: RefCell<Option<Retained<NSView>>>,
4605 count: RefCell<Option<Retained<NSTextField>>>,
4607 icon_fill: std::cell::Cell<f64>,
4609}
4610
4611define_class!(
4612 #[unsafe(super(objc2_app_kit::NSTableCellView))]
4617 #[thread_kind = MainThreadOnly]
4618 #[name = "DayNavCell"]
4619 #[ivars = NavCellIvars]
4620 struct DayNavCell;
4621
4622 unsafe impl NSObjectProtocol for DayNavCell {}
4623
4624 impl DayNavCell {
4625 #[unsafe(method(layout))]
4626 fn layout(&self) {
4627 let _: () = unsafe { msg_send![super(self), layout] };
4628 ffi_guard::contain((), || self.fit_accessories());
4629 }
4630 }
4631);
4632
4633impl DayNavCell {
4634 fn new(mtm: MainThreadMarker) -> Retained<Self> {
4635 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
4636 accessory: RefCell::new(None),
4637 count: RefCell::new(None),
4638 icon_fill: std::cell::Cell::new(1.0),
4639 });
4640 unsafe { msg_send![super(this), init] }
4641 }
4642
4643 fn fit_accessories(&self) {
4648 let label = unsafe { self.textField() };
4649 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
4650 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
4651 (f.pointSize() - 2.0).max(9.0)
4652 });
4653 #[expect(
4654 clippy::float_cmp,
4655 reason = "unchanged-value check against the exact size set below"
4656 )]
4657 let resize = unsafe { count.font() }.is_none_or(|f| f.pointSize() != size);
4658 if resize {
4659 unsafe {
4660 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
4661 size,
4662 objc2_app_kit::NSFontWeightRegular,
4663 )));
4664 }
4665 self.layoutSubtreeIfNeeded();
4666 }
4667 }
4668 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
4669 let mut frame = label.frame();
4670 let end = accessory.frame().origin.x - 6.0;
4671 if frame.origin.x + frame.size.width > end {
4672 frame.size.width = (end - frame.origin.x).max(0.0);
4673 label.setFrame(frame);
4674 }
4675 }
4676 if let Some(icon) = unsafe { self.imageView() } {
4677 fit_nav_icon(&icon, self.ivars().icon_fill.get());
4678 nav_progress::fit(&icon);
4679 }
4680 }
4681}
4682
4683thread_local! {
4684 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
4686}
4687
4688fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
4697 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
4698 return;
4699 };
4700 let slot = icon.frame();
4701 let key = config.hash() as u64;
4704 let side = NAV_GLYPH_SIDES
4705 .with(|m| m.borrow().get(&key).copied())
4706 .or_else(|| {
4707 let symbol =
4708 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4709 &NSString::from_str("gearshape"),
4710 None,
4711 )?;
4712 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
4713 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
4714 Some(side)
4715 });
4716 let Some(side) = side
4719 .filter(|s| *s > 0.0)
4720 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
4721 else {
4722 return;
4723 };
4724 if slot.size.width <= side && slot.size.height <= side {
4725 return;
4726 }
4727 icon.setFrame(NSRect::new(
4728 NSPoint::new(
4729 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
4730 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
4731 ),
4732 NSSize::new(side, side),
4733 ));
4734}
4735
4736define_class!(
4737 #[unsafe(super(objc2_app_kit::NSTableRowView))]
4738 #[thread_kind = MainThreadOnly]
4739 #[name = "DayNavRowView"]
4740 struct DayNavRowView;
4741
4742 unsafe impl NSObjectProtocol for DayNavRowView {}
4743
4744 impl DayNavRowView {
4745 #[unsafe(method(isEmphasized))]
4751 fn is_emphasized(&self) -> bool {
4752 true
4753 }
4754 }
4755);
4756
4757define_class!(
4758 #[unsafe(super(objc2_app_kit::NSOutlineView))]
4759 #[thread_kind = MainThreadOnly]
4760 #[name = "DayNavOutlineView"]
4761 struct DayNavOutlineView;
4762
4763 unsafe impl NSObjectProtocol for DayNavOutlineView {}
4764
4765 impl DayNavOutlineView {
4766 #[unsafe(method_id(menuForEvent:))]
4770 fn menu_for_event(
4771 &self,
4772 event: &objc2_app_kit::NSEvent,
4773 ) -> Option<Retained<NSMenu>> {
4774 ffi_guard::contain(None, || {
4775 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4776 let row = unsafe { self.rowAtPoint(point) };
4777 let data = NAV_OUTLINE_MENUS.with(|t| t.get(std::ptr::from_ref(self) as usize));
4778 match data {
4780 None => None,
4781 Some(d) => {
4782 let items = d
4783 .item_of_row(row)
4784 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
4785 .unwrap_or_default();
4786 if items.is_empty() {
4787 None
4788 } else {
4789 Some(build_ns_menu(d.mtm(), "", &items))
4790 }
4791 }
4792 }
4793 })
4794 }
4795 }
4796);
4797
4798define_class!(
4799 #[unsafe(super(NSObject))]
4800 #[thread_kind = MainThreadOnly]
4801 #[name = "DayNavMenuData"]
4802 #[ivars = NavMenuIvars]
4803 struct DayNavMenuData;
4804
4805 unsafe impl NSObjectProtocol for DayNavMenuData {}
4806
4807 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
4808 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4809 fn number_of_children(
4810 &self,
4811 _ov: &objc2_app_kit::NSOutlineView,
4812 item: Option<&objc2::runtime::AnyObject>,
4813 ) -> isize {
4814 if item.is_none() {
4815 self.ivars().row_objects.borrow().len() as isize
4816 } else {
4817 0
4818 }
4819 }
4820
4821 #[unsafe(method_id(outlineView:child:ofItem:))]
4822 fn child_of_item(
4823 &self,
4824 _ov: &objc2_app_kit::NSOutlineView,
4825 index: isize,
4826 _item: Option<&objc2::runtime::AnyObject>,
4827 ) -> Retained<objc2::runtime::AnyObject> {
4828 let ids = self.ivars().row_ids.borrow();
4829 let id = ids
4833 .get(index as usize)
4834 .cloned()
4835 .unwrap_or_else(|| NSNumber::new_isize(-1));
4836 unsafe { objc2::rc::Retained::cast_unchecked(id) }
4837 }
4838
4839 #[unsafe(method(outlineView:isItemExpandable:))]
4840 fn is_expandable(
4841 &self,
4842 _ov: &objc2_app_kit::NSOutlineView,
4843 _item: &objc2::runtime::AnyObject,
4844 ) -> bool {
4845 false
4846 }
4847
4848 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
4855 fn pasteboard_writer_for_item(
4856 &self,
4857 _ov: &objc2_app_kit::NSOutlineView,
4858 item: &objc2::runtime::AnyObject,
4859 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4860 let make = || {
4861 let row = Self::outline_row(item);
4862 let index = self.item_of_row(row)?;
4863 if !self.is_movable(index) {
4864 return None;
4865 }
4866 let pbitem = objc2_app_kit::NSPasteboardItem::new();
4867 unsafe {
4868 pbitem.setString_forType(
4869 &NSString::from_str(&row.to_string()),
4870 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
4871 );
4872 }
4873 Some(ProtocolObject::from_retained(pbitem))
4874 };
4875 ffi_guard::contain(None, make)
4876 }
4877
4878 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
4879 fn validate_drop(
4880 &self,
4881 ov: &objc2_app_kit::NSOutlineView,
4882 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4883 item: Option<&objc2::runtime::AnyObject>,
4884 child_index: isize,
4885 ) -> objc2_app_kit::NSDragOperation {
4886 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4887 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
4888 return objc2_app_kit::NSDragOperation::None;
4889 };
4890 if drop.retarget {
4892 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
4893 }
4894 objc2_app_kit::NSDragOperation::Move
4895 })
4896 }
4897
4898 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
4899 fn accept_drop(
4900 &self,
4901 ov: &objc2_app_kit::NSOutlineView,
4902 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4903 item: Option<&objc2::runtime::AnyObject>,
4904 child_index: isize,
4905 ) -> bool {
4906 ffi_guard::contain(false, || {
4907 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
4908 return false;
4909 };
4910 match drop.moves {
4913 Some(NavMove::Reorder { from, to }) => {
4914 emit(self.ivars().node, Event::ListReorder { from, to });
4915 }
4916 Some(NavMove::Regroup {
4917 from,
4918 section,
4919 before,
4920 }) => emit(
4921 self.ivars().node,
4922 Event::NavRegroup {
4923 from,
4924 section,
4925 before,
4926 },
4927 ),
4928 None => {}
4929 }
4930 true
4931 })
4932 }
4933 }
4934
4935 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
4936
4937 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
4938 #[unsafe(method(outlineView:isGroupItem:))]
4941 fn is_group_item(
4942 &self,
4943 _ov: &objc2_app_kit::NSOutlineView,
4944 item: &objc2::runtime::AnyObject,
4945 ) -> bool {
4946 let row = Self::outline_row(item);
4947 row >= 0 && self.item_of_row(row).is_none()
4948 }
4949
4950 #[unsafe(method(outlineView:shouldSelectItem:))]
4951 fn should_select(
4952 &self,
4953 _ov: &objc2_app_kit::NSOutlineView,
4954 item: &objc2::runtime::AnyObject,
4955 ) -> bool {
4956 self.item_of_row(Self::outline_row(item)).is_some()
4957 }
4958
4959 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
4960 fn view_for(
4961 &self,
4962 ov: &objc2_app_kit::NSOutlineView,
4963 _col: Option<&objc2_app_kit::NSTableColumn>,
4964 item: &objc2::runtime::AnyObject,
4965 ) -> Option<Retained<NSView>> {
4966 let mtm = self.mtm();
4967 let row = Self::outline_row(item);
4968 let text = self
4969 .ivars()
4970 .row_objects
4971 .borrow()
4972 .get(usize::try_from(row).unwrap_or(usize::MAX))
4973 .cloned();
4974 text.map(|text| {
4976 let text: &NSString = &text;
4977 let Some(index) = self.item_of_row(row) else {
4978 let cell = DayNavCell::new(mtm);
4981 let label = unsafe { NSTextField::labelWithString(text, mtm) };
4982 unsafe {
4983 label.cell().inspect(|c| {
4984 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
4985 });
4986 cell.addSubview(&label);
4987 cell.setTextField(Some(&label));
4988 }
4989 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
4990 };
4991 let icon = self
4992 .ivars()
4993 .icons
4994 .borrow()
4995 .get(index)
4996 .and_then(std::clone::Clone::clone);
4997 let badge = self
4998 .ivars()
4999 .badges
5000 .borrow()
5001 .get(index)
5002 .and_then(std::clone::Clone::clone);
5003 let badge_icon = self
5004 .ivars()
5005 .badge_icons
5006 .borrow()
5007 .get(index)
5008 .and_then(std::clone::Clone::clone);
5009 let badge_tint = self
5010 .ivars()
5011 .badge_tints
5012 .borrow()
5013 .get(index)
5014 .copied()
5015 .flatten();
5016 let cell = DayNavCell::new(mtm);
5020 let label = unsafe { NSTextField::labelWithString(text, mtm) };
5021 unsafe {
5022 label.cell().inspect(|c| {
5025 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
5026 });
5027 cell.addSubview(&label);
5028 cell.setTextField(Some(&label));
5029 let accessory = objc2_app_kit::NSStackView::new(mtm);
5036 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
5037 accessory.setOrientation(
5038 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
5039 );
5040 accessory.setSpacing(4.0);
5041 let mut has_accessory = false;
5042 let trailing: Retained<NSView> = match &badge {
5043 Some(text) => {
5044 let b = NSTextField::labelWithString(text, mtm);
5045 b.setTranslatesAutoresizingMaskIntoConstraints(false);
5046 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
5047 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
5048 b.setFont(Some(
5049 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
5050 objc2_app_kit::NSFont::smallSystemFontSize(),
5051 objc2_app_kit::NSFontWeightRegular,
5052 ),
5053 ));
5054 b.setContentCompressionResistancePriority_forOrientation(
5055 objc2_app_kit::NSLayoutPriorityRequired,
5056 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
5057 );
5058 *cell.ivars().count.borrow_mut() = Some(b.clone());
5059 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
5060 objc2::rc::Retained::into_super(b),
5061 ));
5062 has_accessory = true;
5063 let v: Retained<NSView> =
5064 objc2::rc::Retained::into_super(accessory.clone());
5065 v
5066 }
5067 None => objc2::rc::Retained::into_super(accessory.clone()),
5068 };
5069 if let Some(img) = &badge_icon {
5074 let iv = objc2_app_kit::NSImageView::new(mtm);
5075 iv.setImage(Some(img));
5076 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
5077 if let Some(c) = badge_tint {
5078 iv.setContentTintColor(Some(&color::nsink(c)));
5079 }
5080 iv.setContentCompressionResistancePriority_forOrientation(
5081 objc2_app_kit::NSLayoutPriorityRequired,
5082 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
5083 );
5084 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
5085 has_accessory = true;
5086 }
5087 cell.addSubview(&trailing);
5088 if has_accessory {
5089 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
5090 }
5091 objc2_app_kit::NSLayoutConstraint::activateConstraints(
5092 &objc2_foundation::NSArray::from_retained_slice(&[
5093 trailing
5094 .trailingAnchor()
5095 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
5096 trailing
5097 .centerYAnchor()
5098 .constraintEqualToAnchor(&cell.centerYAnchor()),
5099 ]),
5100 );
5101 }
5102 if let Some(img) = icon {
5103 let fill = self.ivars().icon_fills.borrow().get(index).copied();
5104 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
5105 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
5106 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
5107 unsafe {
5108 iv.setImage(Some(&img));
5109 if let Some(t) = tint {
5112 iv.setContentTintColor(Some(&color::nsink(t)));
5113 }
5114 iv.setImageScaling(
5115 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
5116 );
5117 cell.addSubview(&iv);
5118 cell.setImageView(Some(&iv));
5119 let progress = self
5120 .ivars()
5121 .icon_progress
5122 .borrow()
5123 .iter()
5124 .find(|(row, _)| *row == index)
5125 .map(|(_, f)| *f);
5126 nav_progress::update(&iv, progress);
5127 }
5128 }
5129 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
5130 })
5131 }
5132
5133 #[unsafe(method_id(outlineView:rowViewForItem:))]
5134 fn row_view_for(
5135 &self,
5136 _ov: &objc2_app_kit::NSOutlineView,
5137 _item: &objc2::runtime::AnyObject,
5138 ) -> Retained<objc2_app_kit::NSTableRowView> {
5139 let row: Retained<DayNavRowView> =
5140 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
5141 objc2::rc::Retained::into_super(row)
5142 }
5143
5144 #[unsafe(method(outlineViewSelectionDidChange:))]
5145 fn selection_did_change(&self, notification: &NSNotification) {
5146 ffi_guard::contain((), || {
5147 if self.ivars().suppress.get() {
5148 return;
5149 }
5150 let Some(obj) = (unsafe { notification.object() }) else {
5151 return;
5152 };
5153 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5154 return;
5155 };
5156 let row = unsafe { ov.selectedRow() };
5157 if let Some(item) = self.item_of_row(row) {
5158 emit(self.ivars().node, Event::SelectionChanged(item as i64));
5159 }
5160 });
5161 }
5162 }
5163);
5164
5165thread_local! {
5166 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
5169}
5170
5171fn nav_icon_fills(
5173 names: &[Option<String>],
5174 images: &[Option<Retained<objc2_app_kit::NSImage>>],
5175) -> Vec<f64> {
5176 names
5177 .iter()
5178 .zip(images)
5179 .map(|(name, image)| match (name, image) {
5180 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
5181 *m.borrow_mut()
5182 .entry(name.clone())
5183 .or_insert_with(|| nav_icon_fill(image))
5184 }),
5185 _ => 1.0,
5186 })
5187 .collect()
5188}
5189
5190fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
5195 const PX: f64 = 64.0;
5196 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
5197 return 1.0;
5198 };
5199 let (w, h) = (
5200 rep.pixelsWide().max(0) as usize,
5201 rep.pixelsHigh().max(0) as usize,
5202 );
5203 let stride = rep.bytesPerRow().max(0) as usize;
5204 let data = unsafe { rep.bitmapData() };
5205 if data.is_null() || stride < w * 4 {
5206 return 1.0;
5207 }
5208 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
5211 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
5212 for y in 0..h {
5213 for x in 0..w {
5214 if bytes[y * stride + x * 4 + 3] > 24 {
5215 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
5216 }
5217 }
5218 }
5219 if x1 <= x0 || y1 <= y0 {
5220 return 1.0;
5221 }
5222 let size = image.size();
5225 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
5226 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
5227 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
5228}
5229
5230fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
5231 icons
5233 .iter()
5234 .map(|ic| {
5235 use objc2::AllocAnyThread as _;
5236 let name = ic.as_deref()?;
5237 let path = day_spec::resource::resolve_vector_svg(name)
5239 .or_else(|| day_spec::resource::resolve_image_file(name))?;
5240 let img = unsafe {
5241 objc2_app_kit::NSImage::initWithContentsOfFile(
5242 objc2_app_kit::NSImage::alloc(),
5243 &NSString::from_str(&path.to_string_lossy()),
5244 )
5245 }?;
5246 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
5248 Some(img)
5249 })
5250 .collect()
5251}
5252
5253impl DayNavMenuData {
5254 #[allow(clippy::too_many_arguments)]
5255 fn new(
5256 mtm: MainThreadMarker,
5257 node: NodeId,
5258 items: &[String],
5259 icons: &[Option<String>],
5260 badges: &[Option<String>],
5261 badge_icons: &[Option<String>],
5262 badge_tints: &[Option<day_spec::Ink>],
5263 sections: &[Option<String>],
5264 tints: &[Option<day_spec::Ink>],
5265 menus: &[Vec<day_spec::MenuItem>],
5266 ) -> Retained<Self> {
5267 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
5268 node,
5269 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
5270 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
5271 icons: RefCell::new(resolve_nav_icons(icons)),
5272 tints: RefCell::new(tints.to_vec()),
5273 menus: RefCell::new(menus.to_vec()),
5274 movable: RefCell::new(Vec::new()),
5275 regroup: std::cell::Cell::new(false),
5276 sorted: RefCell::new(Vec::new()),
5277 badges: RefCell::new(ns_badges(badges)),
5278 icon_progress: RefCell::new(Vec::new()),
5279 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
5280 badge_tints: RefCell::new(badge_tints.to_vec()),
5281 rows: RefCell::new(Vec::new()),
5282 row_objects: RefCell::new(Vec::new()),
5283 row_ids: RefCell::new(Vec::new()),
5284 suppress: std::cell::Cell::new(false),
5285 });
5286 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
5287 this.rebuild_rows(items, sections);
5288 this
5289 }
5290
5291 #[allow(clippy::too_many_arguments)]
5295 fn set_items(
5296 &self,
5297 items: &[String],
5298 icons: &[Option<String>],
5299 badges: &[Option<String>],
5300 badge_icons: &[Option<String>],
5301 badge_tints: &[Option<day_spec::Ink>],
5302 sections: &[Option<String>],
5303 tints: &[Option<day_spec::Ink>],
5304 menus: &[Vec<day_spec::MenuItem>],
5305 ) {
5306 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
5307 let resolved = resolve_nav_icons(icons);
5308 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
5309 *self.ivars().icons.borrow_mut() = resolved;
5310 *self.ivars().tints.borrow_mut() = tints.to_vec();
5311 *self.ivars().menus.borrow_mut() = menus.to_vec();
5312 *self.ivars().badges.borrow_mut() = ns_badges(badges);
5313 self.ivars().icon_progress.borrow_mut().clear();
5314 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
5315 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
5316 self.rebuild_rows(items, sections);
5317 }
5318
5319 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
5323 let mut rows = Vec::with_capacity(items.len());
5324 let mut objects = Vec::with_capacity(items.len());
5325 for (i, label) in items.iter().enumerate() {
5326 if let Some(Some(header)) = sections.get(i) {
5327 rows.push(None);
5328 objects.push(NSString::from_str(header));
5329 }
5330 rows.push(Some(i));
5331 objects.push(NSString::from_str(label));
5332 }
5333 let ids = (0..objects.len())
5334 .map(|i| NSNumber::new_isize(i as isize))
5335 .collect();
5336 *self.ivars().rows.borrow_mut() = rows;
5337 *self.ivars().row_objects.borrow_mut() = objects;
5338 *self.ivars().row_ids.borrow_mut() = ids;
5339 }
5340
5341 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
5344 item.downcast_ref::<NSNumber>()
5345 .map_or(-1, objc2_foundation::NSNumber::integerValue)
5346 }
5347
5348 fn item_of_row(&self, row: isize) -> Option<usize> {
5350 if row < 0 {
5351 return None;
5352 }
5353 self.ivars()
5354 .rows
5355 .borrow()
5356 .get(row as usize)
5357 .copied()
5358 .flatten()
5359 }
5360
5361 fn row_of_item(&self, item: usize) -> Option<usize> {
5363 self.ivars()
5364 .rows
5365 .borrow()
5366 .iter()
5367 .position(|r| *r == Some(item))
5368 }
5369
5370 fn is_movable(&self, item: usize) -> bool {
5371 self.ivars()
5372 .movable
5373 .borrow()
5374 .get(item)
5375 .copied()
5376 .unwrap_or(false)
5377 }
5378
5379 fn nav_drop(
5384 &self,
5385 ov: &objc2_app_kit::NSOutlineView,
5386 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5387 item: Option<&objc2::runtime::AnyObject>,
5388 child_index: isize,
5389 ) -> Option<NavDrop> {
5390 let src = unsafe { info.draggingSource() }?;
5391 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
5392 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
5393 {
5394 return None;
5395 }
5396 let pb = unsafe { info.draggingPasteboard() };
5397 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
5398 .to_string()
5399 .parse::<usize>()
5400 .ok()?;
5401 let rows = self.ivars().rows.borrow();
5402 let proposed = match item {
5405 Some(item) => Self::outline_row(item),
5406 None => child_index,
5407 };
5408 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
5409 if self.ivars().regroup.get() {
5410 regroup_gap(
5411 &rows,
5412 &self.ivars().movable.borrow(),
5413 &self.ivars().sorted.borrow(),
5414 from_row,
5415 proposed,
5416 item.is_some(),
5417 )
5418 } else {
5419 reorder_gap(
5420 &rows,
5421 &self.ivars().movable.borrow(),
5422 from_row,
5423 proposed,
5424 item.is_some(),
5425 )
5426 }
5427 }
5428}
5429
5430#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5432struct NavDrop {
5433 gap: usize,
5435 retarget: bool,
5437 moves: Option<NavMove>,
5439}
5440
5441#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5443enum NavMove {
5444 Reorder { from: usize, to: usize },
5446 Regroup {
5449 from: usize,
5450 section: usize,
5451 before: Option<usize>,
5452 },
5453}
5454
5455fn reorder_gap(
5460 rows: &[Option<usize>],
5461 movable: &[bool],
5462 from_row: usize,
5463 proposed: usize,
5464 onto: bool,
5465) -> Option<NavDrop> {
5466 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
5467 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
5468 let in_run = |r: usize| rows[r].is_some_and(is_movable);
5469 let first = (0..from_row)
5470 .rev()
5471 .take_while(|r| in_run(*r))
5472 .last()
5473 .unwrap_or(from_row);
5474 let last = (from_row + 1..rows.len())
5475 .take_while(|r| in_run(*r))
5476 .last()
5477 .unwrap_or(from_row);
5478 let gap = proposed.clamp(first, last + 1);
5479 let target_row = if gap > from_row { gap - 1 } else { gap };
5481 let moves = (target_row != from_row)
5482 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
5483 .flatten();
5484 Some(NavDrop {
5485 gap,
5486 retarget: gap != proposed || onto,
5487 moves,
5488 })
5489}
5490
5491fn regroup_gap(
5499 rows: &[Option<usize>],
5500 movable: &[bool],
5501 sorted: &[bool],
5502 from_row: usize,
5503 proposed: usize,
5504 onto: bool,
5505) -> Option<NavDrop> {
5506 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
5507 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
5508 let gap = match rows.get(proposed) {
5509 Some(None) if onto => proposed + 1,
5510 _ => proposed.min(rows.len()),
5511 };
5512 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
5514 Some(header) => Some(header + 1),
5515 None => rows.first().copied().flatten().map(|_| 0),
5516 };
5517 let first = section_start(gap)?;
5518 let end = (first..rows.len())
5519 .find(|r| rows[*r].is_none())
5520 .unwrap_or(rows.len());
5521 let section = rows.get(first).copied().flatten()?;
5522 if !rows[first..end]
5523 .iter()
5524 .all(|r| r.is_some_and(|i| flag(movable, i)))
5525 {
5526 return None;
5527 }
5528 let own = section_start(from_row) == Some(first);
5529 if own && flag(sorted, from) {
5530 return None;
5531 }
5532 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
5533 from,
5534 section,
5535 before: rows.get(gap).copied().flatten(),
5536 });
5537 Some(NavDrop {
5538 gap,
5539 retarget: gap != proposed || onto,
5540 moves,
5541 })
5542}
5543
5544#[cfg(test)]
5545mod nav_gap_tests {
5546 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
5547
5548 const ROWS: [Option<usize>; 10] = [
5550 Some(0),
5551 None,
5552 Some(1),
5553 Some(2),
5554 Some(3),
5555 None,
5556 Some(4),
5557 Some(5),
5558 None,
5559 Some(6),
5560 ];
5561 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
5563 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
5564 const UNSORTED: [bool; 7] = [false; 7];
5565
5566 fn regroup(from: usize, section: usize, before: Option<usize>) -> NavMove {
5567 NavMove::Regroup {
5568 from,
5569 section,
5570 before,
5571 }
5572 }
5573
5574 #[test]
5575 fn regroup_gaps_name_the_section_above_and_the_row_below() {
5576 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
5577 assert_eq!(
5579 at(2, 6),
5580 Some(NavDrop {
5581 gap: 6,
5582 retarget: false,
5583 moves: Some(regroup(1, 4, Some(4))),
5584 })
5585 );
5586 assert_eq!(at(6, 5).and_then(|d| d.moves), Some(regroup(4, 1, None)));
5588 assert_eq!(at(2, 7).and_then(|d| d.moves), Some(regroup(1, 4, Some(5))));
5590 assert_eq!(at(2, 8).and_then(|d| d.moves), Some(regroup(1, 4, None)));
5591 }
5592
5593 #[test]
5594 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
5595 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
5596 for gap in [0, 1, 9, 10] {
5598 assert_eq!(at(2, gap), None, "gap {gap}");
5599 }
5600 for gap in [2, 3, 4, 5] {
5602 assert_eq!(at(2, gap), None, "gap {gap}");
5603 }
5604 assert_eq!(at(0, 6), None);
5606 assert_eq!(at(1, 6), None);
5607 assert_eq!(at(9, 6), None);
5608 }
5609
5610 #[test]
5611 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
5612 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
5613 assert_eq!(at(2, 4).and_then(|d| d.moves), Some(regroup(1, 1, Some(3))));
5615 assert_eq!(at(2, 5).and_then(|d| d.moves), Some(regroup(1, 1, None)));
5617 for gap in [2, 3] {
5619 let drop = at(2, gap).expect("offered");
5620 assert_eq!(drop.moves, None, "gap {gap}");
5621 }
5622 }
5623
5624 #[test]
5625 fn regroup_drops_onto_a_row_move_to_a_gap() {
5626 assert_eq!(
5628 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
5629 Some(NavDrop {
5630 gap: 6,
5631 retarget: true,
5632 moves: Some(regroup(1, 4, Some(4))),
5633 })
5634 );
5635 assert_eq!(
5636 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
5637 Some(NavDrop {
5638 gap: 7,
5639 retarget: true,
5640 moves: Some(regroup(1, 4, Some(5))),
5641 })
5642 );
5643 }
5644
5645 #[test]
5646 fn regroup_offers_nothing_above_a_leading_header() {
5647 let rows = [None, Some(0), None, Some(1)];
5649 let movable = [true, true];
5650 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
5651 assert_eq!(at(0), None);
5652 assert_eq!(at(1).map(|d| d.moves), Some(None));
5653 assert_eq!(at(2).map(|d| d.moves), Some(None));
5654 assert_eq!(at(3).and_then(|d| d.moves), Some(regroup(0, 1, Some(1))));
5655 assert_eq!(at(4).and_then(|d| d.moves), Some(regroup(0, 1, None)));
5656 }
5657
5658 #[test]
5659 fn reorder_gaps_clamp_to_the_run() {
5660 assert_eq!(
5662 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
5663 Some(NavDrop {
5664 gap: 5,
5665 retarget: true,
5666 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
5667 })
5668 );
5669 assert_eq!(
5671 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
5672 Some(None)
5673 );
5674 assert_eq!(
5676 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
5677 Some(NavMove::Reorder { from: 2, to: 1 })
5678 );
5679 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
5680 }
5681}
5682
5683const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
5685
5686fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
5688 badges
5689 .iter()
5690 .map(|b| b.as_deref().map(NSString::from_str))
5691 .collect()
5692}
5693
5694fn post_realize_visible_rows(key: usize) {
5700 <AppKit as Platform>::post(Box::new(move || {
5701 if let Some((table, data)) = list_entry(key) {
5702 data.apply_held(&table);
5704 {
5705 let _pass = RowPass::enter();
5708 unsafe { table.layoutSubtreeIfNeeded() };
5709 let range = unsafe { table.rowsInRect(table.visibleRect()) };
5710 for row in range.location..range.location + range.length {
5711 let cell =
5712 unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5713 if let Some(cell) = cell {
5721 let raw = Retained::as_ptr(&cell) as RawHandle;
5722 let skipped = data.ivars().unbound.borrow_mut().remove(&(raw as usize));
5723 if (skipped || cell.subviews().is_empty())
5724 && let Some(source) = data.ivars().source.borrow().clone()
5725 && let Some(index) = data.source_row(row as isize)
5726 {
5727 (source.bind_row)(index, raw);
5728 data.note_row_height(&table, &source, row as isize, raw);
5729 }
5730 }
5731 }
5732 }
5733 data.report_viewport(&table);
5734 }
5735 day_core::pump_events();
5738 }));
5739}
5740
5741fn post_settle_list_drop(key: usize) {
5746 <AppKit as Platform>::post(Box::new(move || {
5747 day_core::pump_events();
5750 let Some((table, data)) = list_entry(key) else {
5751 return;
5752 };
5753 data.apply_held(&table);
5754 let Some(scroll) = table.enclosingScrollView() else {
5755 return;
5756 };
5757 let clip = scroll.contentView();
5758 let origin = clip.bounds().origin;
5759 let selected = table.selectedRowIndexes();
5760 let suppressed = data.ivars().suppress.replace(true);
5761 table.reloadData();
5762 table.layoutSubtreeIfNeeded();
5764 let restored = objc2_foundation::NSMutableIndexSet::new();
5765 for row in 0..table.numberOfRows().max(0) as usize {
5766 if selected.containsIndex(row) {
5767 restored.addIndex(row);
5768 }
5769 }
5770 table.selectRowIndexes_byExtendingSelection(&restored, false);
5771 let mut bounds = clip.bounds();
5772 bounds.origin = origin;
5773 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
5774 scroll.reflectScrolledClipView(&clip);
5775 data.ivars().suppress.set(suppressed);
5776 post_realize_visible_rows(key);
5777 }));
5778}
5779
5780define_class!(
5789 #[unsafe(super(NSTableView))]
5790 #[thread_kind = MainThreadOnly]
5791 #[name = "DayListView"]
5792 struct DayListView;
5793 unsafe impl NSObjectProtocol for DayListView {}
5794 impl DayListView {
5795 #[unsafe(method_id(menuForEvent:))]
5798 fn menu_for_event(
5799 &self,
5800 event: &objc2_app_kit::NSEvent,
5801 ) -> Option<Retained<NSMenu>> {
5802 ffi_guard::contain(None, || {
5803 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5804 let row = unsafe { self.rowAtPoint(point) };
5805 let provider = if row >= 0 {
5806 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
5807 .and_then(|cell| list_row_menu_provider(&cell))
5808 } else {
5809 None
5810 };
5811 match provider {
5812 Some((view, provider)) => {
5813 let point = view.convertPoint_fromView(
5814 unsafe { event.locationInWindow() }, None,
5815 );
5816 let items = provider(day_spec::Point::new(point.x, point.y));
5817 if items.is_empty() {
5818 None
5819 } else {
5820 Some(build_ns_menu(self.mtm(), "", &items))
5821 }
5822 }
5823 None => unsafe { msg_send![super(self), menuForEvent: event] },
5824 }
5825 })
5826 }
5827
5828 #[unsafe(method(drawGridInClipRect:))]
5831 fn draw_grid_in_clip_rect(&self, clip: NSRect) {
5832 ffi_guard::contain((), || {
5833 let data = unsafe { self.target() }
5834 .and_then(|t| t.downcast::<DayListData>().ok())
5835 .filter(|d| d.ivars().supplements.get());
5836 let Some(data) = data else {
5837 let _: () = unsafe { msg_send![super(self), drawGridInClipRect: clip] };
5838 return;
5839 };
5840 if unsafe { self.gridStyleMask() }.is_empty() {
5841 return;
5842 }
5843 let rows = unsafe { self.numberOfRows() };
5844 let shown = unsafe { self.rowsInRect(clip) };
5845 unsafe { self.gridColor() }.setFill();
5846 for row in shown.location..shown.location + shown.length {
5847 let row = row as isize;
5848 if data.is_supplement(row) || (row + 1 < rows && data.is_supplement(row + 1)) {
5849 continue;
5850 }
5851 let rect = unsafe { self.rectOfRow(row) };
5852 objc2_app_kit::NSBezierPath::fillRect(NSRect::new(
5853 NSPoint::new(clip.origin.x, rect.origin.y + rect.size.height - 1.0),
5854 NSSize::new(clip.size.width, 1.0),
5855 ));
5856 }
5857 });
5858 }
5859
5860 #[unsafe(method(becomeFirstResponder))]
5861 fn become_first_responder(&self) -> bool {
5862 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
5863 if accepted {
5864 self.report_focus(true);
5865 }
5866 accepted
5867 }
5868
5869 #[unsafe(method(resignFirstResponder))]
5870 fn resign_first_responder(&self) -> bool {
5871 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
5872 if accepted {
5873 self.report_focus(false);
5874 }
5875 accepted
5876 }
5877
5878 #[unsafe(method(keyDown:))]
5879 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
5880 ffi_guard::contain((), || {
5881 let key = unsafe { event.keyCode() };
5882 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
5883 let row = unsafe { self.selectedRow() };
5884 if row >= 0 && let Some(target) = unsafe { self.target() } {
5885 let _: () = unsafe { msg_send![&*target, activateRow: self] };
5886 return;
5887 }
5888 }
5889 let data = unsafe { self.target() }
5892 .and_then(|t| t.downcast::<DayListData>().ok());
5893 if let Some(data) = &data {
5894 if PAGE_KEYS.contains(&key)
5895 && let Some(scroll) = self.enclosingScrollView()
5896 {
5897 scroll::stop_clip_animation(&scroll);
5898 }
5899 data.ivars().input.set(true);
5900 }
5901 let _: () = unsafe { msg_send![super(self), keyDown: event] };
5902 if let Some(data) = &data {
5903 data.ivars().input.set(false);
5904 }
5905 });
5906 }
5907
5908 #[unsafe(method(layout))]
5912 fn layout(&self) {
5913 let _pass = RowPass::enter();
5914 let _: () = unsafe { msg_send![super(self), layout] };
5915 }
5916
5917 #[unsafe(method(prepareContentInRect:))]
5919 fn prepare_content_in_rect(&self, rect: NSRect) {
5920 let _pass = RowPass::enter();
5921 let _: () = unsafe { msg_send![super(self), prepareContentInRect: rect] };
5922 }
5923 }
5924);
5925
5926const PAGE_KEYS: [u16; 4] = [115, 116, 119, 121];
5928
5929define_class!(
5930 #[unsafe(super(NSScrollView))]
5935 #[thread_kind = MainThreadOnly]
5936 #[name = "DayListScrollView"]
5937 struct DayListScrollView;
5938 unsafe impl NSObjectProtocol for DayListScrollView {}
5939 impl DayListScrollView {
5940 #[unsafe(method(isCompatibleWithResponsiveScrolling))]
5941 fn compatible_with_responsive_scrolling() -> bool {
5942 true
5943 }
5944
5945 #[unsafe(method(scrollWheel:))]
5946 fn scroll_wheel(&self, event: &NSEvent) {
5947 ffi_guard::contain((), || {
5948 let entry = list_entry(ptr_of(self));
5949 if let Some((table, data)) = &entry {
5950 let phase = unsafe { event.phase() };
5951 let notch = phase.is_empty() && unsafe { event.momentumPhase() }.is_empty();
5952 if notch || phase.contains(objc2_app_kit::NSEventPhase::Began) {
5953 scroll::stop_clip_animation(self);
5954 }
5955 if unsafe { event.scrollingDeltaY() } > 0.0
5960 && unsafe { self.contentView() }.bounds().origin.y > 0.0
5961 {
5962 data.report_reader_leaving(table);
5963 }
5964 data.ivars().input.set(true);
5965 data.ivars().wheel.set(true);
5966 }
5967 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
5968 if let Some((_, data)) = &entry {
5969 data.ivars().input.set(false);
5970 data.ivars().wheel.set(false);
5971 }
5972 });
5973 }
5974 }
5975);
5976
5977fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
5980 if let Some(provider) =
5981 CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<NSView>(view) as usize))
5982 {
5983 return Some((view.retain(), provider));
5984 }
5985 view.subviews()
5986 .iter()
5987 .find_map(|view| list_row_menu_provider(&view))
5988}
5989
5990#[expect(
5994 clippy::option_option,
5995 reason = "`None` defers to AppKit's own menu while `Some(None)` is an owner's deliberate no-menu answer"
5996)]
5997fn inherited_context_menu(
5998 view: &NSView,
5999 event: &objc2_app_kit::NSEvent,
6000) -> Option<Option<Retained<NSMenu>>> {
6001 let mut current = Some(view.retain());
6002 while let Some(view) = current {
6003 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
6004 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6005 let items = provider(day_spec::Point::new(point.x, point.y));
6006 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
6007 }
6008 current = unsafe { view.superview() };
6009 }
6010 None
6011}
6012
6013impl DayListView {
6014 fn report_focus(&self, focused: bool) {
6015 ffi_guard::contain((), || {
6016 if let Some(target) = unsafe { self.target() }
6017 && let Some(data) = target.downcast_ref::<DayListData>()
6018 {
6019 emit(data.ivars().node, Event::FocusChanged(focused));
6020 }
6021 });
6022 }
6023}
6024
6025struct ListIvars {
6026 node: NodeId,
6027 source: RefCell<Option<ListSource>>,
6029 selectable: std::cell::Cell<bool>,
6030 multi: std::cell::Cell<bool>,
6032 suppress: std::cell::Cell<bool>,
6034 tokens: RefCell<Vec<u64>>,
6037 automatic: bool,
6041 sections: bool,
6045 header_estimate: std::cell::Cell<f64>,
6047 heights: RefCell<std::collections::HashMap<u64, f64>>,
6050 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
6053 estimate: std::cell::Cell<f64>,
6056 heights_pending: std::cell::Cell<bool>,
6058 supplements: std::cell::Cell<bool>,
6062 unbound: RefCell<std::collections::HashSet<usize>>,
6065 splice: RefCell<Option<SpliceRows>>,
6068 live: std::cell::Cell<bool>,
6074 input: std::cell::Cell<bool>,
6076 wheel: std::cell::Cell<bool>,
6079 held: RefCell<Option<HeldRows>>,
6082 held_posted: std::cell::Cell<bool>,
6084 applying: std::cell::Cell<bool>,
6087}
6088
6089thread_local! {
6090 static LIST_ROW_PASS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
6098}
6099
6100struct RowPass;
6102
6103impl RowPass {
6104 fn enter() -> Self {
6105 LIST_ROW_PASS.with(|depth| depth.set(depth.get() + 1));
6106 Self
6107 }
6108
6109 fn active() -> bool {
6111 LIST_ROW_PASS.with(|depth| depth.get() > 0)
6112 }
6113}
6114
6115impl Drop for RowPass {
6116 fn drop(&mut self) {
6117 LIST_ROW_PASS.with(|depth| depth.set(depth.get().saturating_sub(1)));
6118 }
6119}
6120
6121struct HeldRows {
6127 deltas: Option<Vec<day_spec::props::RowDelta>>,
6131 selected: Option<Vec<u64>>,
6133}
6134
6135struct SpliceRows {
6145 entries: Vec<usize>,
6147 finals: Vec<Option<usize>>,
6149 next: usize,
6151}
6152
6153impl SpliceRows {
6154 fn new(shown: usize, deltas: &[day_spec::props::RowDelta]) -> Self {
6157 let mut replay = Self {
6158 entries: (0..shown).collect(),
6159 finals: Vec::new(),
6160 next: shown,
6161 };
6162 for delta in deltas {
6163 replay.apply(*delta);
6164 }
6165 let mut finals = vec![None; replay.next];
6166 for (row, entry) in replay.entries.iter().enumerate() {
6167 finals[*entry] = Some(row);
6168 }
6169 Self {
6170 entries: (0..shown).collect(),
6171 finals,
6172 next: shown,
6173 }
6174 }
6175
6176 fn apply(&mut self, delta: day_spec::props::RowDelta) {
6179 use day_spec::props::RowDelta;
6180 let len = self.entries.len();
6181 match delta {
6182 RowDelta::Insert(i) if i <= len => {
6183 self.entries.insert(i, self.next);
6184 self.next += 1;
6185 }
6186 RowDelta::Remove(i) if i < len => {
6187 self.entries.remove(i);
6188 }
6189 RowDelta::Move(from, to) if from < len && to < len => {
6190 let entry = self.entries.remove(from);
6191 self.entries.insert(to, entry);
6192 }
6193 _ => {}
6194 }
6195 }
6196
6197 fn source_row(&self, row: usize) -> Option<usize> {
6199 self.entries
6200 .get(row)
6201 .and_then(|entry| self.finals.get(*entry).copied().flatten())
6202 }
6203}
6204
6205define_class!(
6206 #[unsafe(super(NSObject))]
6207 #[thread_kind = MainThreadOnly]
6208 #[name = "DayListData"]
6209 #[ivars = ListIvars]
6210 struct DayListData;
6211
6212 unsafe impl NSObjectProtocol for DayListData {}
6213 unsafe impl NSControlTextEditingDelegate for DayListData {}
6214
6215 impl DayListData {
6216 #[unsafe(method(respondsToSelector:))]
6220 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
6221 if selector == objc2::sel!(tableView:heightOfRow:)
6222 && !self.ivars().automatic
6223 && !self.ivars().sections
6224 && !self.ivars().supplements.get()
6225 {
6226 false
6227 } else {
6228 unsafe { msg_send![super(self), respondsToSelector: selector] }
6229 }
6230 }
6231
6232 #[unsafe(method(listViewportChanged:))]
6236 fn list_viewport_changed(&self, notification: &NSNotification) {
6237 ffi_guard::contain((), || {
6238 if let Some(object) = notification.object()
6239 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
6240 && let Some(document) = clip.documentView()
6241 && let Some(table) = document.downcast_ref::<NSTableView>() {
6242 if &*notification.name()
6243 == unsafe { objc2_app_kit::NSViewBoundsDidChangeNotification }
6244 {
6245 self.note_reader_scroll(table);
6246 }
6247 self.report_viewport(table);
6248 }
6249 });
6250 }
6251
6252 #[unsafe(method(listLiveScrollStarted:))]
6259 fn list_live_scroll_started(&self, notification: &NSNotification) {
6260 ffi_guard::contain((), || {
6261 let Some(object) = notification.object() else { return };
6262 let Some(scroll) = object.downcast_ref::<NSScrollView>() else { return };
6263 scroll::stop_clip_animation(scroll);
6264 let app = NSApplication::sharedApplication(self.mtm());
6265 let held = self.ivars().wheel.get()
6266 || app.currentEvent().is_some_and(|event| match unsafe { event.r#type() } {
6267 NSEventType::ScrollWheel => {
6268 !unsafe { event.phase() }.is_empty()
6269 || !unsafe { event.momentumPhase() }.is_empty()
6270 }
6271 NSEventType::LeftMouseDown | NSEventType::LeftMouseDragged => true,
6272 _ => false,
6273 });
6274 if held {
6275 self.ivars().live.set(true);
6276 } else if let Some(document) = unsafe { scroll.documentView() }
6277 && let Some(table) = document.downcast_ref::<NSTableView>()
6278 {
6279 self.report_reader_scroll(table);
6280 }
6281 });
6282 }
6283
6284 #[unsafe(method(listLiveScrollEnded:))]
6286 fn list_live_scroll_ended(&self, _notification: &NSNotification) {
6287 ffi_guard::contain((), || self.ivars().live.set(false));
6288 }
6289
6290 #[unsafe(method(activateRow:))]
6291 fn activate_row(&self, table: &NSTableView) {
6292 ffi_guard::contain((), || {
6293 let row = unsafe { table.selectedRow() };
6294 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
6295 });
6296 }
6297 #[unsafe(method(doubleClickRow:))]
6298 fn double_click_row(&self, table: &NSTableView) {
6299 ffi_guard::contain((), || {
6300 let row = unsafe { table.clickedRow() };
6301 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
6302 });
6303 }
6304 }
6305
6306 unsafe impl NSTableViewDataSource for DayListData {
6307 #[unsafe(method(numberOfRowsInTableView:))]
6308 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
6309 ffi_guard::contain(0, || {
6313 if let Some(splice) = self.ivars().splice.borrow().as_ref() {
6315 return splice.entries.len() as isize;
6316 }
6317 self.ivars()
6318 .source
6319 .borrow()
6320 .as_ref()
6321 .map_or(0, |s| (s.len)() as isize)
6322 })
6323 }
6324
6325 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
6331 fn pasteboard_writer_for_row(
6332 &self,
6333 _tv: &NSTableView,
6334 row: isize,
6335 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
6336 let make = || {
6339 let reorderable = self
6341 .ivars()
6342 .source
6343 .borrow()
6344 .as_ref()
6345 .is_some_and(|s| s.reorder.is_some());
6346 if !reorderable || row < 0 || self.is_header(row) || self.is_supplement(row) {
6348 return None;
6349 }
6350 let item = objc2_app_kit::NSPasteboardItem::new();
6351 unsafe {
6352 item.setString_forType(
6353 &NSString::from_str(&row.to_string()),
6354 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
6355 );
6356 }
6357 Some(ProtocolObject::from_retained(item))
6358 };
6359 ffi_guard::contain(None, make)
6360 }
6361
6362 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
6363 fn validate_drop(
6364 &self,
6365 tv: &NSTableView,
6366 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6367 row: isize,
6368 _op: objc2_app_kit::NSTableViewDropOperation,
6369 ) -> objc2_app_kit::NSDragOperation {
6370 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
6372 let Some((from, len)) = self.drag_context(tv, info) else {
6373 return objc2_app_kit::NSDragOperation::None;
6374 };
6375 let ins = row.clamp(0, len as isize) as usize;
6378 let to = insertion_to_target(from, ins, len);
6379 let accepted = self.can_move(from, to);
6380 if accepted < 0 {
6381 return objc2_app_kit::NSDragOperation::None;
6382 }
6383 let accepted = (accepted as usize).min(len.saturating_sub(1));
6384 if accepted != to {
6385 unsafe {
6387 tv.setDropRow_dropOperation(
6388 target_to_insertion(from, accepted) as isize,
6389 objc2_app_kit::NSTableViewDropOperation::Above,
6390 );
6391 }
6392 }
6393 objc2_app_kit::NSDragOperation::Move
6394 })
6395 }
6396
6397 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
6398 fn accept_drop(
6399 &self,
6400 tv: &NSTableView,
6401 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6402 row: isize,
6403 _op: objc2_app_kit::NSTableViewDropOperation,
6404 ) -> bool {
6405 let drop = || {
6407 let Some((from, len)) = self.drag_context(tv, info) else {
6408 return false;
6409 };
6410 let ins = row.clamp(0, len as isize) as usize;
6411 let to = insertion_to_target(from, ins, len);
6412 let accepted = self.can_move(from, to);
6413 if accepted < 0 {
6414 return false;
6415 }
6416 let accepted = (accepted as usize).min(len.saturating_sub(1));
6417 if accepted == from {
6418 return true; }
6420 let mv = self
6424 .ivars()
6425 .source
6426 .borrow()
6427 .as_ref()
6428 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
6429 let Some(mv) = mv else { return false };
6430 mv(from, accepted);
6431 {
6434 let mut toks = self.ivars().tokens.borrow_mut();
6435 if from < toks.len() && accepted < toks.len() {
6436 let t = toks.remove(from);
6437 toks.insert(accepted, t);
6438 }
6439 }
6440 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
6441 if let Some(scroll) = tv.enclosingScrollView() {
6442 post_settle_list_drop(ptr_of(&scroll));
6443 }
6444 true
6445 };
6446 ffi_guard::contain(false, drop)
6448 }
6449 }
6450
6451 unsafe impl NSTableViewDelegate for DayListData {
6452 #[unsafe(method(tableView:heightOfRow:))]
6457 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
6458 ffi_guard::contain(44.0, || {
6459 let ivars = self.ivars();
6460 let header = self.is_header(row);
6461 let supplement = self.is_supplement(row);
6462 if !header && !supplement && !ivars.automatic {
6465 return unsafe { tv.rowHeight() };
6466 }
6467 let token = self.source_row(row).and_then(|row| {
6468 ivars
6469 .source
6470 .borrow()
6471 .as_ref()
6472 .filter(|s| row < (s.len)())
6473 .map(|s| (s.token_at)(row))
6474 });
6475 token
6476 .and_then(|t| ivars.heights.borrow().get(&t).copied())
6477 .unwrap_or_else(|| {
6478 if header {
6479 ivars.header_estimate.get()
6480 } else if supplement && !ivars.automatic {
6481 unsafe { tv.rowHeight() }
6482 } else {
6483 ivars.estimate.get()
6484 }
6485 })
6486 })
6487 }
6488
6489 #[unsafe(method(tableView:isGroupRow:))]
6493 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
6494 ffi_guard::contain(false, || self.is_header(row))
6495 }
6496
6497 #[unsafe(method(tableView:shouldSelectRow:))]
6500 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
6501 ffi_guard::contain(true, || !self.is_header(row) && !self.is_supplement(row))
6502 }
6503
6504 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
6505 fn view_for_row(
6506 &self,
6507 tv: &NSTableView,
6508 _col: Option<&NSTableColumn>,
6509 row: isize,
6510 ) -> Option<Retained<NSView>> {
6511 ffi_guard::contain(None, || {
6513 let _pass = RowPass::enter();
6516 let mtm = self.mtm();
6517 let ident = NSString::from_str(if self.is_header(row) {
6520 DAY_HEADER_CELL
6521 } else if self.is_supplement(row) {
6522 DAY_EXTRA_CELL
6523 } else {
6524 DAY_ROW_CELL
6525 });
6526 let cell: Retained<NSView> =
6528 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
6529 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
6530 unsafe { v.setIdentifier(Some(&ident)) };
6531 v
6532 });
6533 let source = self.ivars().source.borrow().clone();
6537 if let Some(source) = source
6539 && let Some(index) = self.source_row(row)
6540 {
6541 let raw = Retained::as_ptr(&cell) as RawHandle;
6542 let busy = day_core::try_with_tree(|_| ()).is_none();
6545 (source.bind_row)(index, raw);
6546 if busy {
6547 self.ivars().unbound.borrow_mut().insert(raw as usize);
6548 } else {
6549 self.ivars().unbound.borrow_mut().remove(&(raw as usize));
6550 self.note_row_height(tv, &source, row, raw);
6551 }
6552 }
6553 Some(cell)
6554 })
6555 }
6556
6557 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
6558 fn did_remove_row_view(
6559 &self,
6560 _tv: &NSTableView,
6561 row_view: &objc2_app_kit::NSTableRowView,
6562 _row: isize,
6563 ) {
6564 ffi_guard::contain((), || {
6570 let Some(cell) = row_view.subviews().iter().find(|sub| {
6571 sub.identifier()
6572 .is_some_and(|i| {
6573 let i = i.to_string();
6574 i == DAY_ROW_CELL || i == DAY_HEADER_CELL || i == DAY_EXTRA_CELL
6575 })
6576 }) else {
6577 return;
6578 };
6579 let cell = Retained::into_raw(cell) as usize;
6582 let Some(this) = (unsafe {
6583 Retained::retain(std::ptr::from_ref::<DayListData>(self).cast_mut())
6584 }) else {
6585 return;
6586 };
6587 let this = Retained::into_raw(this) as usize;
6588 <AppKit as Platform>::post(Box::new(move || {
6589 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
6591 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
6592 let (Some(this), Some(cell)) = (this, cell) else {
6593 return;
6594 };
6595 if cell.window().is_some() {
6596 return; }
6598 let recycle = this
6599 .ivars()
6600 .source
6601 .borrow()
6602 .as_ref()
6603 .map(|s| s.recycle.clone());
6604 if let Some(recycle) = recycle {
6605 recycle(Retained::as_ptr(&cell) as RawHandle);
6606 }
6607 }));
6608 });
6609 }
6610
6611 #[unsafe(method(tableViewSelectionDidChange:))]
6612 fn selection_did_change(&self, notification: &NSNotification) {
6613 ffi_guard::contain((), || {
6614 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
6615 return;
6616 }
6617 let Some(obj) = (unsafe { notification.object() }) else {
6618 return;
6619 };
6620 let Ok(tv) = obj.downcast::<NSTableView>() else {
6621 return;
6622 };
6623 if self.ivars().multi.get() {
6624 let idx = unsafe { tv.selectedRowIndexes() };
6626 let mut rows = Vec::with_capacity(idx.count());
6627 let mut i = idx.firstIndex();
6628 while i != objc2_foundation::NSNotFound as usize {
6629 rows.push(i as i64);
6630 i = unsafe { idx.indexGreaterThanIndex(i) };
6631 }
6632 emit(self.ivars().node, Event::SelectionSet(rows));
6633 } else {
6634 let row = unsafe { tv.selectedRow() };
6635 if row >= 0 {
6636 emit(self.ivars().node, Event::SelectionChanged(row as i64));
6637 } else {
6638 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
6646 }
6647 }
6648 });
6649 }
6650
6651 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
6657 fn row_actions_for_row(
6658 &self,
6659 tv: &NSTableView,
6660 row: isize,
6661 edge: objc2_app_kit::NSTableRowActionEdge,
6662 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
6663 ffi_guard::contain(NSArray::new(), || {
6665 let sw = self
6666 .ivars()
6667 .source
6668 .borrow()
6669 .as_ref()
6670 .and_then(|s| s.swipe.clone());
6671 let Some(sw) = sw else {
6672 return NSArray::new();
6673 };
6674 if row < 0 {
6675 return NSArray::new();
6676 }
6677 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
6679 day_spec::SwipeEdge::Leading
6680 } else {
6681 day_spec::SwipeEdge::Trailing
6682 };
6683 let offer = (sw.actions_at)(row as usize, day_edge);
6684 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
6685 .iter()
6686 .enumerate()
6687 .map(|(i, a)| {
6688 let style = if a.destructive {
6689 objc2_app_kit::NSTableViewRowActionStyle::Destructive
6690 } else {
6691 objc2_app_kit::NSTableViewRowActionStyle::Regular
6692 };
6693 let perform = sw.perform.clone();
6694 let table = tv.retain();
6697 let handler = block2::RcBlock::new(
6698 move |_action: std::ptr::NonNull<
6699 objc2_app_kit::NSTableViewRowAction,
6700 >,
6701 row: isize| {
6702 ffi_guard::contain((), || {
6703 perform(row as usize, day_edge, i);
6704 unsafe { table.setRowActionsVisible(false) };
6707 });
6708 },
6709 );
6710 let action =
6711 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
6712 style,
6713 &NSString::from_str(&a.label),
6714 &handler,
6715 );
6716 if let Some(t) = a.tint {
6717 unsafe { action.setBackgroundColor(Some(&color::nsink(t))) };
6718 }
6719 if let Some(sym) = a.symbol {
6723 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
6724 &NSString::from_str(day_spec::sf_symbol_name(sym)),
6725 None,
6726 );
6727 if let Some(img) = img {
6728 unsafe { action.setImage(Some(&img)) };
6729 }
6730 }
6731 action
6732 })
6733 .collect();
6734 NSArray::from_retained_slice(&actions)
6735 })
6736 }
6737 }
6738);
6739
6740impl DayListData {
6741 fn new(
6742 mtm: MainThreadMarker,
6743 node: NodeId,
6744 selectable: bool,
6745 multi: bool,
6746 automatic: bool,
6747 sections: bool,
6748 ) -> Retained<Self> {
6749 let this = Self::alloc(mtm).set_ivars(ListIvars {
6750 node,
6751 source: RefCell::new(None),
6752 selectable: std::cell::Cell::new(selectable),
6753 multi: std::cell::Cell::new(multi),
6754 suppress: std::cell::Cell::new(false),
6755 tokens: RefCell::new(Vec::new()),
6756 automatic,
6757 sections,
6758 header_estimate: std::cell::Cell::new(28.0),
6759 heights: RefCell::new(std::collections::HashMap::new()),
6760 cell_tokens: RefCell::new(std::collections::HashMap::new()),
6761 estimate: std::cell::Cell::new(44.0),
6762 heights_pending: std::cell::Cell::new(false),
6763 supplements: std::cell::Cell::new(false),
6764 unbound: RefCell::new(std::collections::HashSet::new()),
6765 splice: RefCell::new(None),
6766 live: std::cell::Cell::new(false),
6767 input: std::cell::Cell::new(false),
6768 wheel: std::cell::Cell::new(false),
6769 held: RefCell::new(None),
6770 held_posted: std::cell::Cell::new(false),
6771 applying: std::cell::Cell::new(false),
6772 });
6773 unsafe { msg_send![super(this), init] }
6774 }
6775
6776 fn note_row_height(
6781 &self,
6782 table: &NSTableView,
6783 source: &ListSource,
6784 row: isize,
6785 cell: RawHandle,
6786 ) {
6787 let header = self.is_header(row);
6788 let supplement = self.is_supplement(row);
6789 if !self.ivars().automatic && !header && !supplement {
6790 return;
6791 }
6792 let height = (source.cell_height)(cell);
6793 let Some(index) = self.source_row(row).filter(|_| height > 0.0) else {
6794 return;
6795 };
6796 let token = (source.token_at)(index);
6797 self.ivars()
6798 .cell_tokens
6799 .borrow_mut()
6800 .insert(cell as usize, token);
6801 self.ivars().heights.borrow_mut().insert(token, height);
6802 if header {
6804 self.ivars().header_estimate.set(height);
6805 } else if !supplement {
6806 self.ivars().estimate.set(height);
6807 }
6808 let drawn = unsafe { table.rectOfRow(row) }.size.height;
6809 if (drawn - height).abs() > 0.5 {
6810 self.post_row_heights(table);
6811 }
6812 }
6813
6814 fn source_row(&self, row: isize) -> Option<usize> {
6817 let row = usize::try_from(row).ok()?;
6818 match self.ivars().splice.borrow().as_ref() {
6819 Some(splice) => splice.source_row(row),
6820 None => Some(row),
6821 }
6822 }
6823
6824 fn is_header(&self, row: isize) -> bool {
6826 self.source_row(row).is_some_and(|row| {
6827 self.ivars()
6828 .source
6829 .borrow()
6830 .as_ref()
6831 .and_then(|s| s.is_header.clone())
6832 .is_some_and(|is_header| is_header(row))
6833 })
6834 }
6835
6836 fn splice_fits(&self, table: &NSTableView, deltas: &[day_spec::props::RowDelta]) -> bool {
6839 let shown = unsafe { table.numberOfRows() }.max(0) as usize;
6840 let now = self
6841 .ivars()
6842 .source
6843 .borrow()
6844 .as_ref()
6845 .map_or(0, |s| (s.len)());
6846 splice_fits(shown, deltas, now)
6847 }
6848
6849 fn reload_keeping_offset(&self, table: &NSTableView) {
6852 let selected = unsafe { table.selectedRowIndexes() };
6853 let tokens: Vec<u64> = self
6854 .ivars()
6855 .tokens
6856 .borrow()
6857 .iter()
6858 .enumerate()
6859 .filter(|(row, _)| selected.containsIndex(*row))
6860 .map(|(_, token)| *token)
6861 .collect();
6862 let scroll = table.enclosingScrollView();
6863 let origin = scroll
6864 .as_ref()
6865 .map(|s| unsafe { s.contentView() }.bounds().origin);
6866 self.ivars().suppress.set(true);
6867 unsafe { table.reloadData() };
6868 if let Some(source) = self.ivars().source.borrow().as_ref() {
6869 let n = (source.len)();
6870 *self.ivars().tokens.borrow_mut() = (0..n).map(|i| (source.token_at)(i)).collect();
6871 }
6872 let restored = objc2_foundation::NSMutableIndexSet::new();
6873 for (row, token) in self.ivars().tokens.borrow().iter().enumerate() {
6874 if tokens.contains(token) {
6875 restored.addIndex(row);
6876 }
6877 }
6878 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
6879 self.ivars().suppress.set(false);
6880 if let (Some(scroll), Some(origin)) = (scroll, origin) {
6881 let clip = unsafe { scroll.contentView() };
6882 if clip.bounds().origin != origin {
6883 scroll::scroll_clip_to(&scroll, origin, false, None);
6884 }
6885 }
6886 }
6887
6888 fn change_rows(
6894 &self,
6895 key: usize,
6896 table: &NSTableView,
6897 deltas: Option<&[day_spec::props::RowDelta]>,
6898 ) {
6899 let applying = self.ivars().applying.get();
6900 if !RowPass::active() && !applying {
6901 match deltas {
6902 Some(deltas) => self.splice_rows(table, deltas),
6903 None => self.reload_rows(table),
6904 }
6905 return;
6906 }
6907 {
6908 let mut held = self.ivars().held.borrow_mut();
6909 let held = held.get_or_insert_with(|| HeldRows {
6910 deltas: Some(Vec::new()),
6911 selected: None,
6912 });
6913 match (deltas, held.deltas.as_mut()) {
6915 (Some(deltas), Some(all)) => all.extend_from_slice(deltas),
6916 _ => held.deltas = None,
6917 }
6918 }
6919 if !applying {
6922 self.map_held(table);
6923 }
6924 self.post_held(key);
6925 }
6926
6927 fn select(&self, table: &NSTableView, rows: &[usize]) {
6931 if self.ivars().held.borrow().is_none() {
6932 self.select_rows(table, rows);
6933 return;
6934 }
6935 let tokens: Vec<u64> =
6936 self.ivars()
6937 .source
6938 .borrow()
6939 .as_ref()
6940 .map_or_else(Vec::new, |source| {
6941 let n = (source.len)();
6942 rows.iter()
6943 .filter(|row| **row < n)
6944 .map(|row| (source.token_at)(*row))
6945 .collect()
6946 });
6947 if let Some(held) = self.ivars().held.borrow_mut().as_mut() {
6948 held.selected = Some(tokens);
6949 }
6950 }
6951
6952 fn map_held(&self, table: &NSTableView) {
6956 let shown = unsafe { table.numberOfRows() }.max(0) as usize;
6957 let map = self
6958 .ivars()
6959 .held
6960 .borrow()
6961 .as_ref()
6962 .and_then(|held| held.deltas.as_ref())
6963 .map(|deltas| SpliceRows::new(shown, deltas));
6964 *self.ivars().splice.borrow_mut() = map;
6965 }
6966
6967 fn post_held(&self, key: usize) {
6969 if self.ivars().held_posted.replace(true) {
6970 return;
6971 }
6972 <AppKit as Platform>::post(Box::new(move || {
6973 let Some((table, data)) = list_entry(key) else {
6974 return;
6975 };
6976 data.ivars().held_posted.set(false);
6977 if RowPass::active() || data.ivars().applying.get() {
6978 data.post_held(key);
6980 } else {
6981 data.apply_held(&table);
6982 }
6983 }));
6984 }
6985
6986 fn apply_held(&self, table: &NSTableView) {
6990 if RowPass::active() || self.ivars().applying.get() {
6991 return;
6992 }
6993 let Some(held) = self.ivars().held.borrow_mut().take() else {
6994 return;
6995 };
6996 self.ivars().splice.borrow_mut().take();
6998 match &held.deltas {
6999 Some(deltas) => self.splice_rows(table, deltas),
7000 None => self.reload_rows(table),
7001 }
7002 if let Some(tokens) = held.selected {
7003 let rows: Vec<usize> =
7004 self.ivars()
7005 .source
7006 .borrow()
7007 .as_ref()
7008 .map_or_else(Vec::new, |source| {
7009 (0..(source.len)())
7010 .filter(|row| tokens.contains(&(source.token_at)(*row)))
7011 .collect()
7012 });
7013 self.select_rows(table, &rows);
7014 }
7015 if let Some(scroll) = table.enclosingScrollView() {
7016 post_realize_visible_rows(ptr_of(&scroll));
7017 }
7018 }
7019
7020 fn splice_rows(&self, table: &NSTableView, deltas: &[day_spec::props::RowDelta]) {
7025 use objc2_app_kit::NSTableViewAnimationOptions;
7026 if !self.splice_fits(table, deltas) {
7027 log::warn!(
7031 "day-toolkit-appkit: a list splice of {} rows does not fit the {} rows shown; reloading",
7032 deltas.len(),
7033 unsafe { table.numberOfRows() }
7034 );
7035 let applying = self.ivars().applying.replace(true);
7036 self.reload_keeping_offset(table);
7037 self.ivars().applying.set(applying);
7038 self.map_held(table);
7039 return;
7040 }
7041 let quiet = deltas.len() > SPLICE_ANIMATED_MAX;
7044 let (insert, remove) = if quiet {
7045 (
7046 NSTableViewAnimationOptions::EffectNone,
7047 NSTableViewAnimationOptions::EffectNone,
7048 )
7049 } else {
7050 (
7051 NSTableViewAnimationOptions::SlideDown,
7052 NSTableViewAnimationOptions::SlideUp,
7053 )
7054 };
7055 if quiet {
7056 NSAnimationContext::beginGrouping();
7057 NSAnimationContext::currentContext().setDuration(0.0);
7058 }
7059 let shown = unsafe { table.numberOfRows() }.max(0) as usize;
7062 *self.ivars().splice.borrow_mut() = Some(SpliceRows::new(shown, deltas));
7063 {
7064 let applying = self.ivars().applying.replace(true);
7065 let _done = std::mem::DropGuard::new((), |()| {
7066 self.ivars().applying.set(applying);
7067 });
7068 for d in deltas {
7069 if let Some(splice) = self.ivars().splice.borrow_mut().as_mut() {
7070 splice.apply(*d);
7071 }
7072 unsafe {
7073 table.beginUpdates();
7074 match d {
7075 day_spec::props::RowDelta::Insert(i) => table
7076 .insertRowsAtIndexes_withAnimation(
7077 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
7078 insert,
7079 ),
7080 day_spec::props::RowDelta::Remove(i) => table
7081 .removeRowsAtIndexes_withAnimation(
7082 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
7083 remove,
7084 ),
7085 day_spec::props::RowDelta::Move(from, to) => {
7086 table.moveRowAtIndex_toIndex(*from as isize, *to as isize);
7087 }
7088 }
7089 table.endUpdates();
7090 }
7091 }
7092 }
7093 self.ivars().splice.borrow_mut().take();
7094 if quiet {
7095 NSAnimationContext::endGrouping();
7096 }
7097 if let Some(source) = self.ivars().source.borrow().as_ref() {
7101 let n = (source.len)();
7102 *self.ivars().tokens.borrow_mut() = (0..n).map(|i| (source.token_at)(i)).collect();
7103 }
7104 self.map_held(table);
7106 }
7107
7108 fn reload_rows(&self, table: &NSTableView) {
7112 let selected = unsafe { table.selectedRowIndexes() };
7113 let tokens: Vec<u64> = self
7114 .ivars()
7115 .tokens
7116 .borrow()
7117 .iter()
7118 .enumerate()
7119 .filter(|(row, _)| selected.containsIndex(*row))
7120 .map(|(_, token)| *token)
7121 .collect();
7122 self.ivars().suppress.set(true);
7123 {
7124 let applying = self.ivars().applying.replace(true);
7125 let _done = std::mem::DropGuard::new((), |()| {
7126 self.ivars().applying.set(applying);
7127 });
7128 if let Some(moves) = self.permutation_moves(table) {
7134 unsafe {
7135 table.beginUpdates();
7136 for (from, to) in moves {
7137 table.moveRowAtIndex_toIndex(from as isize, to as isize);
7138 }
7139 table.endUpdates();
7140 }
7141 } else {
7142 unsafe { table.reloadData() };
7143 }
7144 }
7145 let restored = objc2_foundation::NSMutableIndexSet::new();
7146 for (row, token) in self.ivars().tokens.borrow().iter().enumerate() {
7147 if tokens.contains(token) {
7148 restored.addIndex(row);
7149 }
7150 }
7151 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
7152 self.ivars().suppress.set(false);
7153 self.map_held(table);
7154 }
7155
7156 fn select_rows(&self, table: &NSTableView, rows: &[usize]) {
7159 self.ivars().suppress.set(true);
7160 unsafe {
7161 if rows.is_empty() {
7162 table.deselectAll(None);
7163 } else {
7164 let set = objc2_foundation::NSMutableIndexSet::new();
7165 let count = table.numberOfRows().max(0) as usize;
7166 for r in rows.iter().copied().filter(|r| *r < count) {
7167 set.addIndex(r);
7168 }
7169 table.selectRowIndexes_byExtendingSelection(&set, false);
7170 }
7171 }
7172 self.ivars().suppress.set(false);
7173 }
7174
7175 fn is_supplement(&self, row: isize) -> bool {
7178 self.source_row(row).is_some_and(|row| {
7179 self.ivars()
7180 .source
7181 .borrow()
7182 .as_ref()
7183 .and_then(|s| s.is_supplement.clone())
7184 .is_some_and(|is_supplement| is_supplement(row))
7185 })
7186 }
7187
7188 fn report_viewport(&self, table: &NSTableView) {
7194 let Some(source) = self.ivars().source.borrow().clone() else {
7195 return;
7196 };
7197 let n = (source.len)();
7198 if n == 0 || unsafe { table.numberOfRows() } != n as isize {
7199 return;
7200 }
7201 let visible = table.visibleRect();
7202 let shown = unsafe { table.rowsInRect(visible) };
7203 if let Some(report) = &source.viewport {
7204 let top = visible.origin.y;
7205 let bottom = top + visible.size.height;
7206 let count = shown.length.min(n.saturating_sub(shown.location));
7207 let span = scroll::visible_span(top, bottom, shown.location, count, |row| {
7208 let rect = unsafe { table.rectOfRow(row as isize) };
7209 (rect.origin.y, rect.origin.y + rect.size.height)
7210 });
7211 let Some((first, last)) = span else {
7212 return;
7213 };
7214 let end = unsafe { table.rectOfRow(n as isize - 1) };
7215 report(day_spec::ListViewport {
7216 first,
7217 last,
7218 end_distance: (end.origin.y + end.size.height - bottom).max(0.0),
7219 });
7220 } else if let Some(report) = &source.first_visible {
7221 report(shown.location.min(n - 1));
7222 }
7223 }
7224
7225 fn note_reader_scroll(&self, table: &NSTableView) {
7231 let ivars = self.ivars();
7232 if ivars.live.get() || ivars.input.get() {
7233 self.report_reader_scroll(table);
7234 }
7235 }
7236
7237 fn report_reader_scroll(&self, table: &NSTableView) {
7239 let rows = unsafe { table.numberOfRows() };
7240 if rows <= 0 {
7241 return;
7242 }
7243 let end = unsafe { table.rectOfRow(rows - 1) };
7244 let visible = table.visibleRect();
7245 if end.origin.y + end.size.height - (visible.origin.y + visible.size.height) > 0.0 {
7246 self.report_reader_leaving(table);
7247 }
7248 }
7249
7250 fn report_reader_leaving(&self, table: &NSTableView) {
7253 let report = self
7254 .ivars()
7255 .source
7256 .borrow()
7257 .as_ref()
7258 .and_then(|s| s.reader_scroll.clone());
7259 if let Some(report) = report
7260 && unsafe { table.numberOfRows() } > 0
7261 {
7262 report();
7263 }
7264 }
7265
7266 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
7269 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
7270 if let Some(token) = token {
7271 self.ivars().heights.borrow_mut().insert(token, height);
7272 self.post_row_heights(table);
7273 }
7274 }
7275
7276 fn post_row_heights(&self, table: &NSTableView) {
7280 if self.ivars().heights_pending.replace(true) {
7281 return;
7282 }
7283 let Some(this) = (unsafe { Retained::retain(std::ptr::from_ref::<Self>(self).cast_mut()) })
7286 else {
7287 return;
7288 };
7289 let this = Retained::into_raw(this) as usize;
7290 let table = Retained::into_raw(table.retain()) as usize;
7291 <AppKit as Platform>::post(Box::new(move || {
7292 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
7294 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
7295 let (Some(this), Some(table)) = (this, table) else {
7296 return;
7297 };
7298 this.ivars().heights_pending.set(false);
7299 ffi_guard::contain((), || this.apply_row_heights(&table));
7300 }));
7301 }
7302
7303 fn apply_row_heights(&self, table: &NSTableView) {
7304 self.apply_held(table);
7306 let Some(source) = self.ivars().source.borrow().clone() else {
7307 return;
7308 };
7309 let count = unsafe { table.numberOfRows() }.max(0) as usize;
7310 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
7311 let first = shown.location.saturating_sub(8);
7313 let last = (shown.location + shown.length + 8)
7314 .min(count)
7315 .min((source.len)());
7316 let changed = objc2_foundation::NSMutableIndexSet::new();
7317 {
7318 let heights = self.ivars().heights.borrow();
7319 for row in first..last {
7320 if let Some(&height) = heights.get(&(source.token_at)(row)) {
7321 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
7322 if (drawn - height).abs() > 0.5 {
7323 unsafe { changed.addIndex(row) };
7324 }
7325 }
7326 }
7327 }
7328 if changed.count() == 0 {
7329 return;
7330 }
7331 NSAnimationContext::beginGrouping();
7333 NSAnimationContext::currentContext().setDuration(0.0);
7334 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
7335 NSAnimationContext::endGrouping();
7336 self.report_viewport(table);
7338 }
7339
7340 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
7352 let source = self.ivars().source.borrow();
7353 let source = source.as_ref()?;
7354 let n = (source.len)();
7355 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
7356 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
7357 if old.len() != n || n == 0 || old == new {
7358 return None;
7359 }
7360 let (mut so, mut sn) = (old.clone(), new.clone());
7361 so.sort_unstable();
7362 sn.sort_unstable();
7363 if so != sn {
7364 return None;
7365 }
7366 for i in 0..n {
7367 if old[i] != new[i]
7368 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
7369 {
7370 return None;
7371 }
7372 }
7373 let mut work = old;
7374 let mut moves = Vec::new();
7375 for i in 0..n {
7376 if work[i] == new[i] {
7377 continue;
7378 }
7379 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
7380 let t = work.remove(j);
7381 work.insert(i, t);
7382 moves.push((j, i));
7383 }
7384 Some(moves)
7385 }
7386
7387 fn drag_context(
7391 &self,
7392 tv: &NSTableView,
7393 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7394 ) -> Option<(usize, usize)> {
7395 let src = unsafe { info.draggingSource() }?;
7396 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
7397 != std::ptr::from_ref::<NSTableView>(tv).cast::<std::ffi::c_void>()
7398 {
7399 return None;
7400 }
7401 let pb = unsafe { info.draggingPasteboard() };
7402 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
7403 .to_string()
7404 .parse::<usize>()
7405 .ok()?;
7406 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
7407 (from < len).then_some((from, len))
7408 }
7409
7410 fn can_move(&self, from: usize, to: usize) -> i64 {
7412 self.ivars()
7413 .source
7414 .borrow()
7415 .as_ref()
7416 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
7417 .unwrap_or(-1)
7418 }
7419}
7420
7421const DAY_ROW_CELL: &str = "day.cell";
7423const DAY_HEADER_CELL: &str = "day.header";
7424const DAY_EXTRA_CELL: &str = "day.extra";
7427
7428const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
7430
7431const SPLICE_ANIMATED_MAX: usize = 64;
7433
7434fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
7437 let to = if ins > from { ins - 1 } else { ins };
7438 to.min(len.saturating_sub(1))
7439}
7440
7441fn splice_fits(shown: usize, deltas: &[day_spec::props::RowDelta], now: usize) -> bool {
7446 use day_spec::props::RowDelta;
7447 let mut count = shown;
7448 for delta in deltas {
7449 match *delta {
7450 RowDelta::Insert(i) if i <= count => count += 1,
7451 RowDelta::Remove(i) if i < count => count -= 1,
7452 RowDelta::Move(from, to) if from < count && to < count => {}
7453 _ => return false,
7454 }
7455 }
7456 count == now
7457}
7458
7459fn target_to_insertion(from: usize, to: usize) -> usize {
7461 if to > from { to + 1 } else { to }
7462}
7463
7464type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
7466
7467fn list_entry(key: usize) -> Option<ListEntry> {
7474 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
7475}
7476
7477struct TreeIvars {
7482 node: NodeId,
7483 source: RefCell<Option<TreeSource>>,
7485 selectable: std::cell::Cell<bool>,
7486 suppress: std::cell::Cell<bool>,
7488 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
7492}
7493
7494define_class!(
7495 #[unsafe(super(NSObject))]
7496 #[thread_kind = MainThreadOnly]
7497 #[name = "DayTreeData"]
7498 #[ivars = TreeIvars]
7499 struct DayTreeData;
7500
7501 unsafe impl NSObjectProtocol for DayTreeData {}
7502
7503 unsafe impl NSOutlineViewDataSource for DayTreeData {
7504 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
7505 fn number_of_children(
7506 &self,
7507 _ov: &objc2_app_kit::NSOutlineView,
7508 item: Option<&objc2::runtime::AnyObject>,
7509 ) -> isize {
7510 ffi_guard::contain(0, || {
7514 let parent = item.and_then(Self::token_of_item);
7515 if item.is_some() && parent.is_none() {
7516 return 0; }
7518 self.ivars()
7519 .source
7520 .borrow()
7521 .as_ref()
7522 .map_or(0, |s| (s.children_len)(parent) as isize)
7523 })
7524 }
7525
7526 #[unsafe(method_id(outlineView:child:ofItem:))]
7527 fn child_of_item(
7528 &self,
7529 _ov: &objc2_app_kit::NSOutlineView,
7530 index: isize,
7531 item: Option<&objc2::runtime::AnyObject>,
7532 ) -> Retained<objc2::runtime::AnyObject> {
7533 let token = ffi_guard::contain(0, || {
7537 let parent = item.and_then(Self::token_of_item);
7538 self.ivars()
7539 .source
7540 .borrow()
7541 .as_ref()
7542 .map_or(0, |s| (s.child_token)(parent, index.max(0) as usize))
7543 });
7544 let ns = self.intern(token);
7545 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
7546 }
7547
7548 #[unsafe(method(outlineView:isItemExpandable:))]
7549 fn is_expandable(
7550 &self,
7551 _ov: &objc2_app_kit::NSOutlineView,
7552 item: &objc2::runtime::AnyObject,
7553 ) -> bool {
7554 ffi_guard::contain(false, || {
7555 let Some(token) = Self::token_of_item(item) else {
7556 return false;
7557 };
7558 self.ivars()
7559 .source
7560 .borrow()
7561 .as_ref()
7562 .is_some_and(|s| (s.expandable)(token))
7563 })
7564 }
7565
7566 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
7572 fn pasteboard_writer_for_item(
7573 &self,
7574 _ov: &objc2_app_kit::NSOutlineView,
7575 item: &objc2::runtime::AnyObject,
7576 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
7577 let make = || {
7578 let movable = self
7579 .ivars()
7580 .source
7581 .borrow()
7582 .as_ref()
7583 .is_some_and(|s| s.moves.is_some());
7584 let token = Self::token_of_item(item)?;
7585 if !movable {
7586 return None;
7587 }
7588 let pbitem = objc2_app_kit::NSPasteboardItem::new();
7589 unsafe {
7590 pbitem.setString_forType(
7591 &NSString::from_str(&token.to_string()),
7592 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
7593 );
7594 }
7595 Some(ProtocolObject::from_retained(pbitem))
7596 };
7597 ffi_guard::contain(None, make)
7598 }
7599
7600 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
7601 fn validate_drop(
7602 &self,
7603 ov: &objc2_app_kit::NSOutlineView,
7604 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7605 item: Option<&objc2::runtime::AnyObject>,
7606 child_index: isize,
7607 ) -> objc2_app_kit::NSDragOperation {
7608 ffi_guard::contain(
7609 objc2_app_kit::NSDragOperation::None,
7610 || match Self::drop_proposal(ov, info, item, child_index) {
7611 Some((token, parent, index)) if self.can_move(token, parent, index) => {
7612 objc2_app_kit::NSDragOperation::Move
7613 }
7614 _ => objc2_app_kit::NSDragOperation::None,
7615 },
7616 )
7617 }
7618
7619 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
7620 fn accept_drop(
7621 &self,
7622 ov: &objc2_app_kit::NSOutlineView,
7623 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7624 item: Option<&objc2::runtime::AnyObject>,
7625 child_index: isize,
7626 ) -> bool {
7627 let drop = || {
7628 let Some((token, parent, index)) = Self::drop_proposal(ov, info, item, child_index)
7629 else {
7630 return false;
7631 };
7632 if !self.can_move(token, parent, index) {
7633 return false;
7634 }
7635 let mv = self
7638 .ivars()
7639 .source
7640 .borrow()
7641 .as_ref()
7642 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
7643 let Some(mv) = mv else { return false };
7644 mv(token, parent, index);
7645 true
7646 };
7647 ffi_guard::contain(false, drop)
7648 }
7649 }
7650
7651 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
7652
7653 unsafe impl NSOutlineViewDelegate for DayTreeData {
7654 #[unsafe(method(outlineView:isGroupItem:))]
7655 fn is_group_item(
7656 &self,
7657 _ov: &objc2_app_kit::NSOutlineView,
7658 item: &objc2::runtime::AnyObject,
7659 ) -> bool {
7660 Self::token_of_item(item).is_some_and(|t| {
7661 self.ivars()
7662 .source
7663 .borrow()
7664 .as_ref()
7665 .is_some_and(|s| (s.section_header)(t))
7666 })
7667 }
7668 #[unsafe(method(outlineView:shouldSelectItem:))]
7669 fn should_select_item(
7670 &self,
7671 _ov: &objc2_app_kit::NSOutlineView,
7672 item: &objc2::runtime::AnyObject,
7673 ) -> bool {
7674 Self::token_of_item(item).is_some_and(|t| {
7675 self.ivars()
7676 .source
7677 .borrow()
7678 .as_ref()
7679 .is_some_and(|s| !(s.section_header)(t))
7680 })
7681 }
7682
7683 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
7684 fn view_for_item(
7685 &self,
7686 ov: &objc2_app_kit::NSOutlineView,
7687 _col: Option<&NSTableColumn>,
7688 item: &objc2::runtime::AnyObject,
7689 ) -> Option<Retained<NSView>> {
7690 ffi_guard::contain(None, || {
7692 let mtm = self.mtm();
7693 let token = Self::token_of_item(item)?;
7694 let ident = NSString::from_str("day.tree.cell");
7695 let cell: Retained<NSView> =
7699 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
7700 let v: Retained<NSView> =
7701 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
7702 unsafe { v.setIdentifier(Some(&ident)) };
7703 v
7704 });
7705 if let Some(source) = self.ivars().source.borrow().as_ref() {
7706 let raw = Retained::as_ptr(&cell) as RawHandle;
7707 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
7708 unsafe {
7709 cell.setTextField(None);
7710 }
7711 }
7712 (source.bind_row)(token, raw);
7713 if (source.section_header)(token) {
7716 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
7717 for child in &unsafe { view.subviews() } {
7718 if let Ok(label) = child.clone().downcast::<NSTextField>() {
7719 return Some(label);
7720 }
7721 if let Some(label) = label_in(&child) {
7722 return Some(label);
7723 }
7724 }
7725 None
7726 }
7727 if let Some(label) = label_in(&cell) {
7728 let cell = cell.downcast_ref::<DayTreeCell>()?;
7729 unsafe {
7730 cell.setTextField(Some(&label));
7731 }
7732 }
7733 }
7734 }
7735 Some(cell)
7736 })
7737 }
7738
7739 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
7740 fn type_select_string(
7741 &self,
7742 _ov: &objc2_app_kit::NSOutlineView,
7743 _col: Option<&NSTableColumn>,
7744 item: &objc2::runtime::AnyObject,
7745 ) -> Option<Retained<NSString>> {
7746 ffi_guard::contain(None, || {
7747 let token = Self::token_of_item(item)?;
7748 let text = self
7749 .ivars()
7750 .source
7751 .borrow()
7752 .as_ref()
7753 .map_or_default(|s| (s.type_select_text)(token));
7754 (!text.is_empty()).then(|| NSString::from_str(&text))
7756 })
7757 }
7758
7759 #[unsafe(method_id(outlineView:rowViewForItem:))]
7760 fn row_view_for_item(
7761 &self,
7762 ov: &objc2_app_kit::NSOutlineView,
7763 _item: &objc2::runtime::AnyObject,
7764 ) -> Retained<objc2_app_kit::NSTableRowView> {
7765 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
7766 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
7768 } else {
7769 let rv: Retained<DayTreeRowView> =
7771 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
7772 Retained::into_super(rv)
7773 }
7774 }
7775
7776 #[unsafe(method(outlineViewSelectionDidChange:))]
7777 fn selection_did_change(&self, notification: &NSNotification) {
7778 ffi_guard::contain((), || {
7779 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
7780 return;
7781 }
7782 let Some(obj) = (unsafe { notification.object() }) else {
7783 return;
7784 };
7785 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
7786 return;
7787 };
7788 let idx = unsafe { ov.selectedRowIndexes() };
7790 let mut tokens = Vec::with_capacity(idx.count());
7791 let mut i = idx.firstIndex();
7792 while i != objc2_foundation::NSNotFound as usize {
7793 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
7794 && let Some(tok) = Self::token_of_item(&item)
7795 {
7796 tokens.push(tok);
7797 }
7798 i = unsafe { idx.indexGreaterThanIndex(i) };
7799 }
7800 emit(self.ivars().node, Event::TreeSelection(tokens));
7801 });
7802 }
7803
7804 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
7805 fn did_remove_row_view(
7806 &self,
7807 ov: &objc2_app_kit::NSOutlineView,
7808 row_view: &objc2_app_kit::NSTableRowView,
7809 _row: isize,
7810 ) {
7811 ffi_guard::contain((), || {
7817 let mut cell_ptr: Option<usize> = None;
7818 for sub in &row_view.subviews() {
7819 let is_cell = sub
7820 .identifier()
7821 .is_some_and(|i| i.to_string() == "day.tree.cell");
7822 if is_cell {
7823 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
7824 }
7825 }
7826 let Some(cell) = cell_ptr else { return };
7827 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
7828 return;
7829 };
7830 let key = Retained::as_ptr(&scroll) as usize;
7831 let retained =
7835 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
7836 as usize;
7837 <AppKit as Platform>::post(Box::new(move || {
7838 let cell_view: Retained<NSView> =
7841 match unsafe { Retained::from_raw(retained as *mut NSView) } {
7842 Some(v) => v,
7843 None => return,
7844 };
7845 let recycle = tree_entry(key).and_then(|(_, data)| {
7846 data.ivars()
7847 .source
7848 .borrow()
7849 .as_ref()
7850 .map(|s| s.recycle.clone())
7851 });
7852 let Some(recycle) = recycle else { return };
7853 if cell_view.window().is_some() {
7854 return; }
7856 recycle(cell as RawHandle);
7857 }));
7858 });
7859 }
7860
7861 #[unsafe(method(outlineViewItemDidExpand:))]
7862 fn item_did_expand(&self, notification: &NSNotification) {
7863 self.report_disclosure(notification, true);
7864 }
7865
7866 #[unsafe(method(outlineViewItemDidCollapse:))]
7867 fn item_did_collapse(&self, notification: &NSNotification) {
7868 self.report_disclosure(notification, false);
7869 }
7870 }
7871);
7872
7873impl DayTreeData {
7874 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
7875 let this = Self::alloc(mtm).set_ivars(TreeIvars {
7876 node,
7877 source: RefCell::new(None),
7878 selectable: std::cell::Cell::new(selectable),
7879 suppress: std::cell::Cell::new(false),
7880 items: RefCell::new(HashMap::new()),
7881 });
7882 unsafe { msg_send![super(this), init] }
7883 }
7884
7885 fn intern(&self, token: u64) -> Retained<NSNumber> {
7887 self.ivars()
7888 .items
7889 .borrow_mut()
7890 .entry(token)
7891 .or_insert_with(|| NSNumber::new_u64(token))
7892 .clone()
7893 }
7894
7895 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
7896 item.downcast_ref::<NSNumber>()
7897 .map(objc2_foundation::NSNumber::as_u64)
7898 }
7899
7900 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
7903 ffi_guard::contain((), || {
7904 if self.ivars().suppress.get() {
7905 return;
7906 }
7907 let token = unsafe { notification.userInfo() }
7908 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
7909 .and_then(|item| Self::token_of_item(&item));
7910 if let Some(token) = token {
7911 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
7912 }
7913 });
7914 }
7915
7916 fn drop_proposal(
7920 ov: &objc2_app_kit::NSOutlineView,
7921 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7922 item: Option<&objc2::runtime::AnyObject>,
7923 child_index: isize,
7924 ) -> Option<(u64, Option<u64>, Option<usize>)> {
7925 let src = unsafe { info.draggingSource() }?;
7926 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
7927 != std::ptr::from_ref::<objc2_app_kit::NSOutlineView>(ov).cast::<std::ffi::c_void>()
7928 {
7929 return None;
7930 }
7931 let pb = unsafe { info.draggingPasteboard() };
7932 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
7933 .to_string()
7934 .parse::<u64>()
7935 .ok()?;
7936 let parent = match item {
7937 Some(i) => Some(Self::token_of_item(i)?), None => None,
7939 };
7940 let index = (child_index >= 0).then_some(child_index as usize);
7941 Some((token, parent, index))
7942 }
7943
7944 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
7946 self.ivars()
7947 .source
7948 .borrow()
7949 .as_ref()
7950 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
7951 .is_some_and(|v| v == MoveVerdict::Allow)
7952 }
7953}
7954
7955define_class!(
7961 #[unsafe(super(objc2_app_kit::NSOutlineView))]
7962 #[thread_kind = MainThreadOnly]
7963 #[name = "DayOutlineView"]
7964 struct DayOutlineView;
7965
7966 impl DayOutlineView {
7967 #[unsafe(method(layout))]
7968 fn layout(&self) {
7969 sync_tree_width(self);
7970 let _: () = unsafe { msg_send![super(self), layout] };
7971 }
7972
7973 #[unsafe(method_id(menuForEvent:))]
7976 fn menu_for_event(
7977 &self,
7978 event: &objc2_app_kit::NSEvent,
7979 ) -> Option<Retained<NSMenu>> {
7980 ffi_guard::contain(None, || {
7981 let scroll = unsafe { self.enclosingScrollView() }?;
7982 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
7983 let row_menu = data
7984 .ivars()
7985 .source
7986 .borrow()
7987 .as_ref()
7988 .and_then(|s| s.row_menu.clone())?;
7989 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
7990 let row = unsafe { self.rowAtPoint(p) };
7991 if row < 0 {
7992 return None;
7993 }
7994 let token =
7995 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
7996 let items = row_menu(token);
7997 if items.is_empty() {
7998 return None;
7999 }
8000 Some(build_ns_menu(self.mtm(), "", &items))
8001 })
8002 }
8003 }
8004);
8005
8006define_class!(
8013 #[unsafe(super(objc2_app_kit::NSTableRowView))]
8014 #[thread_kind = MainThreadOnly]
8015 #[name = "DayTreeRowView"]
8016 struct DayTreeRowView;
8017
8018 impl DayTreeRowView {
8019 #[unsafe(method(drawSelectionInRect:))]
8020 fn draw_selection_in_rect(&self, _dirty: NSRect) {
8021 if !unsafe { self.isSelected() } {
8022 return;
8023 }
8024 let color = if unsafe { self.isEmphasized() } {
8025 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
8026 } else {
8027 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
8028 };
8029 let b = self.bounds();
8030 let pill = NSRect::new(
8031 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
8032 NSSize::new(
8033 (b.size.width - 10.0).max(0.0),
8034 (b.size.height - 2.0).max(0.0),
8035 ),
8036 );
8037 unsafe {
8038 color.setFill();
8039 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
8040 pill, 5.0, 5.0,
8041 )
8042 .fill();
8043 }
8044 }
8045 }
8046);
8047
8048define_class!(
8052 #[unsafe(super(objc2_app_kit::NSTableCellView))]
8053 #[thread_kind = MainThreadOnly]
8054 #[name = "DayTreeCell"]
8055 struct DayTreeCell;
8056
8057 impl DayTreeCell {
8058 #[unsafe(method(isFlipped))]
8059 fn is_flipped(&self) -> bool {
8060 true
8061 }
8062
8063 #[unsafe(method(layout))]
8064 fn layout(&self) {
8065 let _: () = unsafe { msg_send![super(self), layout] };
8066 ffi_guard::contain((), || {
8067 let width = self.bounds().size.width;
8068 if width <= 0.0 {
8069 return;
8070 }
8071 let mut cur = unsafe { self.superview() };
8075 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
8076 while let Some(v) = cur {
8077 cur = unsafe { v.superview() };
8078 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
8079 outline = Some(ov);
8080 break;
8081 }
8082 }
8083 let Some(ov) = outline else { return };
8084 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
8085 return;
8086 };
8087 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
8088 .and_then(|(_, data)| {
8089 data.ivars()
8090 .source
8091 .borrow()
8092 .as_ref()
8093 .map(|s| s.layout_cell_size.clone())
8094 });
8095 if let Some(f) = f {
8096 f(std::ptr::from_ref::<Self>(self) as RawHandle, Size::new(width, self.bounds().size.height));
8097 }
8098 });
8099 }
8100 }
8101);
8102
8103impl DayTreeCell {
8104 fn new(mtm: MainThreadMarker) -> Retained<Self> {
8105 unsafe { msg_send![Self::alloc(mtm), init] }
8106 }
8107}
8108
8109const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
8111
8112type TreeEntry = (
8114 Retained<objc2_app_kit::NSOutlineView>,
8115 Retained<DayTreeData>,
8116);
8117
8118fn tree_entry(key: usize) -> Option<TreeEntry> {
8121 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
8122}
8123
8124fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
8128 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
8129 return;
8130 };
8131 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
8132 let f = outline.frame();
8133 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
8134 unsafe {
8135 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
8136 outline.sizeLastColumnToFit();
8137 }
8138 }
8139}
8140
8141fn post_realize_visible_tree_rows(key: usize) {
8144 <AppKit as Platform>::post(Box::new(move || {
8145 if let Some((outline, _)) = tree_entry(key) {
8146 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
8147 for row in range.location..range.location + range.length {
8148 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
8149 }
8150 }
8151 day_core::pump_events();
8152 }));
8153}
8154
8155type NavMenuEntry = (
8157 Retained<objc2_app_kit::NSOutlineView>,
8158 Retained<DayNavMenuData>,
8159);
8160
8161fn ns_rect(r: day_spec::Rect) -> NSRect {
8162 NSRect::new(
8163 NSPoint::new(r.origin.x, r.origin.y),
8164 NSSize::new(r.size.width, r.size.height),
8165 )
8166}
8167
8168fn draw_op(op: &DrawOp, replay: &mut Replay) {
8169 unsafe {
8170 match op {
8171 DrawOp::Stamp(st) => {
8177 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
8178 for p in &st.at {
8179 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
8180 unsafe { batch.appendBezierPath(©) };
8181 }
8182 }
8183 let day_spec::Paint::Solid(color) = &st.paint else {
8184 let Some(bounds) = stamp_bounds(st) else {
8187 return;
8188 };
8189 draw_grouped(replay, || {
8190 match &st.stroke {
8191 None => unsafe { batch.addClip() },
8192 Some(style) => clip_to_stroke(&batch, style),
8193 }
8194 draw_gradient_in(&st.paint, bounds);
8195 });
8196 return;
8197 };
8198 match &st.stroke {
8199 None => {
8200 nscolor((*color).resolved()).setFill();
8201 unsafe { batch.fill() };
8202 }
8203 Some(style) => {
8204 nscolor((*color).resolved()).setStroke();
8205 apply_stroke_style(&batch, style);
8206 unsafe { batch.stroke() };
8207 }
8208 }
8209 }
8210 DrawOp::Fill(shape, paint) => match paint {
8211 day_spec::Paint::Solid(color) => {
8212 nscolor((*color).resolved()).setFill();
8213 if let Some(p) = bezier(shape) {
8214 p.fill();
8215 }
8216 }
8217 gradient => {
8220 if let Some(p) = bezier(shape) {
8221 draw_grouped(replay, || {
8222 p.addClip();
8223 draw_gradient_in(gradient, shape.bounds());
8224 });
8225 }
8226 }
8227 },
8228 DrawOp::Stroke(shape, paint, style) => {
8229 if let Some(p) = bezier(shape) {
8230 apply_stroke_style(&p, style);
8231 if let day_spec::Paint::Solid(color) = paint {
8232 nscolor((*color).resolved()).setStroke();
8233 p.stroke();
8234 } else {
8235 draw_grouped(replay, || {
8238 clip_to_stroke(&p, style);
8239 draw_gradient_in(paint, shape.bounds());
8240 });
8241 }
8242 }
8243 }
8244 DrawOp::Clip(shape) => {
8245 if let Some(p) = bezier(shape) {
8247 p.addClip();
8248 }
8249 }
8250 DrawOp::Text {
8251 text,
8252 at,
8253 size,
8254 color,
8255 anchor,
8256 font,
8257 } => {
8258 let font = canvas_nsfont(*size, font);
8259 let attrs = canvas_text_attrs(&font, *color);
8260 let ns = NSString::from_str(text);
8261 let mut origin = NSPoint::new(at.x, at.y);
8262 if *anchor != day_spec::TextAnchor::LEADING {
8267 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
8268 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
8269 origin.x += dx;
8270 origin.y += dy;
8271 }
8272 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
8273 }
8274 DrawOp::Image {
8278 image,
8279 rect,
8280 opacity,
8281 source,
8282 } => {
8283 let held = BITMAPS.with(|m| {
8284 m.borrow()
8285 .get(&image.0)
8286 .map(|b| (b.image.clone(), b.info.pixels))
8287 });
8288 if let Some((img, pixels)) = held {
8289 let region = match source {
8295 None => Some((NSRect::ZERO, *rect)),
8296 Some(src) => {
8297 day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
8298 let sz = img.size();
8299 let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
8300 let from = NSRect::new(
8301 NSPoint::new(
8302 src.origin.x * rx,
8303 (pixels.height - src.origin.y - src.size.height) * ry,
8304 ),
8305 NSSize::new(src.size.width * rx, src.size.height * ry),
8306 );
8307 (from, dest)
8308 })
8309 }
8310 };
8311 if let Some((from, dest)) = region {
8312 let dest = NSRect::new(
8313 NSPoint::new(dest.origin.x, dest.origin.y),
8314 NSSize::new(dest.size.width, dest.size.height),
8315 );
8316 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
8320 dest,
8321 from,
8322 ns_compositing(replay.ink.blend),
8323 *opacity,
8324 true,
8325 None,
8326 );
8327 }
8328 }
8329 }
8330 DrawOp::Shadow(shadow) => {
8333 let shadow = shadow.as_ref().filter(|s| s.color.resolved().a > 0.0);
8334 replay.ink.shadow = shadow.is_some();
8335 if let Some(ctx) = NSGraphicsContext::currentContext() {
8336 cg_set_shadow(&ctx.CGContext(), shadow, replay.base_scale);
8337 }
8338 }
8339 DrawOp::Blend(mode) => {
8340 replay.ink.blend = *mode;
8341 if let Some(ctx) = NSGraphicsContext::currentContext() {
8342 objc2_core_graphics::CGContext::set_blend_mode(
8343 Some(&ctx.CGContext()),
8344 cg_blend_mode(*mode),
8345 );
8346 }
8347 }
8348 DrawOp::Save => {
8349 replay.save();
8350 NSGraphicsContext::saveGraphicsState_class();
8351 }
8352 DrawOp::Restore => {
8353 if replay.restore() {
8354 NSGraphicsContext::restoreGraphicsState_class();
8355 }
8356 }
8357 DrawOp::Concat(m) => {
8358 let t = NSAffineTransform::new();
8359 t.setTransformStruct(NSAffineTransformStruct {
8360 m11: m.a,
8361 m12: m.b,
8362 m21: m.c,
8363 m22: m.d,
8364 tX: m.tx,
8365 tY: m.ty,
8366 });
8367 t.concat();
8368 }
8369 }
8370 }
8371}
8372
8373fn clip_to_stroke(path: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
8377 use objc2_core_graphics::CGContext;
8378 let Some(ctx) = (unsafe { NSGraphicsContext::currentContext() }) else {
8380 return;
8381 };
8382 let cg = ctx.CGContext();
8383 cg_stroke_style(&cg, style);
8384 CGContext::begin_path(Some(&cg));
8385 CGContext::add_path(Some(&cg), Some(&*unsafe { path.CGPath() }));
8387 CGContext::replace_path_with_stroked_path(Some(&cg));
8388 CGContext::clip(Some(&cg));
8389}
8390
8391fn stamp_bounds(stamp: &day_spec::Stamp) -> Option<day_spec::Rect> {
8394 let (first, rest) = stamp.at.split_first()?;
8395 let (mut min, mut max) = (*first, *first);
8396 for p in rest {
8397 min = Point::new(min.x.min(p.x), min.y.min(p.y));
8398 max = Point::new(max.x.max(p.x), max.y.max(p.y));
8399 }
8400 let b = stamp.shape.bounds();
8401 Some(day_spec::Rect::new(
8402 b.origin.x + min.x,
8403 b.origin.y + min.y,
8404 b.size.width + (max.x - min.x),
8405 b.size.height + (max.y - min.y),
8406 ))
8407}
8408
8409fn nsgradient(
8411 stops: &[(f64, day_spec::Color)],
8412) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
8413 if stops.is_empty() {
8414 return None;
8415 }
8416 let colors = objc2_foundation::NSArray::from_retained_slice(
8417 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
8418 );
8419 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
8420 unsafe {
8421 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
8422 objc2_app_kit::NSGradient::alloc(),
8423 &colors,
8424 locations.as_ptr(),
8425 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
8426 )
8427 }
8428}
8429
8430fn concat_unit_to_bounds(b: day_spec::Rect) {
8433 let t = NSAffineTransform::new();
8434 t.setTransformStruct(NSAffineTransformStruct {
8435 m11: b.size.width,
8436 m12: 0.0,
8437 m21: 0.0,
8438 m22: b.size.height,
8439 tX: b.origin.x,
8440 tY: b.origin.y,
8441 });
8442 unsafe { t.concat() };
8443}
8444
8445fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
8451 use day_spec::{LineCap, LineJoin};
8452 unsafe {
8453 p.setLineWidth(style.width);
8454 p.setLineCapStyle(match style.cap {
8455 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
8456 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
8457 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
8458 });
8459 if style.is_plain() {
8460 return;
8461 }
8462 p.setLineJoinStyle(match style.join {
8463 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
8464 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
8465 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
8466 });
8467 p.setMiterLimit(style.miter_limit);
8468 if !style.dash.is_empty() {
8469 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
8470 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
8471 }
8472 }
8473}
8474
8475fn stops_now(stops: &[(f64, day_spec::Ink)]) -> Vec<(f64, day_spec::Color)> {
8478 stops
8479 .iter()
8480 .map(|(at, ink)| (*at, color::ink_now(*ink)))
8481 .collect()
8482}
8483
8484fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
8488 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
8489 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
8490 match paint {
8491 day_spec::Paint::Linear(g) => {
8492 if let Some(grad) = nsgradient(&stops_now(&g.stops)) {
8493 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
8494 unsafe {
8495 grad.drawFromPoint_toPoint_options(
8496 NSPoint::new(s.x, s.y),
8497 NSPoint::new(e.x, e.y),
8498 opts,
8499 );
8500 };
8501 }
8502 }
8503 day_spec::Paint::Radial(g) => {
8504 if let Some(grad) = nsgradient(&stops_now(&g.stops)) {
8505 NSGraphicsContext::saveGraphicsState_class();
8506 concat_unit_to_bounds(bounds);
8507 let c = NSPoint::new(g.center.x, g.center.y);
8508 unsafe {
8509 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts);
8510 };
8511 NSGraphicsContext::restoreGraphicsState_class();
8512 }
8513 }
8514 day_spec::Paint::Conic(g) => {
8515 if let Some(ctx) = unsafe { NSGraphicsContext::currentContext() } {
8517 draw_conic(&ctx.CGContext(), g, bounds);
8518 }
8519 }
8520 day_spec::Paint::Solid(_) => {}
8521 }
8522}
8523
8524fn apply_button_content(
8525 btn: &NSButton,
8526 title: &str,
8527 icon: Option<&day_spec::Icon>,
8528 icon_only: bool,
8529) {
8530 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
8531 if let Some(image) = &image {
8532 let size = image.size();
8533 let longest = size.width.max(size.height);
8534 if longest > 0.0 {
8535 image.setSize(objc2_foundation::NSSize::new(
8536 size.width * 20.0 / longest,
8537 size.height * 20.0 / longest,
8538 ));
8539 }
8540 }
8541 let style = BUTTON_STYLES
8542 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
8543 .unwrap_or_default();
8544 BUTTON_IMAGES.with(|images| {
8545 let _ = images.remove(ptr_of(btn));
8546 if let Some(image) = &image {
8547 images.insert(ptr_of(btn), image.clone());
8548 }
8549 });
8550 set_button_title(btn, title, style);
8551 unsafe {
8554 btn.setImagePosition(if image.is_none() {
8555 objc2_app_kit::NSCellImagePosition::NoImage
8556 } else if icon_only {
8557 objc2_app_kit::NSCellImagePosition::ImageOnly
8558 } else {
8559 objc2_app_kit::NSCellImagePosition::ImageLeading
8560 });
8561 }
8562 set_button_image(btn, style);
8563 unsafe {
8564 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
8567 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
8568 }
8569 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
8570 btn.setToolTip(tooltip.as_deref());
8571 }
8572}
8573
8574fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
8578 use day_spec::props::ButtonStyleSpec as S;
8579 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
8580 let image = image.map(|source| {
8581 let S::Tinted(fill) = style else {
8582 return source;
8583 };
8584 let size = source.size();
8585 let ink = color::nsink(color::map_ink(fill, S::on_tint));
8587 let draw = block2::RcBlock::new(move |rect: NSRect| {
8588 source.drawInRect_fromRect_operation_fraction(
8589 rect,
8590 NSRect::ZERO,
8591 objc2_app_kit::NSCompositingOperation::SourceOver,
8592 1.0,
8593 );
8594 unsafe {
8595 ink.setFill();
8596 objc2_app_kit::NSRectFillUsingOperation(
8597 rect,
8598 objc2_app_kit::NSCompositingOperation::SourceIn,
8599 );
8600 }
8601 objc2::runtime::Bool::YES
8602 });
8603 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
8604 });
8605 unsafe {
8606 let position = btn.imagePosition();
8607 let image = image.map(|source| {
8612 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
8615 return source;
8616 }
8617 let size = source.size();
8618 let template = source.isTemplate();
8619 let padded = NSSize::new(size.width + 8.0, size.height);
8620 let draw = block2::RcBlock::new(move |_rect: NSRect| {
8621 source.drawInRect_fromRect_operation_fraction(
8622 NSRect::new(NSPoint::new(0.0, 0.0), size),
8623 NSRect::ZERO,
8624 objc2_app_kit::NSCompositingOperation::SourceOver,
8625 1.0,
8626 );
8627 objc2::runtime::Bool::YES
8628 });
8629 let out =
8630 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
8631 out.setTemplate(template);
8632 out
8633 });
8634 btn.setImage(image.as_deref());
8635 btn.setImagePosition(position);
8636 btn.setImageHugsTitle(true);
8637 }
8638}
8639
8640fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
8646 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
8647 unsafe {
8648 if on {
8649 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
8650 }
8651 btn.setState(if on {
8652 NSControlStateValueOn
8653 } else {
8654 NSControlStateValueOff
8655 });
8656 }
8657}
8658
8659const TINT_CORNER_RADIUS: f64 = 6.0;
8662
8663fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
8673 use day_spec::props::ButtonStyleSpec as S;
8674 let title = unsafe { btn.title() }.to_string();
8675 unsafe {
8676 btn.setKeyEquivalent(&NSString::from_str(""));
8678 btn.setBezelColor(None);
8679 btn.setBordered(!matches!(style, S::Plain));
8680 match style {
8681 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
8682 S::Tinted(c) => btn.setBezelColor(Some(&color::nsink(c))),
8683 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
8686 }
8687 btn.setWantsLayer(true);
8688 if let Some(layer) = btn.layer() {
8689 match style {
8690 S::Tinted(c) => {
8691 layer.setBackgroundColor(Some(&color::cg_for(btn, c)));
8694 layer.setCornerRadius(TINT_CORNER_RADIUS);
8695 if c.is_dynamic() {
8696 color::track_tinted(btn);
8697 }
8698 }
8699 _ => layer.setBackgroundColor(None),
8700 }
8701 }
8702 }
8703 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
8704 let ink = match style {
8705 S::Tinted(c) => Some(color::nsink(color::map_ink(c, S::on_tint))),
8706 _ => None,
8707 };
8708 unsafe {
8709 btn.setContentTintColor(ink.as_deref());
8710 }
8711 set_button_title(btn, &title, style);
8712 set_button_image(btn, style);
8713}
8714
8715fn set_button_title(
8725 btn: &objc2_app_kit::NSButton,
8726 title: &str,
8727 style: day_spec::props::ButtonStyleSpec,
8728) {
8729 use day_spec::props::ButtonStyleSpec as S;
8730 let position = unsafe { btn.imagePosition() };
8733 let S::Tinted(fill) = style else {
8734 unsafe {
8736 btn.setTitle(&NSString::from_str(title));
8737 btn.setImagePosition(position);
8738 }
8739 return;
8740 };
8741 unsafe {
8742 let col = color::nsink(color::map_ink(fill, S::on_tint));
8743 let font = btn
8744 .font()
8745 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
8746 let para = objc2_app_kit::NSMutableParagraphStyle::new();
8749 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
8750 let keys: [&NSString; 3] = [
8751 objc2_app_kit::NSFontAttributeName,
8752 objc2_app_kit::NSForegroundColorAttributeName,
8753 objc2_app_kit::NSParagraphStyleAttributeName,
8754 ];
8755 let objs: [&objc2::runtime::AnyObject; 3] = [
8756 font.as_ref() as &objc2::runtime::AnyObject,
8757 col.as_ref() as &objc2::runtime::AnyObject,
8758 para.as_ref() as &objc2::runtime::AnyObject,
8759 ];
8760 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
8761 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
8762 objc2_foundation::NSAttributedString::alloc(),
8763 &NSString::from_str(title),
8764 Some(&attrs),
8765 );
8766 btn.setAttributedTitle(&s);
8767 btn.setImagePosition(position);
8768 }
8769}
8770
8771define_class!(
8774 #[unsafe(super(objc2_app_kit::NSImageView))]
8775 #[thread_kind = MainThreadOnly]
8776 #[name = "DayFillImageView"]
8777 struct FillImageView;
8778
8779 impl FillImageView {
8780 #[unsafe(method(drawRect:))]
8781 fn draw_rect(&self, dirty: NSRect) {
8782 let bounds = self.bounds();
8783 let image = unsafe { self.image() };
8784 let Some(size) = image.map(|image| image.size()).filter(|size| {
8785 size.width > 0.0 && size.height > 0.0
8786 && bounds.size.width > 0.0 && bounds.size.height > 0.0
8787 }) else {
8788 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
8789 return;
8790 };
8791 let x = bounds.size.width / size.width;
8792 let y = bounds.size.height / size.height;
8793 let scale = x.max(y) / x.min(y);
8794 let cx = bounds.origin.x + bounds.size.width / 2.0;
8795 let cy = bounds.origin.y + bounds.size.height / 2.0;
8796 NSGraphicsContext::saveGraphicsState_class();
8797 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
8798 let transform = NSAffineTransform::transform();
8799 transform.translateXBy_yBy(cx, cy);
8800 transform.scaleBy(scale);
8801 transform.translateXBy_yBy(-cx, -cy);
8802 transform.concat();
8803 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
8804 NSGraphicsContext::restoreGraphicsState_class();
8805 }
8806
8807 #[unsafe(method(setFrameSize:))]
8808 fn set_frame_size(&self, size: NSSize) {
8809 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
8810 NSView::setNeedsDisplay(self, true);
8811 }
8812 }
8813);
8814
8815fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
8816 use day_spec::Shape;
8817 use objc2_app_kit::NSBezierPath;
8818 unsafe {
8819 Some(match shape {
8820 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
8821 Shape::RoundedRect(r, rad) => {
8822 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
8823 }
8824 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
8825 Shape::Arc { rect, start, sweep } => {
8826 let (start_deg, sweep_deg) = (&start.degrees(), &sweep.degrees());
8827 let p = NSBezierPath::new();
8828 let center = NSPoint::new(
8829 rect.origin.x + rect.size.width / 2.0,
8830 rect.origin.y + rect.size.height / 2.0,
8831 );
8832 let radius = rect.size.width.min(rect.size.height) / 2.0;
8833 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
8835 center,
8836 radius,
8837 *start_deg,
8838 *start_deg + *sweep_deg,
8839 );
8840 p
8841 }
8842 Shape::Line(a, b) => {
8843 let p = NSBezierPath::new();
8844 p.moveToPoint(NSPoint::new(a.x, a.y));
8845 p.lineToPoint(NSPoint::new(b.x, b.y));
8846 p
8847 }
8848 Shape::Polygon(pts) => {
8849 if pts.len() < 2 {
8850 return None;
8851 }
8852 let p = NSBezierPath::new();
8853 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
8854 for pt in &pts[1..] {
8855 p.lineToPoint(NSPoint::new(pt.x, pt.y));
8856 }
8857 p.closePath();
8858 p
8859 }
8860 Shape::Path(path) => {
8861 use day_spec::PathSeg;
8862 if path.segs.is_empty() {
8863 return None;
8864 }
8865 let p = NSBezierPath::new();
8866 let mut cur = NSPoint::new(0.0, 0.0);
8870 for seg in &path.segs {
8871 match seg {
8872 PathSeg::Move(a) => {
8873 cur = NSPoint::new(a.x, a.y);
8874 p.moveToPoint(cur);
8875 }
8876 PathSeg::Line(a) => {
8877 cur = NSPoint::new(a.x, a.y);
8878 p.lineToPoint(cur);
8879 }
8880 PathSeg::Quad(c, a) => {
8881 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
8882 let c1 = NSPoint::new(
8883 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
8884 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
8885 );
8886 let c2 = NSPoint::new(
8887 end.x + 2.0 / 3.0 * (ctl.x - end.x),
8888 end.y + 2.0 / 3.0 * (ctl.y - end.y),
8889 );
8890 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
8891 cur = end;
8892 }
8893 PathSeg::Cubic(c1, c2, a) => {
8894 cur = NSPoint::new(a.x, a.y);
8895 p.curveToPoint_controlPoint1_controlPoint2(
8896 cur,
8897 NSPoint::new(c1.x, c1.y),
8898 NSPoint::new(c2.x, c2.y),
8899 );
8900 }
8901 PathSeg::Close => p.closePath(),
8902 }
8903 }
8904 p.setWindingRule(match path.rule {
8905 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
8906 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
8907 });
8908 p
8909 }
8910 })
8911 }
8912}
8913
8914struct UndoIvars {
8922 state: std::cell::RefCell<day_spec::UndoState>,
8923}
8924
8925define_class!(
8926 #[unsafe(super(objc2_foundation::NSUndoManager))]
8927 #[thread_kind = MainThreadOnly]
8928 #[name = "DayUndoManager"]
8929 #[ivars = UndoIvars]
8930 struct DayUndoManager;
8931
8932 impl DayUndoManager {
8936 #[unsafe(method(canUndo))]
8937 fn can_undo(&self) -> bool {
8938 self.ivars().state.borrow().can_undo
8939 }
8940
8941 #[unsafe(method(canRedo))]
8942 fn can_redo(&self) -> bool {
8943 self.ivars().state.borrow().can_redo
8944 }
8945
8946 #[unsafe(method(undo))]
8947 fn do_undo(&self) {
8948 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }));
8949 }
8950
8951 #[unsafe(method(redo))]
8952 fn do_redo(&self) {
8953 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }));
8954 }
8955
8956 #[unsafe(method_id(undoMenuItemTitle))]
8957 fn undo_menu_item_title(&self) -> Retained<NSString> {
8958 let label = self.ivars().state.borrow().undo_label.clone();
8961 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8962 }
8963
8964 #[unsafe(method_id(redoMenuItemTitle))]
8965 fn redo_menu_item_title(&self) -> Retained<NSString> {
8966 let label = self.ivars().state.borrow().redo_label.clone();
8967 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8968 }
8969 }
8970);
8971
8972fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
8973 UNDO_FRONT.with(|u| {
8974 u.borrow_mut()
8975 .get_or_insert_with(|| {
8976 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
8977 state: std::cell::RefCell::new(day_spec::UndoState::default()),
8978 });
8979 unsafe { msg_send![super(this), init] }
8980 })
8981 .clone()
8982 })
8983}
8984
8985struct WinIvars {
8993 node: Option<NodeId>,
8994 group: Option<String>,
8997 last_state: Cell<i32>,
9000}
9001
9002define_class!(
9003 #[unsafe(super(NSObject))]
9004 #[thread_kind = MainThreadOnly]
9005 #[name = "DayWinDelegate"]
9006 #[ivars = WinIvars]
9007 struct DayWinDelegate;
9008
9009 unsafe impl NSObjectProtocol for DayWinDelegate {}
9010
9011 impl DayWinDelegate {
9015 #[unsafe(method(undo:))]
9019 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9020 ffi_guard::contain((), || {
9021 if let Some(m) = self.acting_undo_manager() {
9022 unsafe { m.undo() };
9023 }
9024 });
9025 }
9026
9027 #[unsafe(method(redo:))]
9029 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9030 ffi_guard::contain((), || {
9031 if let Some(m) = self.acting_undo_manager() {
9032 unsafe { m.redo() };
9033 }
9034 });
9035 }
9036
9037 #[unsafe(method(cut:))]
9038 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9039 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
9040 }
9041
9042 #[unsafe(method(copy:))]
9043 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9044 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
9045 }
9046
9047 #[unsafe(method(paste:))]
9048 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9049 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
9050 }
9051
9052 #[unsafe(method(selectAll:))]
9053 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9054 ffi_guard::contain((), || {
9055 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
9056 });
9057 }
9058
9059 #[unsafe(method(validateMenuItem:))]
9063 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
9064 ffi_guard::contain(false, || {
9065 let state = EDIT_STATE.with(std::cell::Cell::get);
9066 match unsafe { item.action() } {
9067 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
9070 Some(m) => {
9071 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
9072 unsafe { m.canUndo() }
9073 }
9074 None => false,
9075 },
9076 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
9077 Some(m) => {
9078 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
9079 unsafe { m.canRedo() }
9080 }
9081 None => false,
9082 },
9083 Some(a) if a == sel!(selectAll:) => state.can_select_all,
9084 Some(a) if a == sel!(cut:) => state.can_cut,
9085 Some(a) if a == sel!(copy:) => state.can_copy,
9086 Some(a) if a == sel!(paste:) => {
9087 state.can_paste && {
9088 let pb = unsafe { NSPasteboard::generalPasteboard() };
9089 pb.types().is_some_and(|types| !types.is_empty())
9090 }
9091 }
9092 _ => true,
9093 }
9094 })
9095 }
9096 }
9097
9098 unsafe impl NSWindowDelegate for DayWinDelegate {
9099 #[unsafe(method(windowDidResize:))]
9100 fn window_did_resize(&self, notification: &NSNotification) {
9101 ffi_guard::contain((), || {
9102 if let Some(obj) = unsafe { notification.object() }
9103 && let Ok(win) = obj.downcast::<NSWindow>()
9104 && let Some(size) = pin_below_title_bar(&win)
9105 {
9106 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
9107 emit(target, Event::WindowResized(size));
9108 }
9109 self.report_state_of(notification);
9111 });
9112 }
9113
9114 #[unsafe(method(windowShouldClose:))]
9115 fn window_should_close(&self, _window: &NSWindow) -> bool {
9116 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
9117 }
9118
9119 #[unsafe(method(windowWillClose:))]
9120 fn window_will_close(&self, _notification: &NSNotification) {
9121 ffi_guard::contain((), || {
9122 match self.ivars().node {
9123 Some(node) => emit(node, Event::WindowClosed),
9126 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
9131 None => {
9132 let app = NSApplication::sharedApplication(self.mtm());
9133 unsafe { app.terminate(None) };
9134 }
9135 }
9136 });
9137 }
9138
9139 #[unsafe(method_id(windowWillReturnUndoManager:))]
9140 fn window_will_return_undo_manager(
9141 &self,
9142 _window: &NSWindow,
9143 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
9144 ffi_guard::contain(None, || {
9148 UNDO_FRONT.with(|u| {
9149 u.borrow()
9150 .as_ref()
9151 .map(|m| Retained::into_super(m.clone()))
9152 })
9153 })
9154 }
9155
9156 #[unsafe(method(windowDidBecomeKey:))]
9157 fn window_did_become_key(&self, _notification: &NSNotification) {
9158 ffi_guard::contain((), || {
9159 if let Some(node) = self.ivars().node {
9160 emit(node, Event::WindowFocused(true));
9161 }
9162 });
9163 }
9164
9165 #[unsafe(method(windowDidResignKey:))]
9166 fn window_did_resign_key(&self, _notification: &NSNotification) {
9167 ffi_guard::contain((), || {
9168 if let Some(node) = self.ivars().node {
9169 emit(node, Event::WindowFocused(false));
9170 }
9171 });
9172 }
9173
9174 #[unsafe(method(windowDidMiniaturize:))]
9175 fn window_did_miniaturize(&self, notification: &NSNotification) {
9176 ffi_guard::contain((), || self.report_state_of(notification));
9177 }
9178
9179 #[unsafe(method(windowDidDeminiaturize:))]
9180 fn window_did_deminiaturize(&self, notification: &NSNotification) {
9181 ffi_guard::contain((), || self.report_state_of(notification));
9182 }
9183
9184 #[unsafe(method(windowDidEnterFullScreen:))]
9185 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
9186 ffi_guard::contain((), || self.report_state_of(notification));
9187 }
9188
9189 #[unsafe(method(windowDidExitFullScreen:))]
9190 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
9191 ffi_guard::contain((), || self.report_state_of(notification));
9192 }
9193 }
9194
9195 impl DayWinDelegate {
9199 #[unsafe(method(newWindowForTab:))]
9200 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
9201 ffi_guard::contain((), || {
9202 let _ = match self.ivars().group.as_deref() {
9205 Some(group) => day_core::windows::open_new_window_for_group(group),
9206 None => day_core::windows::open_new_window(),
9207 };
9208 });
9209 }
9210 }
9211);
9212
9213impl DayWinDelegate {
9214 fn report_state_of(&self, notification: &NSNotification) {
9215 if let Some(obj) = unsafe { notification.object() }
9216 && let Ok(win) = obj.downcast::<NSWindow>()
9217 {
9218 self.report_state(&win);
9219 }
9220 }
9221}
9222
9223fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
9226 match unsafe { event.keyCode() } {
9227 123 => Some("ArrowLeft"),
9228 124 => Some("ArrowRight"),
9229 125 => Some("ArrowDown"),
9230 126 => Some("ArrowUp"),
9231 _ => {
9239 let held = NSEventModifierFlags::Command
9240 | NSEventModifierFlags::Option
9241 | NSEventModifierFlags::Control;
9242 if event.modifierFlags().intersects(held) {
9243 return None;
9244 }
9245 let typed = event.characters()?.to_string();
9246 let mut chars = typed.chars();
9247 match (chars.next(), chars.next()) {
9248 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
9249 _ => None,
9250 }
9251 }
9252 }
9253}
9254
9255fn short_route_key_down(node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
9261 let Some(key) = key_name(event) else {
9262 return false;
9263 };
9264 if !day_spec::keys::handled(node) {
9265 return false;
9266 }
9267 let mods = key_modifiers(event.modifierFlags());
9268 if event.isARepeat() {
9269 if !input::owns_repeat(event) {
9270 return false;
9271 }
9272 emit(
9273 node,
9274 Event::Key(day_spec::KeyEvent::named(key, mods).with_phase(day_spec::KeyPhase::Repeat)),
9275 );
9276 return true;
9277 }
9278 emit(node, Event::Key(day_spec::KeyEvent::named(key, mods)));
9279 input::claim_key(event, node, key.to_string());
9280 true
9281}
9282
9283fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
9286 Some(match unsafe { event.keyCode() } {
9287 123 => "ArrowLeft",
9288 124 => "ArrowRight",
9289 125 => "ArrowDown",
9290 126 => "ArrowUp",
9291 36 | 76 => "Enter",
9292 48 => "Tab",
9293 53 => "Escape",
9294 51 => "Backspace",
9295 117 => "Delete",
9296 115 => "Home",
9297 119 => "End",
9298 116 => "PageUp",
9299 121 => "PageDown",
9300 114 => "Insert",
9301 122 => "F1",
9302 120 => "F2",
9303 99 => "F3",
9304 118 => "F4",
9305 96 => "F5",
9306 97 => "F6",
9307 98 => "F7",
9308 100 => "F8",
9309 101 => "F9",
9310 109 => "F10",
9311 103 => "F11",
9312 111 => "F12",
9313 _ => return None,
9314 })
9315}
9316
9317fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
9333 let ptr = std::ptr::from_ref::<DayCanvas>(view).cast::<NSView>() as usize;
9334 let flags = event.modifierFlags();
9335 let mods = key_modifiers(flags);
9336 if flags.contains(NSEventModifierFlags::Command) {
9337 return false;
9338 }
9339 let composing = MARKED.with(|t| t.contains(ptr));
9340 let phase = if event.isARepeat() {
9341 if !composing && !input::owns_repeat(event) {
9342 return true;
9343 }
9344 day_spec::KeyPhase::Repeat
9345 } else {
9346 day_spec::KeyPhase::Down
9347 };
9348 let claim = |key: String| {
9351 if phase == day_spec::KeyPhase::Down {
9352 input::claim_key(event, node, key);
9353 }
9354 };
9355 if !composing && let Some(named) = named_key(event) {
9356 emit(
9357 node,
9358 Event::Key(day_spec::KeyEvent::named(named, mods).with_phase(phase)),
9359 );
9360 claim(named.to_string());
9361 return true;
9362 }
9363 let unmodified =
9364 unsafe { event.charactersIgnoringModifiers() }.map_or_default(|s| s.to_string());
9365 let typeable = !unmodified.is_empty()
9367 && !unmodified
9368 .chars()
9369 .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
9370 if !composing && flags.contains(NSEventModifierFlags::Control) {
9371 if typeable {
9372 emit(
9373 node,
9374 Event::Key(day_spec::KeyEvent::named(unmodified.clone(), mods).with_phase(phase)),
9375 );
9376 claim(unmodified);
9377 }
9378 return true;
9379 }
9380 if !composing && !typeable {
9381 return true;
9382 }
9383 INTERPRETING.with(|i| {
9384 *i.borrow_mut() = Some(Interpreting {
9385 key: unmodified,
9386 mods,
9387 phase,
9388 event: event.retain(),
9389 });
9390 });
9391 view.interpretKeyEvents(&NSArray::from_slice(&[event]));
9392 INTERPRETING.with(|i| *i.borrow_mut() = None);
9393 true
9394}
9395
9396struct Interpreting {
9400 key: String,
9401 mods: u8,
9402 phase: day_spec::KeyPhase,
9403 event: Retained<NSEvent>,
9404}
9405
9406fn text_of_input_string(string: &AnyObject) -> String {
9408 if let Some(s) = string.downcast_ref::<NSString>() {
9409 s.to_string()
9410 } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
9411 s.string().to_string()
9412 } else {
9413 String::new()
9414 }
9415}
9416
9417fn key_modifiers(f: NSEventModifierFlags) -> u8 {
9419 let mut modifiers = 0u8;
9420 if f.contains(NSEventModifierFlags::Shift) {
9421 modifiers |= day_spec::Modifiers::SHIFT.bits();
9422 }
9423 if f.contains(NSEventModifierFlags::Command) {
9424 modifiers |= day_spec::Modifiers::PRIMARY.bits();
9425 }
9426 if f.contains(NSEventModifierFlags::Option) {
9427 modifiers |= day_spec::Modifiers::ALT.bits();
9428 }
9429 if f.contains(NSEventModifierFlags::Control) {
9430 modifiers |= day_spec::Modifiers::CONTROL.bits();
9431 }
9432 modifiers
9433}
9434
9435impl DayWinDelegate {
9436 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
9441 let responder = NSApplication::sharedApplication(self.mtm())
9442 .keyWindow()
9443 .and_then(|w| w.firstResponder());
9444 responder
9445 .and_then(|r| unsafe { r.undoManager() })
9446 .or_else(|| {
9447 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
9448 })
9449 }
9450}
9451
9452impl DayWinDelegate {
9453 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
9454 let this = Self::alloc(mtm).set_ivars(WinIvars {
9455 node,
9456 group,
9457 last_state: Cell::new(day_spec::WindowState::Normal.code()),
9458 });
9459 unsafe { msg_send![super(this), init] }
9460 }
9461
9462 fn report_state(&self, window: &NSWindow) {
9466 let state = ns_window_state(window);
9467 if self.ivars().last_state.replace(state.code()) != state.code() {
9468 log::debug!("appkit: window state now {state:?}");
9469 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
9470 emit(target, Event::WindowStateChanged(state));
9471 }
9472 }
9473}
9474
9475fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
9478 if window.isMiniaturized() {
9479 day_spec::WindowState::Minimized
9480 } else if window
9481 .styleMask()
9482 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
9483 {
9484 day_spec::WindowState::Fullscreen
9485 } else if window.isZoomed() {
9486 day_spec::WindowState::Maximized
9487 } else {
9488 day_spec::WindowState::Normal
9489 }
9490}
9491
9492fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
9495 use day_spec::WindowState as S;
9496 let current = ns_window_state(window);
9497 if current == state {
9498 return;
9499 }
9500 unsafe {
9501 match current {
9502 S::Minimized => window.deminiaturize(None),
9503 S::Fullscreen => {
9507 window.toggleFullScreen(None);
9508 return;
9509 }
9510 S::Maximized if state != S::Minimized => window.zoom(None),
9511 _ => {}
9512 }
9513 match state {
9514 S::Normal => {}
9515 S::Minimized => window.miniaturize(None),
9516 S::Maximized => {
9517 if !window.isZoomed() {
9518 window.zoom(None);
9519 }
9520 }
9521 S::Fullscreen => window.toggleFullScreen(None),
9522 }
9523 }
9524}
9525
9526#[distributed_slice]
9532pub static RENDERERS: [fn() -> Renderer<AppKit>];
9533
9534struct SecondaryWin {
9538 window: Retained<NSWindow>,
9539 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
9541 content: Handle,
9542}
9543
9544struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
9547impl Drop for MenuEscapeMonitor {
9548 fn drop(&mut self) {
9549 unsafe { NSEvent::removeMonitor(&self.0) };
9550 }
9551}
9552
9553pub struct AppKit {
9554 menu_escape_monitor: Option<MenuEscapeMonitor>,
9555 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
9556 sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
9558
9559 mtm: MainThreadMarker,
9560 registry: Registry<AppKit>,
9561 window: Option<Retained<NSWindow>>,
9562 content: Option<Handle>,
9563 secondary: Vec<SecondaryWin>,
9564 app_name: String,
9565 cascade: Option<NSPoint>,
9570 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
9573}
9574
9575impl AppKit {
9576 fn swap_text_field(
9581 &mut self,
9582 h: &Handle,
9583 old: &NSTextField,
9584 node: NodeId,
9585 secure: bool,
9586 ) -> Retained<NSTextField> {
9587 let new = new_text_field(self.mtm, node, secure);
9588 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
9589 let window = h.window();
9592 let focused = window
9593 .as_deref()
9594 .is_some_and(|w| owns_first_responder(w, h));
9595 let selection = old.currentEditor().map(|e| e.selectedRange());
9596 unsafe {
9597 new.setStringValue(&old.stringValue());
9598 new.setPlaceholderString(old.placeholderString().as_deref());
9599 new.setEnabled(old.isEnabled());
9600 new.setFont(old.font().as_deref());
9601 new.setFrame(h.frame());
9602 new.setHidden(h.isHidden());
9603 new.setMenu(h.menu().as_deref());
9604 new.setToolTip(h.toolTip().as_deref());
9605 if h.wantsLayer() {
9607 new.setWantsLayer(true);
9608 new.setAlphaValue(h.alphaValue());
9609 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
9610 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
9611 if !from.is_null() && !to.is_null() {
9612 let t: CGAffineTransform = msg_send![from, affineTransform];
9613 let _: () = msg_send![to, setAffineTransform: t];
9614 }
9615 }
9616 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
9619 new.setAccessibilityIdentifier(Some(&id));
9620 }
9621 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
9622 new.setAccessibilityLabel(Some(&label));
9623 }
9624 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
9625 new.setAccessibilityHelp(Some(&help));
9626 }
9627 if !h.isAccessibilityElement() {
9628 new.setAccessibilityElement(false);
9629 }
9630 }
9631 for r in &unsafe { h.gestureRecognizers() } {
9633 unsafe {
9634 h.removeGestureRecognizer(&r);
9635 new.addGestureRecognizer(&r);
9636 }
9637 }
9638 GESTURES.with(|m| {
9639 let mut m = m.borrow_mut();
9640 if let Some(targets) = m.remove(&old_key) {
9641 m.insert(new_key, targets);
9642 }
9643 });
9644 if let Some((owner, area)) = self.cursors.remove(&old_key) {
9645 unsafe {
9646 h.removeTrackingArea(&area);
9647 new.addTrackingArea(&area);
9648 }
9649 self.cursors.insert(new_key, (owner, area));
9650 }
9651 PAN_NODES.with(|t| rekey(t, old_key, new_key));
9652 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
9653 ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
9654 ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
9655 KEY_NODES.with(|t| rekey(t, old_key, new_key));
9656 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
9657 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
9658 transfer::moved(h, &new);
9659 unsafe { old.setDelegate(None) };
9662 TARGETS.with(|m| {
9663 m.borrow_mut().remove(&old_key);
9664 });
9665 if let Some(parent) = unsafe { h.superview() } {
9666 unsafe {
9667 parent.addSubview_positioned_relativeTo(
9668 &new,
9669 objc2_app_kit::NSWindowOrderingMode::Above,
9670 Some(h),
9671 );
9672 h.removeFromSuperview();
9673 }
9674 }
9675 if focused && let Some(window) = window {
9676 FIELD_SWAP.with(|s| s.set(true));
9677 let taken = window.makeFirstResponder(Some(&new));
9678 FIELD_SWAP.with(|s| s.set(false));
9679 if taken && let Some(editor) = new.currentEditor() {
9682 let len = unsafe { new.stringValue() }.length();
9683 let range = selection
9684 .filter(|r| r.location.saturating_add(r.length) <= len)
9685 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
9686 editor.setSelectedRange(range);
9687 }
9688 }
9689 day_spec::sidetable::sweep(old_key);
9691 new
9692 }
9693
9694 #[must_use]
9700 pub fn new() -> Self {
9701 let mtm =
9702 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
9703 let mut registry = Registry::default();
9704 for f in RENDERERS {
9705 registry.register(f());
9706 }
9707 AppKit {
9708 menu_escape_monitor: None,
9709 mtm,
9710 registry,
9711 window: None,
9712 sharing: None,
9713 sharing_delegate: None,
9714 content: None,
9715 secondary: Vec::new(),
9716 app_name: "Day".into(),
9717 cascade: None,
9718 cursors: HashMap::new(),
9719 }
9720 }
9721
9722 #[must_use]
9724 pub fn mtm(&self) -> MainThreadMarker {
9725 self.mtm
9726 }
9727
9728 fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
9737 if content.window().is_none_or(|w| w.isVisible()) {
9738 return None;
9739 }
9740 let main = NSApplication::sharedApplication(self.mtm).mainWindow();
9741 let anchor = main
9742 .filter(|m| {
9743 self.secondary
9744 .iter()
9745 .any(|w| std::ptr::eq(&raw const *w.window, &raw const **m))
9746 })
9747 .or_else(|| {
9748 self.secondary
9749 .iter()
9750 .find(|w| w.window.isVisible())
9751 .map(|w| w.window.clone())
9752 })?;
9753 let shown = anchor
9754 .tabGroup()
9755 .and_then(|g| g.selectedWindow())
9756 .unwrap_or(anchor);
9757 self.secondary
9758 .iter()
9759 .find(|w| std::ptr::eq(&raw const *w.window, &raw const *shown) && w.window.isVisible())
9760 .map(|w| w.content.clone())
9761 }
9762
9763 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
9764 if let Some(w) = self
9765 .secondary
9766 .iter()
9767 .find(|w| ptr_of(&w.content) == ptr_of(host))
9768 {
9769 return Some(w.window.clone());
9770 }
9771 self.content
9772 .as_ref()
9773 .filter(|c| ptr_of(c) == ptr_of(host))
9774 .and(self.window.clone())
9775 }
9776
9777 fn make_window(
9783 &self,
9784 options: &WindowOptions,
9785 prefs_style: bool,
9786 node: Option<NodeId>,
9787 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
9788 use day_spec::WindowTabbing as T;
9789 use objc2_app_kit::NSWindowTabbingMode as M;
9790 let mtm = self.mtm;
9791 let (title, size, min_size, tabbing) = (
9792 options.title.as_str(),
9793 options.size,
9794 options.min_size,
9795 &options.tabbing,
9796 );
9797 let content_rect =
9798 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
9799 let style = window_chrome::style_mask(options, prefs_style);
9801 let window = window_chrome::alloc_window(
9802 mtm,
9803 content_rect,
9804 style,
9805 options.chrome == day_spec::WindowChrome::Frameless,
9806 );
9807 unsafe { window.setReleasedWhenClosed(false) };
9808 window.setTitle(&NSString::from_str(title));
9809 if let Some(min) = min_size {
9810 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
9811 }
9812 if let Some(max) = options.max_size {
9813 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
9814 }
9815 let group = match tabbing {
9816 T::Group(g) | T::Preferred(g) => Some(g.clone()),
9817 T::Automatic | T::Disallowed => None,
9818 };
9819 match tabbing {
9820 _ if prefs_style => window.setTabbingMode(M::Disallowed),
9821 T::Disallowed => window.setTabbingMode(M::Disallowed),
9822 T::Automatic => unsafe {
9826 window.setTabbingIdentifier(&NSString::from_str("day.normal"));
9827 },
9828 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
9829 T::Preferred(g) => {
9830 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
9831 window.setTabbingMode(M::Preferred);
9832 }
9833 }
9834 if group.is_some() {
9835 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
9838 }
9839 let delegate = DayWinDelegate::new(mtm, node, group);
9840 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
9841 let content = view_of(&DayFlipped::new(mtm));
9842 window.setContentView(Some(&content));
9843 window_chrome::apply(&window, &content, options);
9844 window.setAutorecalculatesKeyViewLoop(true);
9853 (window, delegate, content)
9854 }
9855}
9856
9857impl Default for AppKit {
9858 fn default() -> Self {
9859 Self::new()
9860 }
9861}
9862
9863fn view_of<T: AsRef<NSView>>(x: &Retained<T>) -> Handle {
9864 Retained::from((**x).as_ref())
9865}
9866
9867fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
9868 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
9869}
9870
9871fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
9874 use objc2_app_kit::*;
9875 unsafe {
9876 Some(match f {
9877 Font::LargeTitle => NSFontTextStyleLargeTitle,
9878 Font::Title => NSFontTextStyleTitle1,
9879 Font::Title2 => NSFontTextStyleTitle2,
9880 Font::Title3 => NSFontTextStyleTitle3,
9881 Font::Headline => NSFontTextStyleHeadline,
9882 Font::Subheadline => NSFontTextStyleSubheadline,
9883 Font::Body => NSFontTextStyleBody,
9884 Font::Callout => NSFontTextStyleCallout,
9885 Font::Footnote => NSFontTextStyleFootnote,
9886 Font::Caption => NSFontTextStyleCaption1,
9887 Font::Caption2 => NSFontTextStyleCaption2,
9888 Font::System(_) | Font::Custom(..) => return None,
9889 })
9890 }
9891}
9892
9893fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
9894 use day_spec::FontWeight as W;
9895 use objc2_app_kit::*;
9896 unsafe {
9897 match w {
9898 W::UltraLight => NSFontWeightUltraLight,
9899 W::Thin => NSFontWeightThin,
9900 W::Light => NSFontWeightLight,
9901 W::Regular => NSFontWeightRegular,
9902 W::Medium => NSFontWeightMedium,
9903 W::Semibold => NSFontWeightSemibold,
9904 W::Bold => NSFontWeightBold,
9905 W::Heavy => NSFontWeightHeavy,
9906 W::Black => NSFontWeightBlack,
9907 }
9908 }
9909}
9910
9911fn nsfm_weight(w: day_spec::FontWeight) -> isize {
9914 use day_spec::FontWeight as W;
9915 match w {
9916 W::UltraLight => 2,
9917 W::Thin => 3,
9918 W::Light => 4,
9919 W::Regular => 5,
9920 W::Medium => 6,
9921 W::Semibold => 8,
9922 W::Bold => 9,
9923 W::Heavy => 10,
9924 W::Black => 12,
9925 }
9926}
9927
9928fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
9933 use objc2_app_kit::*;
9934 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
9935 let prepared = OFFSCREEN_FONTS.with(|t| {
9938 t.borrow()
9939 .iter()
9940 .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
9941 .map(|(_, f)| f.clone())
9942 });
9943 if let Some(f) = prepared {
9944 return f;
9945 }
9946 let Some(mtm) = objc2::MainThreadMarker::new() else {
9947 return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
9951 };
9952 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
9953 let mut traits = NSFontTraitMask::empty();
9954 if weight >= day_spec::FontWeight::Semibold {
9955 traits |= NSFontTraitMask::BoldFontMask;
9956 }
9957 if font.italic {
9958 traits |= NSFontTraitMask::ItalicFontMask;
9959 }
9960 let Some(family) = font.family.as_deref() else {
9961 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
9962 return if font.italic {
9963 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
9964 } else {
9965 base
9966 };
9967 };
9968 let ns_family = NSString::from_str(family);
9969 if let Some(f) = unsafe {
9970 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
9971 } {
9972 return f;
9973 }
9974 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
9975 return if traits.is_empty() {
9976 f
9977 } else {
9978 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
9979 };
9980 }
9981 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
9982 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
9983}
9984
9985fn canvas_text_attrs(
9988 font: &NSFont,
9989 color: day_spec::Color,
9990) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
9991 let col = nscolor(color);
9992 let keys: [&NSString; 2] = unsafe {
9994 [
9995 objc2_app_kit::NSFontAttributeName,
9996 objc2_app_kit::NSForegroundColorAttributeName,
9997 ]
9998 };
9999 let objs: [&objc2::runtime::AnyObject; 2] = [
10000 font as &objc2::runtime::AnyObject,
10001 col.as_ref() as &objc2::runtime::AnyObject,
10002 ];
10003 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
10004}
10005
10006fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
10009 use objc2_app_kit::*;
10010 let base: Retained<NSFont> = match spec.style {
10011 Font::System(pt) => {
10012 let w = spec
10013 .weight
10014 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10015 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
10016 }
10017 Font::Custom(name, pt) => {
10021 if let Some(f) = unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
10022 if spec
10023 .weight
10024 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
10025 {
10026 let mtm =
10027 objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10028 unsafe {
10029 NSFontManager::sharedFontManager(mtm)
10030 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
10031 }
10032 } else {
10033 f
10034 }
10035 } else {
10036 log::warn!(
10037 "unknown font family {name:?} — falling back to the system font \
10038 (is the file in the project's fonts/ directory?)"
10039 );
10040 let w = spec
10041 .weight
10042 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10043 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
10044 }
10045 }
10046 style => {
10047 let ts = ns_text_style(style).expect("semantic style");
10050 let opts = objc2_foundation::NSDictionary::new();
10051 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
10052 match spec.weight {
10053 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
10055 None => f,
10056 }
10057 }
10058 };
10059 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
10064 let w = spec
10065 .weight
10066 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10067 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
10068 } else {
10069 base
10070 };
10071 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
10075 let w = spec
10076 .weight
10077 .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10078 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
10079 } else {
10080 base
10081 };
10082 #[expect(
10086 clippy::float_cmp,
10087 reason = "1.0 is the exact unscaled default of `FontSpec::scale`"
10088 )]
10089 let base = if spec.scale == 1.0 {
10090 base
10091 } else {
10092 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10093 let pts = spec.resolved_points(base.pointSize());
10094 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
10095 };
10096 let base = if spec.italic {
10097 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10098 unsafe {
10099 NSFontManager::sharedFontManager(mtm)
10100 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
10101 }
10102 } else {
10103 base
10104 };
10105 with_font_features(base, spec.small_caps, spec.oldstyle_figures)
10106}
10107
10108fn with_font_features(
10114 font: Retained<NSFont>,
10115 small_caps: bool,
10116 oldstyle: bool,
10117) -> Retained<NSFont> {
10118 use objc2_app_kit::{
10119 NSFontFeatureSelectorIdentifierKey, NSFontFeatureSettingsAttribute,
10120 NSFontFeatureTypeIdentifierKey,
10121 };
10122 let mut pairs: Vec<(i64, i64)> = Vec::new();
10123 if small_caps {
10124 pairs.push((37, 1));
10125 }
10126 if oldstyle {
10127 pairs.push((21, 0));
10128 }
10129 if pairs.is_empty() {
10130 return font;
10131 }
10132 let settings: Vec<Retained<NSDictionary<NSString, AnyObject>>> = pairs
10133 .into_iter()
10134 .map(|(kind, selector)| {
10135 let kind: Retained<AnyObject> = NSNumber::new_i64(kind).into();
10136 let selector: Retained<AnyObject> = NSNumber::new_i64(selector).into();
10137 unsafe {
10138 NSDictionary::from_retained_objects(
10139 &[
10140 NSFontFeatureTypeIdentifierKey,
10141 NSFontFeatureSelectorIdentifierKey,
10142 ],
10143 &[kind, selector],
10144 )
10145 }
10146 })
10147 .collect();
10148 let settings: Retained<AnyObject> = NSArray::from_retained_slice(&settings).into();
10149 let attrs = NSDictionary::from_retained_objects(
10150 &[unsafe { NSFontFeatureSettingsAttribute }],
10151 &[settings],
10152 );
10153 let descriptor = unsafe {
10154 font.fontDescriptor()
10155 .fontDescriptorByAddingAttributes(&attrs)
10156 };
10157 NSFont::fontWithDescriptor_size(&descriptor, font.pointSize()).unwrap_or(font)
10158}
10159
10160fn label_line_limit(wraps: bool, max_lines: u32) -> u32 {
10162 if wraps { max_lines } else { 1 }
10163}
10164
10165fn label_line_break(lines: u32, mode: day_spec::props::Truncation) -> NSLineBreakMode {
10171 use day_spec::props::Truncation;
10172 if lines != 1 {
10173 return NSLineBreakMode::ByWordWrapping;
10174 }
10175 match mode {
10176 Truncation::Tail => NSLineBreakMode::ByTruncatingTail,
10177 Truncation::Head => NSLineBreakMode::ByTruncatingHead,
10178 Truncation::Middle => NSLineBreakMode::ByTruncatingMiddle,
10179 }
10180}
10181
10182fn label_line_points(multiple: f64, font_points: f64) -> Option<f64> {
10185 (multiple.is_finite() && multiple > 0.0).then_some(multiple * font_points)
10186}
10187
10188fn natural_line_height(font: &NSFont) -> f64 {
10191 thread_local! {
10192 static METRICS: Retained<objc2_app_kit::NSLayoutManager> =
10193 objc2_app_kit::NSLayoutManager::new();
10194 }
10195 METRICS.with(|metrics| metrics.defaultLineHeightForFont(font))
10196}
10197
10198fn apply_label_paragraph(label: &DayLabel) {
10208 let iv = label.ivars();
10209 let p = iv.paragraph.get();
10210 let lines = label_line_limit(iv.wraps.get(), p.max_lines);
10211 let mode = label_line_break(lines, p.truncation);
10212 let rtl = match iv.direction.get() {
10213 Some(d) => d == day_spec::LayoutDirection::Rtl,
10214 None => {
10215 label.userInterfaceLayoutDirection()
10216 == objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft
10217 }
10218 };
10219 let writing = match iv.direction.get() {
10220 None => objc2_app_kit::NSWritingDirection::Natural,
10221 Some(_) if rtl => objc2_app_kit::NSWritingDirection::RightToLeft,
10222 Some(_) => objc2_app_kit::NSWritingDirection::LeftToRight,
10223 };
10224 let align = nstextalign(iv.align.get(), rtl);
10225 unsafe {
10226 label.setMaximumNumberOfLines(lines as isize);
10227 if let Some(cell) = label.cell() {
10230 cell.setWraps(lines != 1);
10231 cell.setUsesSingleLineMode(lines == 1);
10232 cell.setTruncatesLastVisibleLine(lines > 0);
10233 }
10234 label.setLineBreakMode(mode);
10235 label.setAlignment(align);
10236 label.setBaseWritingDirection(writing);
10237 }
10238 let needs_string = p.letter_spacing != 0.0 || label_line_points(p.line_height, 1.0).is_some();
10239 if !iv.has_runs.get() && !needs_string && !iv.stamped.get() {
10240 return;
10241 }
10242 if !iv.has_runs.get() {
10243 iv.stamped.set(true);
10244 }
10245 stamp_paragraph(label, &p, mode, align, writing);
10246}
10247
10248fn stamp_paragraph(
10252 label: &DayLabel,
10253 p: &day_spec::props::LabelParagraph,
10254 mode: NSLineBreakMode,
10255 align: objc2_app_kit::NSTextAlignment,
10256 writing: objc2_app_kit::NSWritingDirection,
10257) {
10258 use objc2_foundation::{NSMutableAttributedString, NSRange};
10259 let font = unsafe { label.font() }.unwrap_or_else(|| nsfont(day_spec::FontSpec::default()));
10260 let points = font.pointSize();
10261 unsafe {
10262 let cur = label.attributedStringValue();
10263 let m = NSMutableAttributedString::initWithAttributedString(
10264 NSMutableAttributedString::alloc(),
10265 &cur,
10266 );
10267 let whole = NSRange::new(0, cur.length());
10268 if !label.ivars().has_runs.get() {
10269 let fg = label
10272 .textColor()
10273 .unwrap_or_else(objc2_app_kit::NSColor::labelColor);
10274 m.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &font, whole);
10275 m.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
10276 }
10277 let style = objc2_app_kit::NSMutableParagraphStyle::new();
10278 style.setAlignment(align);
10279 style.setLineBreakMode(mode);
10280 style.setBaseWritingDirection(writing);
10281 let line = label_line_points(p.line_height, points);
10282 if let Some(h) = line {
10283 style.setMinimumLineHeight(h);
10284 style.setMaximumLineHeight(h);
10285 }
10286 m.addAttribute_value_range(objc2_app_kit::NSParagraphStyleAttributeName, &style, whole);
10287 if p.letter_spacing == 0.0 {
10288 m.removeAttribute_range(objc2_app_kit::NSKernAttributeName, whole);
10289 } else {
10290 let kern = NSNumber::new_f64(p.letter_spacing * points);
10291 m.addAttribute_value_range(objc2_app_kit::NSKernAttributeName, &kern, whole);
10292 }
10293 match line {
10296 Some(h) => {
10297 let offset = NSNumber::new_f64((h - natural_line_height(&font)) / 2.0);
10298 m.addAttribute_value_range(
10299 objc2_app_kit::NSBaselineOffsetAttributeName,
10300 &offset,
10301 whole,
10302 );
10303 }
10304 None => m.removeAttribute_range(objc2_app_kit::NSBaselineOffsetAttributeName, whole),
10305 }
10306 label.setAttributedStringValue(&m);
10307 }
10308}
10309
10310fn attributed_label(
10316 text: &str,
10317 base_font: &NSFont,
10318 color: Option<day_spec::Ink>,
10319 role: day_spec::props::TextRole,
10320 runs: &[day_spec::TextRun],
10321) -> Retained<objc2_foundation::NSAttributedString> {
10322 use objc2_foundation::{NSMutableAttributedString, NSRange};
10323 let ns = NSString::from_str(text);
10324 let s = unsafe {
10325 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
10326 };
10327 let whole = NSRange::new(0, ns.length());
10328 unsafe {
10329 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
10330 let fg = color.map_or_else(
10338 || match role {
10339 day_spec::props::TextRole::Secondary => {
10340 objc2_app_kit::NSColor::secondaryLabelColor()
10341 }
10342 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
10343 },
10344 color::nsink,
10345 );
10346 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
10347 }
10348 for r in runs {
10349 let Some(range) = utf16_range(text, &r.range) else {
10350 continue;
10351 };
10352 unsafe {
10353 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
10354 if let Some(c) = r.color {
10355 s.addAttribute_value_range(
10356 objc2_app_kit::NSForegroundColorAttributeName,
10357 &color::nsink(c),
10358 range,
10359 );
10360 }
10361 if let Some(c) = r.background {
10362 s.addAttribute_value_range(
10363 objc2_app_kit::NSBackgroundColorAttributeName,
10364 &color::nsink(c),
10365 range,
10366 );
10367 }
10368 for (line, style_key, color_key) in [
10371 (
10372 r.underline,
10373 objc2_app_kit::NSUnderlineStyleAttributeName,
10374 objc2_app_kit::NSUnderlineColorAttributeName,
10375 ),
10376 (
10377 r.strikethrough,
10378 objc2_app_kit::NSStrikethroughStyleAttributeName,
10379 objc2_app_kit::NSStrikethroughColorAttributeName,
10380 ),
10381 ] {
10382 let Some(d) = line else { continue };
10383 let style = objc2_foundation::NSNumber::new_i64(ns_underline(Some(d)));
10384 s.addAttribute_value_range(style_key, &style, range);
10385 if let Some(c) = d.color {
10386 s.addAttribute_value_range(color_key, &color::nsink(c), range);
10387 }
10388 }
10389 if let Some(url) = r.link.as_deref() {
10390 let value = NSString::from_str(url);
10393 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
10394 }
10395 }
10396 }
10397 s.into_super()
10398}
10399
10400fn ns_underline(u: Option<day_spec::Decoration>) -> i64 {
10406 use day_spec::DecorationStyle as U;
10407 match u.map(|d| d.style) {
10408 None => 0,
10409 Some(U::Single) => 0x01,
10410 Some(U::Double) => 0x09,
10411 Some(U::Dotted) => 0x01 | 0x0100,
10412 Some(U::Wavy) => 0x01 | 0x0400,
10413 }
10414}
10415
10416fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
10418 let start = text.get(..r.start)?.encode_utf16().count();
10419 let len = text.get(r.clone())?.encode_utf16().count();
10420 Some(objc2_foundation::NSRange::new(start, len))
10421}
10422
10423fn register_bundled_fonts() {
10428 #[link(name = "CoreText", kind = "framework")]
10430 unsafe extern "C" {
10431 fn CTFontManagerRegisterFontsForURL(
10432 font_url: *const std::ffi::c_void,
10433 scope: u32, error: *mut *const std::ffi::c_void,
10435 ) -> bool;
10436 }
10437 for path in day_spec::fonts::bundled_fonts() {
10438 let url = unsafe {
10439 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
10440 };
10441 let ok = unsafe {
10442 CTFontManagerRegisterFontsForURL(
10443 Retained::as_ptr(&url).cast::<std::ffi::c_void>(),
10444 1,
10445 std::ptr::null_mut(),
10446 )
10447 };
10448 if !ok {
10449 log::warn!("could not register bundled font {}", path.display());
10450 }
10451 }
10452}
10453
10454fn nstextalign(a: day_spec::props::TextAlign, rtl: bool) -> objc2_app_kit::NSTextAlignment {
10459 match a {
10460 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
10461 day_spec::props::TextAlign::Justified => objc2_app_kit::NSTextAlignment::Justified,
10462 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
10463 day_spec::props::TextAlign::Trailing if rtl => objc2_app_kit::NSTextAlignment::Left,
10464 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
10465 }
10466}
10467
10468fn content_of(parent: &Handle) -> Retained<NSView> {
10470 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
10471 && let Some(doc) = unsafe { sv.documentView() }
10472 {
10473 return doc;
10474 }
10475 parent.clone()
10476}
10477
10478fn warn_missing_renderer(kind: PieceKind) {
10483 day_spec::placeholder::report(kind, "appkit");
10484}
10485
10486pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
10490 view_of(&unsafe {
10491 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
10492 })
10493}
10494
10495impl Toolkit for AppKit {
10496 fn ui_idle(&mut self) -> bool {
10499 toolbar::chrome_settled()
10500 }
10501
10502 type Handle = Handle;
10503
10504 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
10507 let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
10508 let block = block2::StackBlock::new(|| {
10509 if let Some(rgb) = color::srgb(&color::role_color(role)) {
10510 result.set(rgb);
10511 }
10512 });
10513 NSApplication::sharedApplication(self.mtm())
10514 .effectiveAppearance()
10515 .performAsCurrentDrawingAppearance(&block);
10516 result.get()
10517 }
10518
10519 fn dark_mode(&mut self) -> bool {
10520 let app = NSApplication::sharedApplication(self.mtm());
10523 app.effectiveAppearance()
10524 .name()
10525 .to_string()
10526 .contains("Dark")
10527 }
10528
10529 fn reduce_motion(&mut self) -> bool {
10532 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
10533 }
10534
10535 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
10539 use day_spec::AppBadge;
10540 let label = match badge {
10541 AppBadge::None | AppBadge::Count(0) => None,
10543 AppBadge::Count(n) => Some(n.to_string()),
10544 AppBadge::Text(t) if t.is_empty() => None,
10545 AppBadge::Text(t) => Some(t.clone()),
10546 AppBadge::Dot => Some("\u{2022}".to_string()),
10548 };
10549 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
10550 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
10551 unsafe { tile.setBadgeLabel(ns.as_deref()) };
10552 tile.display();
10553 }
10554
10555 fn set_appearance(&mut self, dark: Option<bool>) {
10556 let app = NSApplication::sharedApplication(self.mtm());
10557 let appearance = dark.and_then(|d| {
10558 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
10559 if d {
10560 objc2_app_kit::NSAppearanceNameDarkAqua
10561 } else {
10562 objc2_app_kit::NSAppearanceNameAqua
10563 }
10564 })
10565 });
10566 unsafe { app.setAppearance(appearance.as_deref()) };
10568 color::refresh_layers_soon();
10571 }
10572
10573 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
10574 controls::refresh_gesture::attach(handle, host);
10575 }
10576
10577 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
10578 unsafe {
10579 handle.setHidden(!visible);
10580 }
10581 }
10582
10583 #[expect(
10584 clippy::match_same_arms,
10585 reason = "one arm per capability, each documented with the AppKit mechanism behind it"
10586 )]
10587 fn capability(&self, cap: Cap) -> Support {
10588 match cap {
10589 Cap::ShareActions => Support::Native,
10591 Cap::SearchField => Support::Native,
10592 Cap::ComboBox => Support::Native,
10593 Cap::Stepper => Support::Native,
10594 Cap::DateTimePicker => Support::Native,
10595 Cap::ColorPicker => Support::Native,
10596 Cap::PullRefresh => Support::Emulated,
10597 Cap::Pager => Support::Emulated,
10598 Cap::PullRefreshGesture => Support::Emulated,
10599 Cap::Cursor => Support::Native,
10603 Cap::FontList => Support::Native,
10605 Cap::ListItem => Support::Native,
10607 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
10611 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
10614 Cap::Announce => Support::Native,
10617 Cap::ReduceMotion => Support::Native,
10620 Cap::Snapshot
10621 | Cap::NativeSymbols
10622 | Cap::NavTabs
10631 | Cap::NavSplit
10632 | Cap::NavRepresent
10636 | Cap::NavContentList
10639 | Cap::Dialogs
10640 | Cap::FileDialogs
10641 | Cap::FolderDialog
10643 | Cap::Animation
10644 | Cap::TextEditable
10646 | Cap::TextSelectable
10647 | Cap::TextSpellCheck
10648 | Cap::NavReorder | Cap::ListReorder
10651 | Cap::ListRecycling
10654 | Cap::ListSwipeActions
10657 | Cap::ListSections
10659 | Cap::Tree
10662 | Cap::TreeSections
10663 | Cap::TreeMove
10664 | Cap::MultiWindow
10666 | Cap::WindowStates
10669 | Cap::WindowFullscreen
10670 | Cap::ContentProtection
10672 | Cap::WindowTabbing
10675 | Cap::DockMenu
10677 | Cap::FramelessWindow
10681 | Cap::OverlayTitleBar
10682 | Cap::TransparentWindow
10683 | Cap::WindowMaterial
10684 | Cap::DragRegion
10686 | Cap::StatusItem
10689 | Cap::AppProgress
10690 | Cap::DockVisibility
10691 | Cap::WindowGeometry
10694 | Cap::WindowPosition
10695 | Cap::WindowLevel
10696 | Cap::WindowAppearance
10697 | Cap::RequestAttention
10698 | Cap::Monitors
10699 | Cap::DynamicShortcuts
10701 | Cap::Toolbar
10703 | Cap::ToolbarSearch
10705 | Cap::AppMenu
10706 | Cap::AppBadgeCount
10709 | Cap::AppBadgeText
10710 | Cap::UndoBridge
10713 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
10714 | Cap::AppBadgeDot
10715 | Cap::Appearance
10716 | Cap::BaselineAlignment
10718 | Cap::Inspector
10721 | Cap::Split
10723 | Cap::TextRuns
10724 | Cap::TextLinks => Support::Native,
10725 Cap::Cover => Support::Emulated,
10728 Cap::CoverSheet => Support::Native,
10730 Cap::Focusable => Support::Native,
10734 Cap::KeyPhases => Support::Native,
10737 Cap::HitSlop => Support::Native,
10740 Cap::LabelSelection => Support::Native,
10743 Cap::ScrollOffset => Support::Native,
10746 Cap::ScrollPhases => Support::Native,
10750 Cap::ScrollSnap => Support::Emulated,
10753 Cap::ScrollZoom => Support::Native,
10755 Cap::ListViewport | Cap::ListScrollAlign => Support::Native,
10758 Cap::ListReaderScroll => Support::Native,
10763 Cap::ScrollKeyboardDismiss | Cap::PagerProgress => Support::Unsupported,
10767 _ => Support::Unsupported,
10768 }
10769 }
10770
10771 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
10772 let mtm = self.mtm;
10773 match Builtin::from_key(kind) {
10774 Some(Builtin::Container) => {
10775 let v = DayFlipped::new(mtm);
10776 if let Some(p) = props.downcast_ref::<ContainerProps>() {
10777 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
10778 v.set_section_card(p.corner_radius);
10779 } else if p.fill.is_some()
10780 || p.border.is_some()
10781 || p.shadow.is_some()
10782 || p.corner_radius > 0.0
10783 || p.clips
10784 {
10785 v.set_surface(p);
10786 }
10787 }
10788 view_of(&v)
10789 }
10790 Some(Builtin::Scroll) => {
10791 let p = props
10792 .downcast_ref::<day_spec::props::ScrollProps>()
10793 .cloned()
10794 .unwrap_or_default();
10795 scroll::realize(mtm, id, &p)
10796 }
10797 Some(Builtin::Label) => {
10798 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
10803 return placeholder_view(mtm, kind);
10804 };
10805 let tf = DayLabel::new(mtm, id, &p.text);
10806 tf.ivars().wraps.set(p.wraps);
10807 tf.ivars().paragraph.set(p.paragraph());
10808 tf.ivars().align.set(p.align);
10809 tf.ivars().reports_selection.set(p.reports_selection);
10810 tf.ivars().color.set(p.color);
10811 tf.ivars().role.set(p.role);
10812 unsafe { tf.setFont(Some(&nsfont(p.font))) };
10813 match (p.color, p.role) {
10817 (Some(c), _) => unsafe { tf.setTextColor(Some(&color::nsink(c))) },
10818 (None, day_spec::props::TextRole::Secondary) => unsafe {
10819 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
10820 },
10821 (None, day_spec::props::TextRole::Primary) => {}
10822 }
10823 if !p.runs.is_empty() {
10824 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
10825 unsafe { tf.setAttributedStringValue(&s) };
10826 }
10827 tf.ivars().has_runs.set(!p.runs.is_empty());
10828 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
10829 apply_label_paragraph(&tf);
10834 view_of(&Retained::into_super(tf))
10835 }
10836 Some(Builtin::Button) => {
10837 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
10838 return placeholder_view(mtm, kind);
10839 };
10840 let target = DayTarget::new(mtm, id);
10841 let btn = unsafe {
10842 NSButton::buttonWithTitle_target_action(
10843 &NSString::from_str(&p.title),
10844 Some(&*target),
10845 Some(sel!(action:)),
10846 mtm,
10847 )
10848 };
10849 apply_button_style(&btn, p.style);
10850 if p.icon.is_some() {
10851 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
10852 }
10853 unsafe { btn.setEnabled(p.enabled) };
10854 set_button_selected(&btn, p.selected);
10855 let view = view_of(&btn);
10856 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10857 view
10858 }
10859 Some(Builtin::Toggle) => {
10860 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
10861 return placeholder_view(mtm, kind);
10862 };
10863 let target = DayTarget::new(mtm, id);
10864 let sw = unsafe { NSSwitch::new(mtm) };
10865 unsafe {
10866 sw.setState(isize::from(p.on));
10867 sw.setEnabled(p.enabled);
10868 sw.setTarget(Some(&*target));
10869 sw.setAction(Some(sel!(action:)));
10870 }
10871 let view = view_of(&sw);
10872 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10873 view
10874 }
10875 Some(Builtin::Slider) => {
10876 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
10877 return placeholder_view(mtm, kind);
10878 };
10879 let target = DayTarget::new(mtm, id);
10880 let sl = unsafe {
10881 NSSlider::sliderWithValue_minValue_maxValue_target_action(
10882 p.value,
10883 p.min,
10884 p.max,
10885 Some(&*target),
10886 Some(sel!(action:)),
10887 mtm,
10888 )
10889 };
10890 unsafe { sl.setContinuous(true) };
10891 let view = view_of(&sl);
10892 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10893 view
10894 }
10895 Some(Builtin::Picker) => picker::realize_any(self, props, id),
10896 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
10897 Some(Builtin::TextField) => {
10898 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
10899 return placeholder_view(mtm, kind);
10900 };
10901 let tf = new_text_field(mtm, id, false);
10902 unsafe {
10903 tf.setStringValue(&NSString::from_str(&p.text));
10904 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
10905 }
10906 view_of(&tf)
10907 }
10908 Some(Builtin::Divider) => {
10909 let b = unsafe { NSBox::new(mtm) };
10910 unsafe { b.setBoxType(NSBoxType::Separator) };
10911 view_of(&b)
10912 }
10913 Some(Builtin::Progress) => {
10914 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
10915 return placeholder_view(mtm, kind);
10916 };
10917 if p.value.is_none() {
10918 return crate::controls::spinner::make(self, p, id);
10919 }
10920 let pi = unsafe { NSProgressIndicator::new(mtm) };
10921 unsafe {
10922 if let Some(v) = p.value {
10923 pi.setStyle(NSProgressIndicatorStyle::Bar);
10924 pi.setIndeterminate(false);
10925 pi.setMinValue(0.0);
10926 pi.setMaxValue(1.0);
10927 pi.setDoubleValue(v);
10928 } else {
10929 pi.setStyle(NSProgressIndicatorStyle::Spinning);
10930 pi.setIndeterminate(true);
10931 pi.startAnimation(None);
10932 }
10933 }
10934 view_of(&pi)
10935 }
10936 Some(Builtin::Canvas) => {
10937 let canvas = DayCanvas::new(mtm);
10938 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
10939 view_of(&canvas)
10940 }
10941 Some(Builtin::Inspector) => {
10942 let (visible, width, leading) =
10943 props
10944 .downcast_ref::<InspectorProps>()
10945 .map_or((false, 280.0, false), |p| {
10946 (
10947 p.visible,
10948 p.width,
10949 p.edge == day_spec::props::PaneEdge::Leading,
10950 )
10951 });
10952 let content_wrap = view_of(&DayFlipped::new(mtm));
10953 let panel_flipped = DayFlipped::new(mtm);
10954 panel_flipped.set_pane_backdrop();
10958 let panel_wrap = view_of(&panel_flipped);
10959 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
10960 let _ = unsafe { split_vc.view() };
10963 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
10964 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
10965 unsafe {
10966 content_vc.setView(&content_wrap);
10967 panel_vc.setView(&panel_wrap);
10968 }
10969 let content_item = unsafe {
10970 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
10971 };
10972 let panel_item = unsafe {
10977 if leading {
10978 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
10979 } else {
10980 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
10981 }
10982 };
10983 unsafe {
10984 panel_item.setCanCollapse(false);
10988 panel_item.setCollapsed(!visible);
10989 panel_item.setMinimumThickness(width);
10990 panel_item.setMaximumThickness(width);
10991 panel_item.setAllowsFullHeightLayout(true);
10992 if leading {
10993 split_vc.addSplitViewItem(&panel_item);
10994 split_vc.addSplitViewItem(&content_item);
10995 } else {
10996 split_vc.addSplitViewItem(&content_item);
10997 split_vc.addSplitViewItem(&panel_item);
10998 }
10999 }
11000 let split = unsafe { split_vc.splitView() };
11001 unsafe {
11002 split.setVertical(true);
11003 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11004 split.setTranslatesAutoresizingMaskIntoConstraints(true);
11008 }
11009 let view = view_of(&split);
11010 INSPECTOR_STATE.with(|m| {
11011 m.borrow_mut().insert(
11012 ptr_of(&view),
11013 InspectorState {
11014 content_wrap,
11015 panel_wrap,
11016 split_vc,
11017 panel_item,
11018 },
11019 )
11020 });
11021 view
11022 }
11023 Some(Builtin::InspectorPane) => {
11024 let pane = view_of(&DayNavPage::new(mtm, id));
11028 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
11029 let panel = props
11030 .downcast_ref::<InspectorPaneProps>()
11031 .is_some_and(|p| p.panel);
11032 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
11033 pane
11034 }
11035 Some(Builtin::Split) => {
11036 let (axis, fraction, min_pane) = props
11037 .downcast_ref::<SplitProps>()
11038 .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
11039 (p.axis, p.fraction, p.min_pane)
11040 });
11041 let wrap = view_of(&DayFlipped::new(mtm));
11042 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
11043 let first_wrap = view_of(&DayFlipped::new(mtm));
11044 let second_wrap = view_of(&DayFlipped::new(mtm));
11045 unsafe {
11046 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
11048 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11049 split.addArrangedSubview(&first_wrap);
11050 split.addArrangedSubview(&second_wrap);
11051 split.setFrame(wrap.bounds());
11052 split.setAutoresizingMask(
11053 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
11054 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
11055 );
11056 wrap.addSubview(&split);
11057 }
11058 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
11059 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
11060 SPLIT_STATE.with(|m| {
11061 m.borrow_mut().insert(
11062 ptr_of(&wrap),
11063 SplitState {
11064 split,
11065 first_wrap,
11066 second_wrap,
11067 delegate,
11068 },
11069 )
11070 });
11071 wrap
11072 }
11073 Some(Builtin::SplitPane) => {
11074 let pane = view_of(&DayNavPage::new(mtm, id));
11077 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
11078 let second = props
11079 .downcast_ref::<SplitPaneProps>()
11080 .is_some_and(|p| p.second);
11081 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
11082 pane
11083 }
11084 Some(Builtin::Nav) => {
11085 let presentation = props
11086 .downcast_ref::<NavProps>()
11087 .map_or(NavPresentation::Split, |p| p.presentation);
11088 let is_split = presentation.is_split();
11089 let sidebar_wrap = view_of(&DayFlipped::new(mtm));
11098 let detail_wrap = view_of(&DayFlipped::new(mtm));
11099 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
11100 let _ = unsafe { split_vc.view() };
11106 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11109 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11110 unsafe {
11111 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
11112 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
11113 }
11114 let sidebar_item = unsafe {
11115 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
11116 };
11117 let detail_item = unsafe {
11118 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
11119 };
11120 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
11126 let list_visible = props
11132 .downcast_ref::<NavProps>()
11133 .is_none_or(|p| p.list_visible);
11134 let (list_wrap, list_item) = match list_width {
11135 Some(w) => {
11136 let wrap = view_of(&DayFlipped::new(mtm));
11137 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11138 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
11139 let item = unsafe {
11140 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
11141 };
11142 unsafe {
11143 item.setCanCollapse(true);
11144 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
11145 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
11146 item.setCollapsed(!list_visible);
11147 }
11148 (Some(wrap), Some(item))
11149 }
11150 None => (None, None),
11151 };
11152 unsafe {
11153 sidebar_item.setCanCollapse(is_split);
11156 sidebar_item.setCollapsed(!is_split);
11157 if is_split {
11158 sidebar_item.setAllowsFullHeightLayout(true);
11162 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
11163 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
11164 } else {
11165 sidebar_item.setMinimumThickness(0.0);
11166 sidebar_item.setMaximumThickness(0.0);
11167 }
11168 split_vc.addSplitViewItem(&sidebar_item);
11169 if let Some(item) = list_item.as_ref() {
11170 split_vc.addSplitViewItem(item);
11171 }
11172 split_vc.addSplitViewItem(&detail_item);
11173 }
11174 let split = unsafe { split_vc.splitView() };
11175 unsafe {
11182 let after = split.nextResponder();
11183 split.setNextResponder(Some(&split_vc));
11184 let own_view = split_vc.view();
11194 let vc_resp: *const objc2_app_kit::NSResponder = {
11195 let r: &objc2_app_kit::NSResponder = &split_vc;
11196 r
11197 };
11198 let view_resp: *const objc2_app_kit::NSResponder = {
11199 let r: &objc2_app_kit::NSResponder = &own_view;
11200 r
11201 };
11202 let upstream = after.filter(|a| {
11203 let p: *const objc2_app_kit::NSResponder = &raw const **a;
11204 p != vc_resp && p != view_resp
11205 });
11206 split_vc.setNextResponder(upstream.as_deref());
11207 }
11208 unsafe {
11209 split.setVertical(true);
11210 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11211 split.setTranslatesAutoresizingMaskIntoConstraints(true);
11219 }
11220 let root_title = props
11221 .downcast_ref::<NavProps>()
11222 .map_or_default(|p| p.title.clone());
11223 let header = if presentation == NavPresentation::Stack {
11226 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
11227 } else {
11228 None
11229 };
11230 let tabs = (presentation == NavPresentation::Tabs).then(|| {
11233 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
11234 let documents = props
11235 .downcast_ref::<NavProps>()
11236 .is_some_and(|p| p.documents.is_some());
11237 let (inset, inset_top) = if documents {
11243 (0.0, 0.0)
11244 } else {
11245 (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
11246 };
11247 let b = detail_wrap.bounds();
11248 let frame = NSRect::new(
11249 NSPoint::new(inset, inset_top),
11250 NSSize::new(
11251 (b.size.width - 2.0 * inset).max(0.0),
11252 (b.size.height - inset_top - inset).max(0.0),
11253 ),
11254 );
11255 unsafe {
11256 tv.setTabViewType(if documents {
11257 objc2_app_kit::NSTabViewType::NoTabsNoBorder
11258 } else {
11259 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
11260 });
11261 tv.setFrame(frame);
11262 tv.setAutoresizingMask(
11263 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
11264 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
11265 );
11266 detail_wrap.addSubview(&tv);
11267 }
11268 TabHost {
11269 view: tv,
11270 target: None,
11271 }
11272 });
11273 let view = view_of(&split);
11274 NAV_STATE.with(|m| {
11275 m.borrow_mut().insert(
11276 ptr_of(&view),
11277 NavState {
11278 sidebar_wrap,
11279 detail_wrap,
11280 split_vc,
11281 sidebar_item,
11282 list_wrap,
11283 list_item,
11284 pages: Vec::new(),
11285 list_page: None,
11286 sidebar_page: None,
11287 list_width,
11288 list_visible,
11289 list_positioned: false,
11290 positioned: false,
11291 presentation,
11292 selected: 0,
11293 tabs,
11294 header,
11295 root_title,
11296 node: id,
11297 title_strip: 0.0,
11298 },
11299 )
11300 });
11301 view
11302 }
11303 Some(Builtin::NavPage) => {
11304 let page = view_of(&DayNavPage::new(mtm, id));
11305 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
11306 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
11307 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
11308 }
11309 page
11310 }
11311 Some(Builtin::Cover) => {
11315 let page = DayNavPage::new(mtm, id);
11316 let cover_props = props.downcast_ref::<CoverProps>();
11317 page.ivars()
11320 .sheet
11321 .set(cover_props.is_some_and(|p| p.sheet || p.half));
11322 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
11323 page.ivars().large.set(cover_props.is_some_and(|p| p.large));
11324 unsafe { page.setHidden(true) };
11325 view_of(&page)
11326 }
11327 Some(Builtin::NavMenu) => {
11328 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
11329 return placeholder_view(mtm, kind);
11330 };
11331 let data = DayNavMenuData::new(
11332 mtm,
11333 id,
11334 &p.items,
11335 &p.icons,
11336 &p.badges,
11337 &p.badge_icons,
11338 &p.badge_tints,
11339 &p.sections,
11340 &p.tints,
11341 &p.menus,
11342 );
11343 (*data.ivars().movable.borrow_mut()).clone_from(&p.movable);
11344 data.ivars().regroup.set(p.regroup);
11345 (*data.ivars().sorted.borrow_mut()).clone_from(&p.sorted);
11346 let outline: Retained<objc2_app_kit::NSOutlineView> = {
11348 let o: Retained<DayNavOutlineView> =
11349 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
11350 NAV_OUTLINE_MENUS
11351 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
11352 unsafe { msg_send![&*o, self] }
11353 };
11354 let col = unsafe {
11355 objc2_app_kit::NSTableColumn::initWithIdentifier(
11356 objc2_app_kit::NSTableColumn::alloc(mtm),
11357 &NSString::from_str("item"),
11358 )
11359 };
11360 unsafe {
11361 outline.addTableColumn(&col);
11362 outline.setOutlineTableColumn(Some(&col));
11363 outline.setHeaderView(None);
11364 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
11377 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
11382 outline.setFloatsGroupRows(true);
11385 outline.setIndentationPerLevel(0.0);
11386 outline.registerForDraggedTypes(
11389 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11390 DAY_NAV_PASTEBOARD_TYPE,
11391 )]),
11392 );
11393 outline.setDraggingSourceOperationMask_forLocal(
11394 objc2_app_kit::NSDragOperation::Move,
11395 true,
11396 );
11397 outline.setDraggingSourceOperationMask_forLocal(
11398 objc2_app_kit::NSDragOperation::None,
11399 false,
11400 );
11401 outline.setDraggingDestinationFeedbackStyle(
11402 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
11403 );
11404 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11405 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11406 outline.reloadData();
11407 }
11408 let scroll = unsafe { NSScrollView::new(mtm) };
11409 unsafe {
11410 scroll.setDrawsBackground(false);
11411 scroll.setHasVerticalScroller(true);
11412 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11416 scroll.setHasHorizontalScroller(false);
11418 outline.setAutoresizingMask(
11419 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
11420 );
11421 outline.setColumnAutoresizingStyle(
11422 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11423 );
11424 scroll.setDocumentView(Some(&outline));
11425 }
11426 let view = view_of(&scroll);
11427 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
11430 data.ivars().suppress.set(true);
11431 unsafe {
11432 outline.selectRowIndexes_byExtendingSelection(
11433 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
11434 false,
11435 );
11436 };
11437 data.ivars().suppress.set(false);
11438 }
11439 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
11440 view
11441 }
11442 Some(Builtin::List) => {
11443 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
11444 return placeholder_view(mtm, kind);
11445 };
11446 let table: Retained<DayListView> =
11448 unsafe { msg_send![DayListView::alloc(mtm), init] };
11449 let table = Retained::into_super(table);
11450 if p.inset_grouped {
11451 unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
11454 }
11455 let col = unsafe {
11456 NSTableColumn::initWithIdentifier(
11457 NSTableColumn::alloc(mtm),
11458 &NSString::from_str("day.list.col"),
11459 )
11460 };
11461 let data = DayListData::new(
11462 mtm,
11463 id,
11464 p.selectable,
11465 p.multi_select,
11466 p.row_height == RowHeight::Automatic,
11467 p.sections,
11468 );
11469 unsafe {
11470 if p.multi_select {
11471 table.setAllowsMultipleSelection(true);
11472 }
11473 table.addTableColumn(&col);
11474 table.setHeaderView(None);
11475 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
11484 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
11488 if p.separators == Some(true) {
11492 table.setGridStyleMask(
11493 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
11494 );
11495 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
11496 }
11497 table.setColumnAutoresizingStyle(
11498 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11499 );
11500 table.setFloatsGroupRows(p.sections);
11503 match p.row_height {
11504 RowHeight::Uniform(h) => table.setRowHeight(h),
11505 RowHeight::Automatic => table.setRowHeight(44.0),
11506 }
11507 if !p.selectable {
11508 table.setSelectionHighlightStyle(
11509 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
11510 );
11511 }
11512 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
11516 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11517 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11518 table.setTarget(Some(&*data));
11519 if p.activatable {
11520 table.setDoubleAction(Some(sel!(doubleClickRow:)));
11521 }
11522 if p.reorderable {
11523 table.registerForDraggedTypes(
11527 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11528 DAY_ROW_PASTEBOARD_TYPE,
11529 )]),
11530 );
11531 table.setDraggingSourceOperationMask_forLocal(
11532 objc2_app_kit::NSDragOperation::Move,
11533 true,
11534 );
11535 table.setDraggingSourceOperationMask_forLocal(
11536 objc2_app_kit::NSDragOperation::None,
11537 false,
11538 );
11539 table.setDraggingDestinationFeedbackStyle(
11540 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
11541 );
11542 }
11543 }
11544 let scroll: Retained<DayListScrollView> =
11545 unsafe { msg_send![DayListScrollView::alloc(mtm), init] };
11546 let scroll = Retained::into_super(scroll);
11547 unsafe {
11548 scroll.setDrawsBackground(false);
11549 scroll.setHasVerticalScroller(true);
11550 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11554 scroll.setDocumentView(Some(&table));
11555 let clip = scroll.contentView();
11556 clip.setPostsBoundsChangedNotifications(true);
11557 clip.setPostsFrameChangedNotifications(true);
11558 let center = objc2_foundation::NSNotificationCenter::defaultCenter();
11559 for name in [
11561 objc2_app_kit::NSViewBoundsDidChangeNotification,
11562 objc2_app_kit::NSViewFrameDidChangeNotification,
11563 ] {
11564 center.addObserver_selector_name_object(
11565 &data,
11566 sel!(listViewportChanged:),
11567 Some(name),
11568 Some(&clip),
11569 );
11570 }
11571 for (name, selector) in [
11573 (
11574 objc2_app_kit::NSScrollViewWillStartLiveScrollNotification,
11575 sel!(listLiveScrollStarted:),
11576 ),
11577 (
11578 objc2_app_kit::NSScrollViewDidEndLiveScrollNotification,
11579 sel!(listLiveScrollEnded:),
11580 ),
11581 ] {
11582 center.addObserver_selector_name_object(
11583 &data,
11584 selector,
11585 Some(name),
11586 Some(&scroll),
11587 );
11588 }
11589 }
11590 let view = view_of(&scroll);
11591 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
11592 view
11593 }
11594 Some(Builtin::Tree) => {
11595 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
11596 return placeholder_view(mtm, kind);
11597 };
11598 let outline: Retained<objc2_app_kit::NSOutlineView> = {
11600 let o: Retained<DayOutlineView> =
11601 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
11602 unsafe { msg_send![&*o, self] }
11603 };
11604 let col = unsafe {
11605 NSTableColumn::initWithIdentifier(
11606 NSTableColumn::alloc(mtm),
11607 &NSString::from_str("day.tree.col"),
11608 )
11609 };
11610 let data = DayTreeData::new(mtm, id, p.selectable);
11611 unsafe {
11612 if p.multi_select {
11613 outline.setAllowsMultipleSelection(true);
11614 }
11615 outline.addTableColumn(&col);
11616 outline.setOutlineTableColumn(Some(&col));
11617 outline.setHeaderView(None);
11618 if p.section_headers {
11619 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
11622 outline.setFloatsGroupRows(true);
11623 } else {
11624 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
11627 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
11628 }
11629 outline.setColumnAutoresizingStyle(
11630 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11631 );
11632 outline.setAutoresizesOutlineColumn(true);
11633 if let Some(indent) = p.indent {
11634 outline.setIndentationPerLevel(indent);
11635 }
11636 match p.row_height {
11637 RowHeight::Uniform(h) => outline.setRowHeight(h),
11638 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
11639 RowHeight::Automatic => {}
11640 }
11641 if !p.selectable {
11642 outline.setSelectionHighlightStyle(
11643 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
11644 );
11645 }
11646 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
11647 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11648 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11649 if p.movable {
11650 outline.registerForDraggedTypes(
11655 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11656 DAY_TREE_PASTEBOARD_TYPE,
11657 )]),
11658 );
11659 outline.setDraggingSourceOperationMask_forLocal(
11660 objc2_app_kit::NSDragOperation::Move,
11661 true,
11662 );
11663 outline.setDraggingSourceOperationMask_forLocal(
11664 objc2_app_kit::NSDragOperation::None,
11665 false,
11666 );
11667 }
11668 }
11669 let scroll = unsafe { NSScrollView::new(mtm) };
11670 unsafe {
11671 scroll.setDrawsBackground(false);
11672 scroll.setHasVerticalScroller(true);
11673 scroll.setHasHorizontalScroller(false);
11674 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11675 outline.setAutoresizingMask(
11676 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
11677 );
11678 scroll.setDocumentView(Some(&outline));
11679 }
11680 let view = view_of(&scroll);
11681 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
11682 view
11683 }
11684 Some(Builtin::Image) => {
11685 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
11686 return placeholder_view(mtm, kind);
11687 };
11688 let iv: Retained<objc2_app_kit::NSImageView> =
11689 if p.content_mode == ContentMode::Fill {
11690 let view: Retained<FillImageView> =
11691 unsafe { msg_send![FillImageView::alloc(mtm), init] };
11692 Retained::from(
11693 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
11694 )
11695 } else {
11696 unsafe { objc2_app_kit::NSImageView::new(mtm) }
11697 };
11698 let scaling = match p.content_mode {
11701 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
11702 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
11703 };
11704 unsafe { iv.setImageScaling(scaling) };
11705 if let Some(img) = appkit_image_for(&p.source) {
11706 let img = image_rendered(img, p.tint.is_some() || p.template);
11712 unsafe { iv.setImage(Some(&img)) };
11713 }
11714 if let Some(t) = p.tint {
11715 unsafe { iv.setContentTintColor(Some(&color::nsink(t))) };
11716 }
11717 IMAGE_MODES.with(|t| {
11718 t.insert(
11719 ptr_of(&iv),
11720 ImageMode {
11721 template: p.template,
11722 tinted: p.tint.is_some(),
11723 },
11724 )
11725 });
11726 view_of(&iv)
11727 }
11728 Some(Builtin::ListItem) => {
11729 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
11730 else {
11731 return placeholder_view(mtm, kind);
11732 };
11733 make_list_item(p, mtm)
11734 }
11735 Some(Builtin::ListCell) | None => {
11738 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
11739 return make(self, props, id);
11740 }
11741 warn_missing_renderer(kind);
11745 placeholder_view(mtm, kind)
11746 }
11747 }
11748 }
11749
11750 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, anim: Option<&AnimSpec>) {
11751 match kind {
11752 kinds::LIST_ITEM => {
11753 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
11754 return;
11755 };
11756 let props = LIST_ITEMS.with(|m| {
11757 use day_spec::props::ListItemPatch as P;
11758 let mut m = m.borrow_mut();
11759 let props = m.get_mut(&ptr_of(h))?;
11760 match p {
11761 P::Title(t) => props.title.clone_from(t),
11762 P::Subtitle(t) => props.subtitle.clone_from(t),
11763 P::Detail(t) => props.detail.clone_from(t),
11764 P::Icon(i) => props.icon.clone_from(i),
11765 P::IconTint(c) => props.icon_tint = *c,
11766 P::Checked(on) => props.checked = *on,
11767 }
11768 Some(props.clone())
11769 });
11770 if let Some(props) = props {
11771 dress_list_item(h, &props, self.mtm());
11772 }
11773 }
11774 kinds::IMAGE => {
11775 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
11776 match p {
11777 day_spec::props::ImagePatch::Tint(c) => {
11778 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
11782 let key = ptr_of(&iv);
11783 let template = IMAGE_MODES
11784 .with(|t| {
11785 t.with(key, |m| {
11786 m.tinted = c.is_some();
11787 m.renders_template()
11788 })
11789 })
11790 .unwrap_or(c.is_some());
11791 if let Some(img) = unsafe { iv.image() } {
11792 let img = image_rendered(img, template);
11793 unsafe { iv.setImage(Some(&img)) };
11794 }
11795 let tint = c.map(color::nsink);
11796 unsafe { iv.setContentTintColor(tint.as_deref()) };
11797 }
11798 }
11799 day_spec::props::ImagePatch::Source(source) => {
11803 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
11804 if let Some(img) = appkit_image_for(source) {
11810 let template = IMAGE_MODES
11811 .with(|t| t.get(ptr_of(&iv)))
11812 .is_some_and(ImageMode::renders_template);
11813 let img = image_rendered(img, template);
11814 unsafe { iv.setImage(Some(&img)) };
11815 }
11816 }
11817 }
11818 }
11819 }
11820 }
11821 kinds::CONTAINER => {
11822 let (Some(patch), Ok(v)) = (
11823 patch.downcast_ref::<ContainerPatch>(),
11824 h.clone().downcast::<DayFlipped>(),
11825 ) else {
11826 return;
11827 };
11828 match patch {
11829 ContainerPatch::Fill(fill) => motion::set_background(&v, fill.clone(), anim),
11832 ContainerPatch::Surface(p) => {
11839 if v.ivars().section_card.get().is_some() {
11840 v.set_section_card(p.corner_radius);
11841 return;
11842 }
11843 let fill = v.ivars().surface.borrow().as_ref().map(|s| s.fill.clone());
11844 if fill.as_ref() != Some(&p.fill) {
11845 motion::set_background(&v, p.fill.clone(), anim);
11846 }
11847 v.set_surface(p);
11848 }
11849 }
11850 }
11851 kinds::LABEL => {
11852 if let (Some(p), Ok(tf)) = (
11853 patch.downcast_ref::<LabelPatch>(),
11854 h.clone().downcast::<NSTextField>(),
11855 ) {
11856 let label = h.downcast_ref::<DayLabel>();
11857 match p {
11858 LabelPatch::Paragraph(para) => {
11859 if let Some(label) = label {
11860 label.ivars().paragraph.set(*para);
11861 }
11862 }
11863 LabelPatch::Text(t) => {
11864 unsafe { tf.setStringValue(&NSString::from_str(t)) };
11865 if let Some(label) = label {
11866 label.clear_selection();
11867 label.ivars().has_runs.set(false);
11868 label.set_links(false);
11869 }
11870 }
11871 LabelPatch::Color(c) => {
11872 if let Some(label) = label {
11873 label.ivars().color.set(*c);
11874 }
11875 unsafe { tf.setTextColor(c.map(color::nsink).as_deref()) };
11876 }
11877 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
11878 LabelPatch::Runs(text, runs) => {
11879 let base = unsafe { tf.font() };
11883 let (own, role) = label.map_or((None, TextRole::default()), |l| {
11885 (l.ivars().color.get(), l.ivars().role.get())
11886 });
11887 let s = match base.as_deref() {
11888 Some(f) => attributed_label(text, f, own, role, runs),
11889 None => attributed_label(
11890 text,
11891 &nsfont(day_spec::FontSpec::default()),
11892 own,
11893 role,
11894 runs,
11895 ),
11896 };
11897 unsafe { tf.setAttributedStringValue(&s) };
11898 if let Some(label) = label {
11901 label.clear_selection();
11902 label.ivars().has_runs.set(!runs.is_empty());
11903 label.set_links(runs.iter().any(|r| r.link.is_some()));
11904 }
11905 }
11906 }
11907 if let Some(label) = label {
11911 apply_label_paragraph(label);
11912 }
11913 }
11914 }
11915 kinds::BUTTON => {
11916 if let (Some(p), Ok(btn)) = (
11917 patch.downcast_ref::<ButtonPatch>(),
11918 h.clone().downcast::<NSButton>(),
11919 ) {
11920 match p {
11921 ButtonPatch::Content(c) => {
11922 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only);
11923 }
11924 ButtonPatch::Title(t) => {
11925 let style = BUTTON_STYLES
11926 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
11927 .unwrap_or_default();
11928 set_button_title(&btn, t, style);
11929 }
11930 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
11931 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
11932 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
11933 }
11934 }
11935 }
11936 kinds::TOGGLE => {
11937 if let (Some(p), Ok(sw)) = (
11938 patch.downcast_ref::<TogglePatch>(),
11939 h.clone().downcast::<NSSwitch>(),
11940 ) {
11941 match p {
11942 TogglePatch::On(on) => {
11943 let want = isize::from(*on);
11944 if unsafe { sw.state() } != want {
11945 unsafe { sw.setState(want) };
11946 }
11947 }
11948 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
11949 }
11950 }
11951 }
11952 kinds::SLIDER => {
11953 if let (Some(p), Ok(sl)) = (
11954 patch.downcast_ref::<SliderPatch>(),
11955 h.clone().downcast::<NSSlider>(),
11956 ) {
11957 match p {
11958 SliderPatch::Value(v) => {
11959 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
11960 unsafe { sl.setDoubleValue(*v) };
11961 }
11962 }
11963 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
11964 }
11965 }
11966 }
11967 kinds::PROGRESS => {
11968 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
11969 {
11970 crate::controls::spinner::update(self, h, p);
11971 return;
11972 }
11973
11974 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
11975 patch.downcast_ref::<ProgressPatch>(),
11976 h.clone().downcast::<NSProgressIndicator>(),
11977 ) {
11978 unsafe {
11979 if let Some(val) = v {
11980 if pi.isIndeterminate() {
11981 pi.stopAnimation(None);
11982 pi.setIndeterminate(false);
11983 pi.setStyle(NSProgressIndicatorStyle::Bar);
11984 pi.setMinValue(0.0);
11985 pi.setMaxValue(1.0);
11986 }
11987 if (pi.doubleValue() - val).abs() > 0.0001 {
11988 pi.setDoubleValue(*val);
11989 }
11990 } else {
11991 pi.setIndeterminate(true);
11992 pi.setStyle(NSProgressIndicatorStyle::Spinning);
11993 pi.startAnimation(None);
11994 }
11995 }
11996 }
11997 }
11998 kinds::NAV_MENU => {
11999 if let Some(NavMenuPatch::Items {
12000 items,
12001 icons,
12002 badges,
12003 badge_icons,
12004 badge_tints,
12005 sections,
12006 tints,
12007 menus,
12008 movable,
12009 sorted,
12010 selected,
12011 rows_changed,
12012 ..
12013 }) = patch.downcast_ref::<NavMenuPatch>()
12014 {
12015 NAV_MENUS.with(|m| {
12016 let m = m.borrow();
12017 let Some((outline, data)) = m.get(&ptr_of(h)) else {
12018 return;
12019 };
12020 (*data.ivars().movable.borrow_mut()).clone_from(movable);
12021 (*data.ivars().sorted.borrow_mut()).clone_from(sorted);
12022 data.set_items(
12023 items,
12024 icons,
12025 badges,
12026 badge_icons,
12027 badge_tints,
12028 sections,
12029 tints,
12030 menus,
12031 );
12032 data.ivars().suppress.set(true);
12033 if let Some(rows) = rows_changed {
12036 let set = objc2_foundation::NSMutableIndexSet::new();
12037 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
12038 unsafe { set.addIndex(row) };
12039 }
12040 unsafe {
12041 outline.reloadDataForRowIndexes_columnIndexes(
12042 &set,
12043 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
12044 );
12045 };
12046 data.ivars().suppress.set(false);
12047 return;
12048 }
12049 unsafe {
12050 outline.reloadData();
12051 match selected.and_then(|i| data.row_of_item(i)) {
12052 Some(row) => outline.selectRowIndexes_byExtendingSelection(
12053 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
12054 false,
12055 ),
12056 None => outline.deselectAll(None),
12057 }
12058 }
12059 data.ivars().suppress.set(false);
12060 });
12061 adopt_menu_for_tabs(self.mtm(), h);
12063 } else if let Some(NavMenuPatch::IconProgress(progress)) =
12064 patch.downcast_ref::<NavMenuPatch>()
12065 {
12066 NAV_MENUS.with(|menus| {
12067 let menus = menus.borrow();
12068 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
12069 return;
12070 };
12071 let previous = data.ivars().icon_progress.replace(progress.clone());
12072 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
12073 let Some(index) = item else {
12074 continue;
12075 };
12076 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
12077 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
12078 continue;
12079 }
12080 if let Some(view) = unsafe {
12081 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
12082 } && let Some(cell) =
12083 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
12084 && let Some(icon) = unsafe { cell.imageView() }
12085 {
12086 nav_progress::update(&icon, value);
12087 }
12088 }
12089 });
12090 } else if let Some(NavMenuPatch::Selected(sel)) =
12091 patch.downcast_ref::<NavMenuPatch>()
12092 {
12093 NAV_MENUS.with(|m| {
12094 let m = m.borrow();
12095 let Some((outline, data)) = m.get(&ptr_of(h)) else {
12096 return;
12097 };
12098 data.ivars().suppress.set(true);
12099 unsafe {
12100 match sel.and_then(|i| data.row_of_item(i)) {
12101 Some(row) => outline.selectRowIndexes_byExtendingSelection(
12102 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
12103 false,
12104 ),
12105 None => outline.deselectAll(None),
12106 }
12107 }
12108 data.ivars().suppress.set(false);
12109 });
12110 }
12111 }
12112 kinds::INSPECTOR => {
12113 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
12114 INSPECTOR_STATE.with(|m| {
12115 if let Some(state) = m.borrow().get(&ptr_of(h)) {
12116 state.panel_item.setCollapsed(!*v);
12119 }
12120 });
12121 }
12122 }
12123 kinds::SPLIT => {
12124 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
12125 SPLIT_STATE.with(|m| {
12126 let m = m.borrow();
12127 let Some(state) = m.get(&ptr_of(h)) else {
12128 return;
12129 };
12130 let iv = state.delegate.ivars();
12131 match p {
12132 SplitPatch::Fraction(f) => {
12133 iv.share.set(f.clamp(0.0, 1.0));
12134 if iv.positioned.get() {
12135 split_place(&state.split, iv);
12136 }
12137 }
12138 SplitPatch::Axis(axis) => unsafe {
12139 state
12140 .split
12141 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
12142 state.split.adjustSubviews();
12143 if iv.positioned.get() {
12144 split_place(&state.split, iv);
12145 }
12146 },
12147 }
12148 });
12149 }
12150 }
12151 kinds::NAV => {
12152 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
12153 nav_present(self.mtm(), h, *next);
12154 return;
12155 }
12156 if let Some(p) = patch.downcast_ref::<NavPatch>() {
12157 NAV_STATE.with(|m| {
12158 let mut m = m.borrow_mut();
12159 let Some(state) = m.get_mut(&ptr_of(h)) else {
12160 return;
12161 };
12162 match p {
12163 NavPatch::Pushed { title, .. } => {
12164 let last = state.pages.len().saturating_sub(1);
12166 state.selected = last;
12167 for (i, page) in state.pages.iter().enumerate() {
12168 page.setHidden(i != last);
12169 }
12170 if let Some(hdr) = state.header.as_mut() {
12171 hdr.titles.push(title.clone());
12172 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
12173 }
12174 }
12175 NavPatch::Popped => {
12176 let n = state.pages.len();
12179 if let Some(top) = state.pages.last() {
12180 top.setHidden(true);
12181 }
12182 if n >= 2 {
12183 state.pages[n - 2].setHidden(false);
12184 }
12185 state.selected = n.saturating_sub(2);
12186 if let Some(hdr) = state.header.as_mut() {
12187 if hdr.titles.len() > 1 {
12188 hdr.titles.pop();
12189 }
12190 let after: Vec<Retained<NSView>> = state
12193 .pages
12194 .iter()
12195 .take(n.saturating_sub(1))
12196 .cloned()
12197 .collect();
12198 sync_nav_header(hdr, &state.detail_wrap, &after);
12199 }
12200 }
12201 NavPatch::Title(t) => {
12202 if let Some(hdr) = state.header.as_mut() {
12203 if let Some(last) = hdr.titles.last_mut() {
12204 last.clone_from(t);
12205 }
12206 unsafe {
12207 hdr.title.setStringValue(&NSString::from_str(t));
12208 }
12209 }
12210 }
12211 #[expect(
12215 clippy::match_same_arms,
12216 reason = "each no-op patch keeps its own arm and the comment saying why it is one"
12217 )]
12218 NavPatch::GuardTop(_) => {}
12219 NavPatch::Reorder(order) => {
12220 let old = state.pages.clone();
12221 state.pages =
12222 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
12223 if let Some(tabs) = &state.tabs {
12224 TAB_PICK_SUPPRESS.with(|s| s.set(true));
12225 unsafe {
12226 let items = tabs.view.tabViewItems();
12227 for item in &items {
12228 tabs.view.removeTabViewItem(&item);
12229 }
12230 for i in order {
12231 if let Some(item) = items.iter().nth(*i) {
12232 tabs.view.addTabViewItem(&item);
12233 }
12234 }
12235 }
12236 TAB_PICK_SUPPRESS.with(|s| s.set(false));
12237 }
12238 }
12239 #[expect(
12241 clippy::match_same_arms,
12242 reason = "each no-op patch keeps its own arm and the comment saying why it is one"
12243 )]
12244 NavPatch::Presentation(_) => {}
12245 NavPatch::Select(i) => {
12249 state.selected = *i;
12250 match state.tabs.as_ref() {
12251 Some(tabs) => {
12253 let n = unsafe { tabs.view.numberOfTabViewItems() };
12254 if (*i as isize) < n {
12255 TAB_PICK_SUPPRESS.with(|s| s.set(true));
12256 unsafe {
12257 tabs.view.selectTabViewItemAtIndex(*i as isize);
12258 };
12259 TAB_PICK_SUPPRESS.with(|s| s.set(false));
12260 }
12261 }
12262 None => {
12263 for (n, page) in state.pages.iter().enumerate() {
12264 page.setHidden(n != *i);
12265 }
12266 }
12267 }
12268 }
12269 NavPatch::ListVisible(v) => {
12275 state.list_visible = *v;
12276 if let Some(item) = state.list_item.as_ref() {
12277 item.setCollapsed(!*v);
12278 let split = unsafe { state.split_vc.splitView() };
12279 unsafe { split.layoutSubtreeIfNeeded() };
12280 if let Some(w) = take_list_placement(state) {
12285 unsafe {
12286 split.setPosition_ofDividerAtIndex(
12287 day_spec::NAV_SIDEBAR_WIDTH + w,
12288 1,
12289 );
12290 }
12291 }
12292 if *v
12299 && let Some(wrap) = state.list_wrap.as_ref()
12300 && let Some(page) = state.list_page.as_ref()
12301 {
12302 unsafe {
12303 wrap.layoutSubtreeIfNeeded();
12304 page.setFrame(wrap.bounds());
12305 }
12306 }
12307 }
12308 }
12309 NavPatch::ListInStack(_) => {}
12313 }
12314 });
12315 }
12316 }
12317 kinds::COVER => {
12323 if let (Some(p), Ok(page)) = (
12324 patch.downcast_ref::<CoverPatch>(),
12325 h.clone().downcast::<DayNavPage>(),
12326 ) {
12327 let node = page.ivars().node;
12328 match p {
12329 CoverPatch::Present { background, .. } => {
12330 if page.ivars().sheet.get() {
12331 if let Some(parent) =
12332 primary_content().and_then(|v| unsafe { v.window() })
12333 {
12334 let bounds = parent.frame().size;
12335 let max = if page.ivars().large.get() {
12336 day_spec::props::LARGE_SHEET_MAX
12337 } else {
12338 day_spec::props::SHEET_MAX
12339 };
12340 let height = if page.ivars().half.get() {
12341 (bounds.height * 0.5).clamp(160.0, max.height)
12342 } else {
12343 (bounds.height - 80.0).clamp(300.0, max.height)
12344 };
12345 let size = NSSize::new(
12346 (bounds.width - 40.0).clamp(320.0, max.width),
12347 height,
12348 );
12349 let window = unsafe {
12350 NSWindow::initWithContentRect_styleMask_backing_defer(
12351 NSWindow::alloc(MainThreadMarker::new().unwrap()),
12352 NSRect::new(NSPoint::new(0.0, 0.0), size),
12353 NSWindowStyleMask::Titled,
12354 NSBackingStoreType::Buffered,
12355 false,
12356 )
12357 };
12358 unsafe {
12359 window.setReleasedWhenClosed(false);
12360 page.removeFromSuperview();
12361 page.setHidden(false);
12362 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
12363 window.setContentView(Some(&page));
12364 }
12365 let key = ptr_of(h);
12366 SHEET_NODES.with(|t| {
12367 t.insert(Retained::as_ptr(&window) as usize, node)
12368 });
12369 install_sheet_escape_monitor();
12370 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
12371 dispatch2::DispatchQueue::main().exec_async(move || {
12372 ffi_guard::contain((), || {
12373 let window =
12374 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
12375 if let (Some(window), Some(parent)) = (
12376 window,
12377 primary_content()
12378 .and_then(|v| unsafe { v.window() }),
12379 ) {
12380 unsafe {
12381 parent.beginSheet_completionHandler(
12382 &window, None,
12383 );
12384 }
12385 }
12386 });
12387 });
12388 emit(
12389 node,
12390 Event::FrameChanged(Size::new(size.width, size.height)),
12391 );
12392 }
12393 return;
12394 }
12395 page.set_fill(
12399 background.unwrap_or(day_spec::SystemColor::Background.into()),
12400 );
12401 if let Some(content) = primary_content() {
12404 if let Some(window) = unsafe { content.window() } {
12405 toolbar::cover_presented(ptr_of(h), &window);
12406 }
12407 let top = title_bar_inset(&content);
12412 let full = content.frame().size;
12413 page.ivars().top_inset.set(top);
12414 unsafe {
12415 page.removeFromSuperview();
12416 content.addSubview(&page);
12417 page.setFrame(NSRect::new(
12418 NSPoint::new(0.0, -top),
12419 NSSize::new(full.width, full.height),
12420 ));
12421 page.setBoundsOrigin(NSPoint::new(0.0, -top));
12422 page.setAutoresizingMask(
12423 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12424 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12425 );
12426 page.setHidden(false);
12427 }
12428 emit(
12429 node,
12430 Event::FrameChanged(Size::new(
12431 full.width,
12432 (full.height - top).max(0.0),
12433 )),
12434 );
12435 }
12436 }
12437 CoverPatch::DismissDisabled(_) => {}
12438 CoverPatch::Dismiss => {
12439 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
12440 toolbar::cover_dismissed(ptr_of(h));
12441 unsafe {
12442 page.setHidden(true);
12443 page.removeFromSuperview();
12444 }
12445 emit(node, Event::CoverHidden);
12446 }
12447 }
12448 }
12449 }
12450 kinds::PICKER => picker::update_any(self, h, patch),
12451 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
12452 kinds::TEXT_FIELD => {
12453 if let (Some(p), Ok(tf)) = (
12454 patch.downcast_ref::<TextFieldPatch>(),
12455 h.clone().downcast::<NSTextField>(),
12456 ) {
12457 match p {
12458 TextFieldPatch::Text { text, from_native } => {
12459 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
12461 unsafe { tf.setStringValue(&NSString::from_str(text)) };
12462 }
12463 }
12464 TextFieldPatch::Placeholder(t) => unsafe {
12465 tf.setPlaceholderString(Some(&NSString::from_str(t)));
12466 },
12467 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
12468 TextFieldPatch::Select(sel) => {
12472 if let Some(editor) = tf.currentEditor() {
12473 let (start, end) = sel.utf16(&editor.string().to_string());
12474 editor.setSelectedRange(objc2_foundation::NSRange::new(
12475 start,
12476 end - start,
12477 ));
12478 }
12479 }
12480 }
12481 }
12482 }
12483 kinds::SCROLL => {
12484 if let Some(ScrollPatch::Zoom { scale, animated }) =
12485 patch.downcast_ref::<ScrollPatch>()
12486 {
12487 scroll::zoom(h, *scale, *animated);
12488 }
12489 }
12490 kinds::LIST => {
12491 let key = ptr_of(h);
12492 let entry = list_entry(key);
12493 if let Some((table, data)) = &entry {
12496 data.apply_held(table);
12497 }
12498 match patch.downcast_ref::<ListPatch>() {
12499 Some(ListPatch::Splice(deltas)) => {
12500 if let Some((table, data)) = &entry {
12504 data.change_rows(key, table, Some(deltas));
12505 }
12506 post_realize_visible_rows(key);
12507 }
12508 Some(ListPatch::Reload) => {
12509 if let Some((table, data)) = &entry {
12510 data.change_rows(key, table, None);
12511 }
12512 post_realize_visible_rows(key);
12518 }
12519 Some(ListPatch::ScrollToRow(row)) => {
12520 let row = *row;
12523 <AppKit as Platform>::post(Box::new(move || {
12524 if let Some((table, data)) = list_entry(key) {
12525 data.apply_held(&table);
12527 let rows = unsafe { table.numberOfRows() };
12528 if rows > 0 {
12529 unsafe {
12530 table.scrollRowToVisible((row as isize).min(rows - 1));
12531 };
12532 }
12533 }
12534 }));
12535 post_realize_visible_rows(key);
12536 }
12537 Some(ListPatch::ScrollToEnd) => {
12538 <AppKit as Platform>::post(Box::new(move || {
12544 if let Some((table, data)) = list_entry(key) {
12545 data.apply_held(&table);
12547 let rows = unsafe { table.numberOfRows() };
12548 if rows > 0 {
12549 unsafe { table.scrollRowToVisible(rows - 1) };
12550 }
12551 }
12552 }));
12553 post_realize_visible_rows(key);
12555 }
12556 Some(ListPatch::Selected(rows)) => {
12557 if let Some((table, data)) = &entry {
12558 data.select(table, rows);
12559 }
12560 }
12561 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
12562 if let Some((table, data)) = &entry {
12563 data.row_resized(table, *cell, *height);
12564 }
12565 }
12566 Some(ListPatch::Editing(_)) | None => {}
12569 }
12570 }
12571 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
12572 Some(TreePatch::Reload) => {
12573 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
12578 unsafe { outline.reloadData() };
12579 }
12580 post_realize_visible_tree_rows(ptr_of(h));
12581 }
12582 Some(TreePatch::Expand(token, on)) => {
12583 let (key, token, on) = (ptr_of(h), *token, *on);
12588 <AppKit as Platform>::post(Box::new(move || {
12589 if let Some((outline, data)) = tree_entry(key) {
12590 let item = data.intern(token);
12591 data.ivars().suppress.set(true);
12594 unsafe {
12595 if on {
12596 outline.expandItem(Some(&item));
12597 } else {
12598 outline.collapseItem(Some(&item));
12599 }
12600 }
12601 data.ivars().suppress.set(false);
12602 }
12603 day_core::pump_events();
12604 }));
12605 post_realize_visible_tree_rows(ptr_of(h));
12606 }
12607 Some(TreePatch::Selected(tokens)) => {
12608 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
12609 data.ivars().suppress.set(true);
12610 unsafe {
12611 if tokens.is_empty() {
12612 outline.deselectAll(None);
12613 } else {
12614 let set = objc2_foundation::NSMutableIndexSet::new();
12615 for t in tokens {
12616 let row = outline.rowForItem(Some(&data.intern(*t)));
12619 if row >= 0 {
12620 set.addIndex(row as usize);
12621 }
12622 }
12623 outline.selectRowIndexes_byExtendingSelection(&set, false);
12624 }
12625 }
12626 data.ivars().suppress.set(false);
12627 }
12628 }
12629 Some(TreePatch::Reveal(token)) => {
12630 let (key, token) = (ptr_of(h), *token);
12633 <AppKit as Platform>::post(Box::new(move || {
12634 if let Some((outline, data)) = tree_entry(key) {
12635 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
12636 if row >= 0 {
12637 unsafe { outline.scrollRowToVisible(row) };
12638 }
12639 }
12640 }));
12641 post_realize_visible_tree_rows(ptr_of(h));
12642 }
12643 None => {}
12644 },
12645 _ => {
12646 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
12647 update(self, h, patch);
12648 }
12649 }
12650 }
12651 }
12652
12653 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
12655 let f = self.registry.get(kind).and_then(|r| r.release);
12658 if let Some(f) = f {
12659 f(self, h);
12660 }
12661 }
12662 fn release(&mut self, h: Handle) {
12663 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
12664 self.secondary.retain(|w| {
12668 if ptr_of(&w.content) == ptr_of(&h) {
12669 w.window.close();
12670 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
12674 false
12675 } else {
12676 true
12677 }
12678 });
12679 TARGETS.with(|m| {
12680 m.borrow_mut().remove(&ptr_of(&h));
12681 });
12682 LIST_STATE.with(|m| {
12683 m.borrow_mut().remove(&ptr_of(&h));
12684 });
12685 TREE_STATE.with(|m| {
12686 m.borrow_mut().remove(&ptr_of(&h));
12687 });
12688 GESTURES.with(|m| {
12689 m.borrow_mut().remove(&ptr_of(&h));
12690 });
12691 NAV_STATE.with(|m| {
12692 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
12693 unsafe {
12701 nav.split_vc.setNextResponder(None);
12702 let split = nav.split_vc.splitView();
12703 if split.nextResponder().is_some_and(|r| {
12704 core::ptr::eq::<objc2::runtime::AnyObject>(
12705 r.as_ref(),
12706 nav.split_vc.as_ref(),
12707 )
12708 }) {
12709 split.setNextResponder(None);
12710 }
12711 }
12712 }
12713 });
12714 NAV_PAGES.with(|set| {
12715 set.borrow_mut().remove(&ptr_of(&h));
12716 });
12717 SPLIT_STATE.with(|m| {
12718 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
12719 state.split.setDelegate(None);
12720 }
12721 });
12722 INSPECTOR_STATE.with(|m| {
12723 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
12724 unsafe {
12727 insp.split_vc.setNextResponder(None);
12728 let split = insp.split_vc.splitView();
12729 if split.nextResponder().is_some_and(|r| {
12730 core::ptr::eq::<objc2::runtime::AnyObject>(
12731 r.as_ref(),
12732 insp.split_vc.as_ref(),
12733 )
12734 }) {
12735 split.setNextResponder(None);
12736 }
12737 }
12738 }
12739 });
12740 NAV_MENUS.with(|m| {
12741 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
12742 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
12747 }
12748 });
12749 input::forget_disabled_root(ptr_of(&h));
12757 day_spec::sidetable::sweep(ptr_of(&h));
12758 unsafe { h.removeFromSuperview() };
12759 }
12760
12761 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
12762 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
12766 unsafe { content_of(parent).addSubview(child) };
12767 adopt_menu_for_tabs(self.mtm(), child);
12768 return;
12769 }
12770 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
12773 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
12774 let handled = NAV_STATE.with(|m| {
12775 let mut m = m.borrow_mut();
12776 let Some(state) = m.get_mut(&ptr_of(parent)) else {
12777 return false;
12778 };
12779 if page_pane == Some(day_spec::props::Pane::List)
12782 && let Some(wrap) = state.list_wrap.as_ref()
12783 {
12784 state.list_page = Some(child.clone());
12785 unsafe {
12786 child.setFrame(wrap.bounds());
12787 child.setAutoresizingMask(
12788 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12789 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12790 );
12791 wrap.addSubview(child);
12792 }
12793 return true;
12794 }
12795 if is_sidebar_page {
12796 state.sidebar_page = Some(child.clone());
12797 }
12798 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
12804 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
12809 state.pages.push(child.clone());
12810 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
12811 unsafe {
12812 child.setAutoresizingMask(
12813 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12814 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12815 );
12816 item.setView(Some(child));
12817 tabs.view.addTabViewItem(&item);
12818 }
12819 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
12820 sync_tab_labels(tabs, &titles, state.selected);
12821 }
12822 return true;
12823 }
12824 let (wrap, frame) = if to_pane {
12825 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
12826 } else {
12827 state.pages.push(child.clone());
12828 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
12829 (
12830 &state.detail_wrap,
12831 nav_page_frame(&state.detail_wrap, visible),
12832 )
12833 };
12834 unsafe {
12835 child.setFrame(frame);
12836 child.setAutoresizingMask(
12837 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12838 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12839 );
12840 wrap.addSubview(child);
12841 }
12842 true
12843 });
12844 if handled {
12845 return;
12846 }
12847 let split_pane = SPLIT_STATE.with(|m| {
12850 let m = m.borrow();
12851 let Some(state) = m.get(&ptr_of(parent)) else {
12852 return false;
12853 };
12854 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
12855 let wrap = if second {
12856 &state.second_wrap
12857 } else {
12858 &state.first_wrap
12859 };
12860 unsafe {
12861 child.setFrame(wrap.bounds());
12862 child.setAutoresizingMask(
12863 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12864 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12865 );
12866 wrap.addSubview(child);
12867 }
12868 true
12869 });
12870 if split_pane {
12871 return;
12872 }
12873 let inspected = INSPECTOR_STATE.with(|m| {
12876 let m = m.borrow();
12877 let Some(state) = m.get(&ptr_of(parent)) else {
12878 return false;
12879 };
12880 let panel = INSPECTOR_PANES
12881 .with(|t| t.get(ptr_of(child)))
12882 .unwrap_or(false);
12883 let wrap = if panel {
12884 &state.panel_wrap
12885 } else {
12886 &state.content_wrap
12887 };
12888 unsafe {
12889 child.setFrame(wrap.bounds());
12890 child.setAutoresizingMask(
12891 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12892 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12893 );
12894 wrap.addSubview(child);
12895 }
12896 true
12897 });
12898 if !inspected {
12899 unsafe { content_of(parent).addSubview(child) };
12902 }
12903 }
12904
12905 fn remove(&mut self, parent: &Handle, child: &Handle) {
12906 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
12907 let mtm = self.mtm();
12908 NAV_STATE.with(|m| {
12909 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
12910 if let Some(tabs) = state.tabs.as_ref() {
12912 unsafe {
12913 let n = tabs.view.numberOfTabViewItems();
12914 for i in 0..n {
12915 let item = tabs.view.tabViewItemAtIndex(i);
12916 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
12917 tabs.view.removeTabViewItem(&item);
12918 break;
12919 }
12920 }
12921 }
12922 }
12923 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
12924 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
12925 state.sidebar_page = None;
12926 }
12927 }
12928 });
12929 unsafe { child.removeFromSuperview() };
12930 }
12931
12932 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
12933 unsafe { content_of(parent).addSubview(child) };
12934 }
12935
12936 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
12937 match kind {
12938 kinds::LABEL => {
12939 if let Some(tf) = h.downcast_ref::<NSTextField>() {
12940 let w = p.width.unwrap_or(1.0e6);
12941 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
12943 let mut height = s.height.ceil();
12944 if tf.maximumNumberOfLines() == 1
12948 && let Some(font) = unsafe { tf.font() }
12949 {
12950 let fixed = h.downcast_ref::<DayLabel>().and_then(|l| {
12951 label_line_points(
12952 l.ivars().paragraph.get().line_height,
12953 font.pointSize(),
12954 )
12955 });
12956 let line = fixed.unwrap_or_else(|| natural_line_height(&font));
12957 height = height.min(line.ceil());
12958 }
12959 return Size::new(s.width.ceil().min(w), height);
12960 }
12961 Size::ZERO
12962 }
12963 kinds::BUTTON | kinds::TOGGLE => {
12964 let s = unsafe { h.fittingSize() };
12965 Size::new(s.width.ceil(), s.height.ceil())
12966 }
12967 kinds::SLIDER => {
12968 let s = unsafe { h.fittingSize() };
12969 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
12970 }
12971 kinds::PICKER => picker::measure_any(self, h, p),
12972 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
12973 kinds::TEXT_FIELD => {
12974 let s = unsafe { h.fittingSize() };
12975 Size::new(
12976 p.width.unwrap_or(s.width.max(160.0)),
12977 s.height.max(22.0).ceil(),
12978 )
12979 }
12980 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
12981 kinds::LIST_ITEM => {
12984 let s = h.fittingSize();
12985 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
12986 }
12987 kinds::PROGRESS => {
12988 let indeterminate = h
12990 .clone()
12991 .downcast::<NSProgressIndicator>()
12992 .is_ok_and(|pi| unsafe { pi.isIndeterminate() });
12993 if indeterminate {
12994 let large = h
12995 .downcast_ref::<NSProgressIndicator>()
12996 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
12997 let side = if large { 32.0 } else { 20.0 };
12998 Size::new(side, side)
12999 } else {
13000 Size::new(p.width.unwrap_or(180.0), 20.0)
13001 }
13002 }
13003 kinds::NAV_MENU => {
13004 let rows = NAV_MENUS.with(|m| {
13005 m.borrow()
13006 .get(&ptr_of(h))
13007 .map_or(0, |(_, d)| d.ivars().items.borrow().len())
13008 });
13009 Size::new(
13010 p.width.unwrap_or(220.0),
13011 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
13012 )
13013 }
13014 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
13016 _ => {
13017 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
13018 measure(self, h, p)
13019 } else {
13020 let s = unsafe { h.fittingSize() };
13021 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
13022 }
13023 }
13024 }
13025 }
13026
13027 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
13029 motion::set_opacity(h, opacity, anim);
13030 }
13031
13032 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
13033 let from = motion::shown_geometry(h);
13037 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
13038 if let Some(base) = BASE_FRAMES.with(|m| m.get(ptr_of(h))) {
13039 motion::move_geometry(h, from, (base, t), anim, || apply_geometry(h, base, t));
13040 }
13041 }
13042
13043 fn read_displayed(&self, h: &Handle) -> day_spec::Displayed {
13045 motion::displayed(h)
13046 }
13047
13048 fn text_scale(&mut self, _style: Font) -> f64 {
13051 1.0
13052 }
13053
13054 fn set_layout_direction(
13060 &mut self,
13061 h: &Handle,
13062 kind: PieceKind,
13063 direction: day_spec::LayoutDirection,
13064 ) {
13065 use objc2_app_kit::{NSUserInterfaceLayoutDirection as Ui, NSWritingDirection as Writing};
13066 let rtl = direction == day_spec::LayoutDirection::Rtl;
13067 let (ui, writing) = if rtl {
13068 (Ui::RightToLeft, Writing::RightToLeft)
13069 } else {
13070 (Ui::LeftToRight, Writing::LeftToRight)
13071 };
13072 if kind == kinds::TEXT_AREA {
13073 textarea::set_direction(h, ui, writing);
13074 return;
13075 }
13076 if !matches!(
13077 kind,
13078 kinds::LABEL
13079 | kinds::BUTTON
13080 | kinds::TOGGLE
13081 | kinds::SLIDER
13082 | kinds::TEXT_FIELD
13083 | kinds::PICKER
13084 | kinds::PROGRESS
13085 ) {
13086 return;
13087 }
13088 h.setUserInterfaceLayoutDirection(ui);
13089 if let Some(label) = h.downcast_ref::<DayLabel>() {
13090 label.ivars().direction.set(Some(direction));
13091 apply_label_paragraph(label);
13092 return;
13093 }
13094 if let Some(control) = h.downcast_ref::<NSControl>() {
13095 if let Some(cell) = unsafe { control.cell() } {
13096 cell.setUserInterfaceLayoutDirection(ui);
13097 }
13098 if control.isKindOfClass(<NSTextField as objc2::ClassType>::class()) {
13100 unsafe { control.setBaseWritingDirection(writing) };
13101 }
13102 }
13103 }
13104
13105 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
13106 if let Some(label) = h.downcast_ref::<DayLabel>() {
13107 label.ivars().selectable.set(selectable);
13108 label.set_links(label.ivars().has_links.get());
13109 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
13110 unsafe { tf.setSelectable(selectable) };
13111 }
13112 None
13113 }
13114
13115 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
13116 let node = text_field_node(h)?;
13117 let old = h.downcast_ref::<NSTextField>()?;
13118 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
13121 .then(|| self.swap_text_field(h, old, node, traits.secure));
13122 let tf = swapped.as_deref().unwrap_or(old);
13123 unsafe {
13124 tf.setEditable(!traits.read_only);
13127 tf.setSelectable(true);
13128 }
13129 let content_type = match traits.purpose {
13133 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
13134 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
13135 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
13136 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
13137 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
13138 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
13139 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
13140 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
13141 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
13142 };
13143 unsafe {
13144 tf.setContentType(content_type);
13145 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
13148 }
13149 swapped.as_ref().map(view_of)
13152 }
13153
13154 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
13155 let key = Retained::as_ptr(h) as usize;
13156 if cursor == Cursor::Default {
13157 if let Some((owner, area)) = self.cursors.remove(&key) {
13159 unsafe { h.removeTrackingArea(&area) };
13160 if owner.ivars().hiding.replace(false) {
13161 NSCursor::unhide();
13162 }
13163 }
13164 return;
13165 }
13166 let hidden = cursor == Cursor::None;
13167 let shape = if hidden { None } else { ns_cursor(&cursor) };
13168 let mtm = self.mtm;
13169 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
13170 let owner = DayCursorOwner::new(mtm);
13171 let opts = NSTrackingAreaOptions::CursorUpdate
13174 | NSTrackingAreaOptions::MouseEnteredAndExited
13175 | NSTrackingAreaOptions::ActiveInKeyWindow
13176 | NSTrackingAreaOptions::InVisibleRect;
13177 let any: &objc2::runtime::AnyObject = &owner;
13178 let area = unsafe {
13179 NSTrackingArea::initWithRect_options_owner_userInfo(
13180 NSTrackingArea::alloc(),
13181 NSRect::ZERO,
13182 opts,
13183 Some(any),
13184 None,
13185 )
13186 };
13187 unsafe { h.addTrackingArea(&area) };
13188 (owner, area)
13189 });
13190 let changed = {
13191 let iv = owner.ivars();
13192 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
13193 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
13194 (None, None) => true,
13195 _ => false,
13196 };
13197 *iv.cursor.borrow_mut() = shape;
13198 let was_hidden = iv.hidden.replace(hidden);
13199 !same || was_hidden != hidden
13200 };
13201 if changed && let Some(w) = h.window() {
13204 unsafe { w.invalidateCursorRectsForView(h) };
13205 }
13206 }
13207
13208 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
13222 if !day_spec::kind_has_baseline(kind) {
13223 return None;
13224 }
13225 let current = unsafe { h.frame() };
13228 if (current.size.height - size.height).abs() > 0.5 {
13229 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
13230 }
13231 let insets = unsafe { h.alignmentRectInsets() };
13232 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
13233 let font = h
13234 .downcast_ref::<NSControl>()
13235 .and_then(|c| unsafe { c.font() });
13236 let offset = match font {
13237 Some(_) if kind == kinds::TEXT_AREA => reported,
13240 Some(f) => {
13241 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
13242 let line = ascender - descender;
13243 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
13244 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
13245 }
13246 None => reported,
13247 };
13248 (offset > 0.0 && offset < size.height).then_some(offset)
13250 }
13251
13252 fn set_frame(&mut self, h: &Handle, frame: Rect, anim: Option<&AnimSpec>) {
13253 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
13255 return;
13256 }
13257 let r = NSRect::new(
13260 NSPoint::new(frame.origin.x, frame.origin.y),
13261 NSSize::new(frame.size.width, frame.size.height),
13262 );
13263 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
13268 let strip = unsafe { split.superview() }
13272 .and_then(|sup| {
13273 let content = unsafe { sup.window() }?.contentView()?;
13274 let mut ancestor = Some(sup.clone());
13278 while let Some(view) = ancestor {
13279 if std::ptr::eq(&raw const *view, &raw const *content) {
13280 break;
13281 }
13282 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
13283 return None; }
13285 ancestor = unsafe { view.superview() };
13286 }
13287 let point = unsafe {
13288 sup.convertPoint_toView(
13289 NSPoint::new(frame.origin.x, frame.origin.y),
13290 Some(&content),
13291 )
13292 };
13293 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
13294 })
13295 .unwrap_or(0.0);
13296 let r = NSRect::new(
13297 NSPoint::new(r.origin.x, r.origin.y - strip),
13298 NSSize::new(r.size.width, r.size.height + strip),
13299 );
13300 let wraps = NAV_STATE.with(|m| {
13301 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
13302 #[expect(
13303 clippy::float_cmp,
13304 reason = "unchanged-value check against the strip stored last time"
13305 )]
13306 let changed = s.title_strip != strip;
13307 changed.then(|| {
13308 s.title_strip = strip;
13309 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
13310 w.extend(s.list_wrap.clone());
13311 w
13312 })
13313 })
13314 });
13315 let first = NAV_STATE.with(|m| {
13316 m.borrow_mut()
13317 .get_mut(&ptr_of(h))
13318 .map_or((false, None), |s| {
13319 if !s.presentation.is_split() {
13320 return (false, None);
13321 }
13322 let sidebar = !std::mem::replace(&mut s.positioned, true);
13323 (sidebar, take_list_placement(s))
13328 })
13329 });
13330 unsafe {
13331 split.setFrame(r);
13332 split.layoutSubtreeIfNeeded();
13333 }
13334 for wrap in wraps.iter().flatten() {
13337 place_below_strip(wrap, strip);
13338 }
13339 unsafe {
13340 if first.0 {
13341 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
13342 }
13343 if let Some(w) = first.1 {
13348 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
13349 }
13350 }
13351 } else {
13352 let base = [
13353 frame.origin.x,
13354 frame.origin.y,
13355 frame.size.width,
13356 frame.size.height,
13357 ];
13358 let from = motion::shown_geometry(h);
13359 BASE_FRAMES.with(|m| m.insert(ptr_of(h), base));
13360 let t = TRANSFORMS.with(|m| m.get(ptr_of(h)));
13363 let to = (base, t.unwrap_or(Transform::IDENTITY));
13364 motion::move_geometry(h, from, to, anim, || match t {
13365 Some(t) => apply_geometry(h, base, t),
13366 None => h.setFrame(r),
13367 });
13368 }
13369 }
13370
13371 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
13372 if let Some(sv) = h.downcast_ref::<NSScrollView>()
13373 && let Some(doc) = unsafe { sv.documentView() }
13374 {
13375 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
13376 }
13377 }
13378
13379 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
13381 day_spec::RowMetrics {
13382 insets: day_spec::Insets {
13383 top: 4.0,
13384 leading: 8.0,
13385 bottom: 4.0,
13386 trailing: 8.0,
13387 },
13388 min_height: 28.0,
13389 }
13390 }
13391
13392 fn scroll_to(&mut self, h: &Handle, target: Rect, animated: bool) {
13395 if let Some(sv) = h.downcast_ref::<NSScrollView>()
13396 && unsafe { sv.documentView() }.is_some()
13397 {
13398 let bounds = unsafe { sv.contentView() }.bounds();
13399 let to = NSPoint::new(
13400 scroll::reveal_origin(
13401 bounds.origin.x,
13402 bounds.size.width,
13403 target.origin.x,
13404 target.size.width,
13405 ),
13406 scroll::reveal_origin(
13407 bounds.origin.y,
13408 bounds.size.height,
13409 target.origin.y,
13410 target.size.height,
13411 ),
13412 );
13413 scroll::scroll_clip_to(sv, to, animated, None);
13414 }
13415 }
13416
13417 fn scroll_offset(&mut self, h: &Handle) -> Point {
13418 scroll::offset(h)
13419 }
13420
13421 fn list_scroll(&mut self, h: &Handle, to: day_spec::ListScroll) -> bool {
13426 let key = ptr_of(h);
13427 if list_entry(key).is_none() {
13428 return false;
13429 }
13430 <AppKit as Platform>::post(Box::new(move || {
13431 let Some((table, data)) = list_entry(key) else {
13432 return;
13433 };
13434 if data.ivars().live.get() {
13437 return;
13438 }
13439 data.apply_held(&table);
13441 let rows = unsafe { table.numberOfRows() };
13442 let Some(scroll) = table.enclosingScrollView() else {
13443 return;
13444 };
13445 if rows <= 0 {
13446 return;
13447 }
13448 let bounds = unsafe { scroll.contentView() }.bounds();
13449 let y = match to.row {
13450 Some(row) => {
13451 let rect = unsafe { table.rectOfRow((row as isize).min(rows - 1)) };
13452 scroll::row_origin(
13453 bounds.origin.y,
13454 bounds.size.height,
13455 rect.origin.y,
13456 rect.origin.y + rect.size.height,
13457 to.align,
13458 )
13459 }
13460 None => table.frame().size.height - bounds.size.height,
13462 };
13463 let done: Box<dyn FnOnce()> = Box::new(move || post_realize_visible_rows(key));
13464 scroll::scroll_clip_to(
13465 &scroll,
13466 NSPoint::new(bounds.origin.x, y),
13467 to.animated,
13468 Some(done),
13469 );
13470 }));
13471 true
13472 }
13473
13474 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
13475 let Some(window) = h.window() else { return };
13476 let list = list_entry(ptr_of(h));
13478 let responder: &NSResponder = match &list {
13479 Some((table, _)) => table,
13480 None => h,
13481 };
13482 let responder_ptr = std::ptr::from_ref::<NSResponder>(responder) as usize;
13483 if focused {
13484 window.makeFirstResponder(Some(responder));
13485 return;
13486 }
13487 let owns = window
13490 .firstResponder()
13491 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
13492 || owns_first_responder(&window, h);
13493 if owns {
13494 window.makeFirstResponder(None);
13495 }
13496 }
13497
13498 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
13499 if focusable {
13502 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
13503 } else {
13504 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
13505 }
13506 }
13507
13508 fn set_event_sink(&mut self, sink: EventSink) {
13509 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
13510 input::install_monitor();
13512 }
13513
13514 fn set_edit_state(&mut self, state: &day_spec::EditState) {
13515 EDIT_STATE.with(|s| s.set(*state));
13516 }
13517
13518 fn modifiers(&mut self) -> day_spec::Modifiers {
13519 let f = NSEvent::modifierFlags_class();
13520 day_spec::Modifiers::NONE
13521 .with(
13522 day_spec::Modifiers::SHIFT,
13523 f.contains(NSEventModifierFlags::Shift),
13524 )
13525 .with(
13526 day_spec::Modifiers::PRIMARY,
13527 f.contains(NSEventModifierFlags::Command),
13528 )
13529 .with(
13530 day_spec::Modifiers::ALT,
13531 f.contains(NSEventModifierFlags::Option),
13532 )
13533 }
13534
13535 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
13536 let front = undo_front(self.mtm);
13537 *front.ivars().state.borrow_mut() = state.clone();
13538 }
13539
13540 fn attach_list(&mut self, host: &Handle, source: ListSource) {
13541 let key = ptr_of(host);
13542 if let Some((table, data)) = list_entry(key) {
13543 let supplements = source.is_supplement.is_some();
13544 data.ivars().source.replace(Some(source));
13545 data.ivars().held.replace(None);
13547 data.ivars().splice.replace(None);
13548 if data.ivars().supplements.replace(supplements) != supplements {
13549 unsafe {
13552 table.setDelegate(None);
13553 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
13554 }
13555 }
13556 unsafe { table.reloadData() };
13558 }
13559 post_realize_visible_rows(key);
13564 }
13565
13566 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
13567 let key = ptr_of(host);
13568 if let Some((outline, data)) = tree_entry(key) {
13569 data.ivars().source.replace(Some(source));
13570 unsafe { outline.reloadData() };
13572 }
13573 <AppKit as Platform>::post(Box::new(move || {
13576 if let Some((outline, _)) = tree_entry(key) {
13577 unsafe { outline.layoutSubtreeIfNeeded() };
13578 }
13579 }));
13580 }
13581
13582 fn adopt(&mut self, raw: RawHandle) -> Handle {
13583 let ptr = raw.cast::<NSView>();
13587 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
13588 }
13589
13590 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
13591 self.edit_toolbar(h, ops)
13592 }
13593
13594 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
13595 Self::patch_toolbar(h, patch);
13596 }
13597
13598 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
13599 let mtm = self.mtm;
13600 if self.menu_escape_monitor.is_none() {
13601 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
13602 ffi_guard::contain(event.as_ptr(), || {
13603 let event_ref = unsafe { event.as_ref() };
13604 let app = NSApplication::sharedApplication(mtm);
13605 if app.modalWindow().is_none()
13608 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
13609 && unsafe { event_ref.charactersIgnoringModifiers() }
13610 .is_some_and(|s| s.to_string() == "\u{1b}")
13611 && app
13612 .mainMenu()
13613 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
13614 {
13615 std::ptr::null_mut()
13616 } else {
13617 event.as_ptr()
13618 }
13619 })
13620 });
13621 self.menu_escape_monitor = unsafe {
13622 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
13623 objc2_app_kit::NSEventMask::KeyDown,
13624 &block,
13625 )
13626 }
13627 .map(MenuEscapeMonitor);
13628 }
13629 let app = NSApplication::sharedApplication(mtm);
13630 let menubar = NSMenu::new(mtm);
13631 let mut items = items.to_vec();
13634 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
13635 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
13636 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
13637 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
13638 let services =
13639 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
13640 let items =
13645 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
13646 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
13647 for item in &items {
13649 match item {
13650 day_spec::MenuItem::Submenu { label, items, role } => {
13651 let sub = build_ns_menu(mtm, label, items);
13652 let it = NSMenuItem::new(mtm);
13653 if *role == Some(day_spec::MenuBarRole::Help)
13657 || *label == day_localization::t(day_localization::key::day_help)
13658 {
13659 help_menu = Some((label.clone(), sub));
13660 continue;
13661 }
13662 it.setTitle(&NSString::from_str(label));
13663 it.setSubmenu(Some(&sub));
13664 menubar.addItem(&it);
13665 }
13666 other => {
13667 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
13669 let it = NSMenuItem::new(mtm);
13670 it.setSubmenu(Some(&sub));
13671 menubar.addItem(&it);
13672 }
13673 }
13674 }
13675 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
13678 install_windows_menu(mtm, &app, &menubar);
13679 }
13680 if let Some((label, help)) = help_menu {
13681 let it = NSMenuItem::new(mtm);
13682 it.setTitle(&NSString::from_str(&label));
13683 it.setSubmenu(Some(&help));
13684 menubar.addItem(&it);
13685 unsafe { app.setHelpMenu(Some(&help)) };
13688 }
13689 app.setMainMenu(Some(&menubar));
13690 unsafe { app.setServicesMenu(Some(&services)) };
13691 }
13692
13693 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
13694 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
13695 for sub in v.subviews() {
13696 unsafe { sub.setMenu(Some(menu)) };
13697 apply_to_subviews(&sub, menu);
13698 }
13699 }
13700 let Some(view) = h.downcast_ref::<NSView>() else {
13701 return;
13702 };
13703 if items.is_empty() {
13704 unsafe { view.setMenu(None) };
13705 return;
13706 }
13707 let menu = build_ns_menu(self.mtm, "", items);
13708 unsafe { view.setMenu(Some(&menu)) };
13714 apply_to_subviews(view, &menu);
13715 }
13716
13717 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
13718 transfer::source(h, source);
13719 }
13720 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
13721 transfer::target(h, target);
13722 }
13723 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
13724 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
13727 }
13728
13729 fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
13730 let Some(btn) = h.downcast_ref::<NSButton>() else {
13731 return;
13732 };
13733 unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
13737 BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
13738 }
13739
13740 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
13741 let key = ptr_of(h);
13742 if kind == day_spec::GestureKind::Pan {
13746 PAN_NODES.with(|t| t.insert(key, node));
13747 install_container_pan_monitor();
13748 return;
13749 }
13750 if kind == day_spec::GestureKind::Rotate {
13754 ROTATE_NODES.with(|t| t.insert(key, node));
13755 return;
13756 }
13757 if kind == day_spec::GestureKind::Hover {
13761 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
13765 HOVER_NODES.with(|t| t.insert(key, node));
13766 if first {
13767 input::install_hover_area(h);
13771 }
13772 return;
13773 }
13774 if kind == day_spec::GestureKind::Press {
13779 input::PRESS_NODES.with(|t| t.insert(key, node));
13780 input::install_monitor();
13781 return;
13782 }
13783 if kind == day_spec::GestureKind::Touches {
13786 return;
13787 }
13788 let already = GESTURES.with(|m| {
13790 m.borrow()
13791 .get(&key)
13792 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
13793 });
13794 if already {
13795 return;
13796 }
13797 let mtm = self.mtm;
13798 let target = DayGesture::new(mtm, node, kind);
13799 let recognizer: Retained<NSGestureRecognizer> = unsafe {
13800 match kind {
13801 day_spec::GestureKind::Drag => {
13802 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
13803 NSPanGestureRecognizer::alloc(mtm),
13804 Some(&target),
13805 Some(sel!(fire:)),
13806 ))
13807 }
13808 day_spec::GestureKind::Pinch => Retained::into_super(
13809 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
13810 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
13811 Some(&target),
13812 Some(sel!(fire:)),
13813 ),
13814 ),
13815 day_spec::GestureKind::LongPress => {
13819 let press = NSPressGestureRecognizer::initWithTarget_action(
13820 NSPressGestureRecognizer::alloc(mtm),
13821 Some(&target),
13822 Some(sel!(fire:)),
13823 );
13824 press.setDelaysPrimaryMouseButtonEvents(false);
13825 press.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13826 Retained::into_super(press)
13827 }
13828 day_spec::GestureKind::DoubleTap => {
13832 let double = NSClickGestureRecognizer::initWithTarget_action(
13833 NSClickGestureRecognizer::alloc(mtm),
13834 Some(&target),
13835 Some(sel!(fire:)),
13836 );
13837 double.setNumberOfClicksRequired(2);
13838 double.setDelaysPrimaryMouseButtonEvents(false);
13839 double.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13840 Retained::into_super(double)
13841 }
13842 _ => {
13843 let click = NSClickGestureRecognizer::initWithTarget_action(
13844 NSClickGestureRecognizer::alloc(mtm),
13845 Some(&target),
13846 Some(sel!(fire:)),
13847 );
13848 click.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13849 Retained::into_super(click)
13850 }
13851 }
13852 };
13853 unsafe { h.addGestureRecognizer(&recognizer) };
13854 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
13855 }
13856
13857 fn gesture_support(&self, kind: day_spec::GestureKind) -> Support {
13861 match kind {
13862 day_spec::GestureKind::Touches => Support::Unsupported,
13863 _ => Support::Native,
13864 }
13865 }
13866
13867 fn set_hit_slop(&mut self, h: &Handle, _node: NodeId, slop: day_spec::Insets) {
13868 input::set_hit_slop(h, slop);
13869 }
13870
13871 fn set_drag_axis(&mut self, _h: &Handle, _node: NodeId, _axis: Option<day_spec::DragAxis>) {}
13877
13878 fn set_subtree_enabled(&mut self, h: &Handle, _node: NodeId, enabled: bool) {
13879 input::set_subtree_enabled(h, enabled);
13880 }
13881
13882 fn primary_pointer(&self) -> day_spec::PointerKind {
13884 input::pointer_kind()
13885 }
13886
13887 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
13888 unsafe {
13889 if let Some(id) = &a11y.identifier {
13890 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
13891 }
13892 if let Some(label) = &a11y.label {
13893 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
13894 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
13895 } else {
13896 APP_LABELED.with(|t| t.remove(ptr_of(h)));
13897 }
13898 if let Some(hint) = &a11y.hint {
13899 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
13900 }
13901 if let Some(value) = &a11y.value {
13902 let ns = NSString::from_str(value);
13903 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
13904 }
13905 if let Some(role) = ns_role(a11y.role) {
13908 h.setAccessibilityRole(Some(role));
13909 }
13910 if a11y.role == day_spec::Role::Tab {
13911 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
13912 }
13913 if let Some(on) = a11y.selected {
13914 h.setAccessibilitySelected(on);
13915 }
13916 if a11y.hidden {
13922 h.setAccessibilityElement(false);
13923 h.setAccessibilityChildren(Some(&NSArray::new()));
13924 }
13925 }
13926 }
13927
13928 fn announce(&mut self, text: &str, urgent: bool) {
13932 use objc2_app_kit::{
13933 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
13934 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
13935 NSAccessibilityPriorityLevel,
13936 };
13937 let app = NSApplication::sharedApplication(self.mtm());
13938 let window = primary_content().and_then(|content| content.window());
13939 let element: &objc2::runtime::AnyObject = match &window {
13940 Some(window) => window,
13941 None => &app,
13942 };
13943 let priority = if urgent {
13945 NSAccessibilityPriorityLevel::High
13946 } else {
13947 NSAccessibilityPriorityLevel::Medium
13948 };
13949 let announcement = NSString::from_str(text);
13950 let priority = NSNumber::new_isize(priority.0);
13951 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
13952 unsafe {
13955 let user_info = NSDictionary::from_slices::<NSString>(
13956 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
13957 &values,
13958 );
13959 NSAccessibilityPostNotificationWithUserInfo(
13960 element,
13961 NSAccessibilityAnnouncementRequestedNotification,
13962 Some(&user_info),
13963 );
13964 }
13965 }
13966
13967 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
13968 unsafe {
13969 let role = h
13970 .accessibilityRole()
13971 .map_or(day_spec::Role::None, |r| day_role_from_ns(&r.to_string()));
13972 let picker = picker::read_native(h);
13975 day_spec::NativeSnapshot {
13976 found: true,
13977 role,
13978 label: h.accessibilityLabel().map(|s| s.to_string()),
13979 value: h.accessibilityValue().and_then(|v| {
13980 v.downcast_ref::<NSString>()
13981 .map(std::string::ToString::to_string)
13982 }),
13983 identifier: h
13984 .accessibilityIdentifier()
13985 .map(|s| s.to_string())
13986 .filter(|s| !s.is_empty()),
13987 text: match &picker {
13988 Some((text, _)) => text.clone(),
13989 None => native_text(h),
13990 },
13991 number: native_number(h),
13992 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
13993 match sw.state() {
13994 s if s == NSControlStateValueOn => Some(true),
13995 s if s == NSControlStateValueOff => Some(false),
13996 _ => None,
13998 }
13999 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
14000 BUTTON_SELECTED
14003 .with(|m| m.borrow().contains_key(&ptr_of(h)))
14004 .then(|| btn.state() == NSControlStateValueOn)
14005 } else {
14006 None
14007 },
14008 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
14011 (Some((_, on)), _) => *on,
14012 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
14013 (None, Some(c)) => Some(c.isEnabled()),
14014 (None, None) => None,
14015 },
14016 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
14018 frame: native_frame(h),
14019 }
14020 }
14021 }
14022
14023 fn request_frame(
14024 &mut self,
14025 host: &Handle,
14026 cb: day_spec::FrameCallback,
14027 ) -> day_spec::CancelFrame {
14028 frame::request(host, cb)
14029 }
14030
14031 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
14032 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
14033 unsafe { h.setNeedsDisplay(true) };
14034 }
14035 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
14036 NAV_STATE.with(|m| {
14037 let m = m.borrow();
14038 let Some(st) = m.get(&ptr_of(host)) else {
14039 return false;
14040 };
14041 if !matches!(
14044 st.presentation,
14045 NavPresentation::Split | NavPresentation::Rail
14046 ) {
14047 return false;
14048 }
14049 let item = &st.sidebar_item;
14050 let collapsed = unsafe { item.isCollapsed() };
14056 unsafe { item.setCollapsed(!collapsed) };
14057 true
14058 })
14059 }
14060
14061 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
14062 let content = self.content.as_ref().ok_or("no window content")?;
14063 match self.shown_document_content(content) {
14064 Some(shown) => snapshot_view(&shown),
14065 None => snapshot_view(content),
14066 }
14067 }
14068
14069 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
14075 use objc2::AllocAnyThread as _;
14076 let data = NSData::with_bytes(bytes);
14077 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
14078 else {
14079 emit(
14080 WINDOW_NODE,
14081 Event::ImageDecoded {
14082 req,
14083 result: Err(day_spec::ImageError::Decode),
14084 },
14085 );
14086 return;
14087 };
14088 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
14089 let info = day_spec::BitmapInfo {
14090 pixels: Size::new(w, h),
14091 scale: 1.0,
14094 format: day_spec::ImageFormat::sniff(bytes),
14095 has_alpha: unsafe { rep.hasAlpha() },
14096 };
14097 let image = unsafe {
14101 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
14102 };
14103 unsafe { image.addRepresentation(&rep) };
14104 BITMAPS.with(|m| {
14105 m.borrow_mut().insert(
14106 id.0,
14107 AppKitBitmap {
14108 image,
14109 rep: Some(rep),
14110 info,
14111 },
14112 )
14113 });
14114 emit(
14115 WINDOW_NODE,
14116 Event::ImageDecoded {
14117 req,
14118 result: Ok(info),
14119 },
14120 );
14121 }
14122
14123 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
14124 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
14125 }
14126
14127 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
14134 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
14135 let mut out = day_spec::ImageProperties::default();
14136 let size = unsafe { rep.size() };
14137 if size.width > 0.0 {
14138 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
14139 if (dpi - 72.0).abs() > 0.5 {
14142 out.dpi = Some(dpi);
14143 }
14144 }
14145 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
14149 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
14150 for key in &keys {
14151 let value: Option<Retained<objc2::runtime::AnyObject>> =
14152 unsafe { msg_send![&*exif, objectForKey: &*key] };
14153 let Some(value) = value else { continue };
14154 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
14155 let (k, v) = (key.to_string(), text.to_string());
14156 match k.as_str() {
14157 "Orientation" => out.orientation = v.parse().ok(),
14158 "DateTimeOriginal" => out.created = Some(v.clone()),
14159 _ => {}
14160 }
14161 out.extra.push((k, v));
14164 }
14165 }
14166 Some(out)
14167 }
14168
14169 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
14173 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
14174 vec![Png, Jpeg, Tiff, Bmp, Gif]
14175 }
14176
14177 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
14178 let result = encode_bitmap(id, spec);
14179 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
14180 }
14181
14182 fn release_image(&mut self, id: day_spec::BitmapId) {
14183 release_bitmap(id);
14184 }
14185
14186 fn render_bitmap(
14196 &mut self,
14197 req: u64,
14198 id: day_spec::BitmapId,
14199 ops: &[DrawOp],
14200 size: Size,
14201 scale: f64,
14202 ) {
14203 let resources = Sendable(OffscreenResources::collect(ops));
14204 let ops = ops.to_vec();
14205 day_spec::offscreen::spawn(move || {
14206 let resources = resources;
14208 let painted = day_spec::ffi_guard::contain(
14209 Err(day_spec::ExportError::Failed(
14210 "the offscreen painter panicked".into(),
14211 )),
14212 || {
14213 let started = std::time::Instant::now();
14214 let painted = resources
14215 .0
14216 .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
14217 log::debug!(
14219 "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
14220 size.width * scale,
14221 size.height * scale,
14222 started.elapsed().as_secs_f64() * 1000.0,
14223 ops.len()
14224 );
14225 painted
14226 },
14227 );
14228 let painted = Sendable(painted);
14229 <AppKit as Platform>::post(Box::new(move || {
14230 let painted = painted;
14231 let result = painted.0.map(|cg_image| {
14232 let bitmap = bitmap_from_cgimage(&cg_image, scale);
14233 let info = bitmap.info;
14234 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
14235 info
14236 });
14237 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
14238 }));
14239 });
14240 }
14241
14242 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
14243 let result = render_pdf_bytes(pages, info);
14244 emit(WINDOW_NODE, Event::PdfRendered { req, result });
14245 }
14246
14247 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
14251 use day_spec::FontWeight as W;
14252 let mtm =
14253 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
14254 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
14255 let mut out = Vec::new();
14256 for family in &unsafe { manager.availableFontFamilies() } {
14257 let name = family.to_string();
14258 if name.starts_with('.') {
14259 continue;
14260 }
14261 let mut faces = Vec::new();
14262 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
14263 for member in &members {
14264 if member.count() < 4 {
14265 continue;
14266 }
14267 let style = member
14268 .objectAtIndex(1)
14269 .downcast_ref::<NSString>()
14270 .map_or_default(std::string::ToString::to_string);
14271 let weight = member
14272 .objectAtIndex(2)
14273 .downcast_ref::<objc2_foundation::NSNumber>()
14274 .map_or(5, objc2_foundation::NSNumber::integerValue);
14275 let traits = member
14276 .objectAtIndex(3)
14277 .downcast_ref::<objc2_foundation::NSNumber>()
14278 .map_or(0, objc2_foundation::NSNumber::integerValue);
14279 let weight = match weight {
14280 ..=2 => W::UltraLight,
14281 3 => W::Thin,
14282 4 => W::Light,
14283 5 => W::Regular,
14284 6 => W::Medium,
14285 7 | 8 => W::Semibold,
14286 9 => W::Bold,
14287 10 | 11 => W::Heavy,
14288 _ => W::Black,
14289 };
14290 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
14292 name: if style.is_empty() {
14293 day_spec::FontFace::synthesized_name(weight, italic)
14294 } else {
14295 style
14296 },
14297 weight,
14298 italic,
14299 });
14300 }
14301 }
14302 out.push(day_spec::FontFamilyInfo {
14303 family: name,
14304 faces,
14305 });
14306 }
14307 out
14308 }
14309
14310 fn measure_text(
14313 &mut self,
14314 text: &str,
14315 size: f64,
14316 font: &day_spec::CanvasFont,
14317 ) -> Option<day_spec::TextMetrics> {
14318 let nsfont = canvas_nsfont(size, font);
14319 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
14320 let ns = NSString::from_str(text);
14321 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
14322 let unbounded = NSSize::new(f64::MAX, f64::MAX);
14326 let ink: NSRect = unsafe {
14327 msg_send![
14328 &ns,
14329 boundingRectWithSize: unbounded,
14330 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
14331 attributes: &*attrs,
14332 ]
14333 };
14334 Some(day_spec::TextMetrics::from_baseline(
14335 sz.width,
14336 nsfont.ascender(),
14337 sz.height - nsfont.ascender(),
14338 nsfont.capHeight(),
14339 day_spec::Rect::new(
14340 ink.origin.x,
14341 -(ink.origin.y + ink.size.height),
14342 ink.size.width,
14343 ink.size.height,
14344 ),
14345 ))
14346 }
14347
14348 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
14349 let content = self.content.as_ref().ok_or("no window content")?;
14350 match self.shown_document_content(content) {
14351 Some(shown) => snapshot_view_chrome(&shown),
14352 None => snapshot_view_chrome(content),
14353 }
14354 }
14355
14356 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
14357 snapshot_view(host)
14358 }
14359
14360 fn open_window(
14361 &mut self,
14362 id: NodeId,
14363 options: &WindowOptions,
14364 kind: day_spec::WindowKind,
14365 ) -> day_spec::WindowOpenReply<Handle> {
14366 let prefs = kind.is_panel();
14367 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
14368 if prefs {
14369 window.center();
14372 unsafe { window.setExcludedFromWindowsMenu(true) };
14373 } else {
14374 let from = match self.cascade {
14382 Some(p) => p,
14383 None => self.window.as_ref().map_or(NSPoint::new(0.0, 0.0), |w| {
14384 let f = w.frame();
14385 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
14386 unsafe { w.cascadeTopLeftFromPoint(top_left) }
14389 }),
14390 };
14391 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
14392 }
14393 window_chrome::place(&window, options.placement);
14394 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
14399 center_on_screen_of(&window, self.window.as_deref());
14400 }
14401 let _ = pin_below_title_bar(&window);
14404 if !options.start_hidden {
14405 window.makeKeyAndOrderFront(None);
14406 }
14407 mark_tree_needs_display(&content);
14410 self.secondary.push(SecondaryWin {
14411 window,
14412 delegate,
14413 content: content.clone(),
14414 });
14415 day_spec::WindowOpenReply::Open(content)
14416 }
14417
14418 fn native_window_tabs(&self) -> bool {
14419 true
14420 }
14421 fn group_windows(&mut self, hosts: &[Handle]) {
14422 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
14423 let Some(first) = windows.first() else {
14424 return;
14425 };
14426 unsafe {
14427 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
14428 }
14429 for window in windows.iter().skip(1) {
14431 unsafe {
14432 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
14433 }
14434 }
14435 if let Some(group) = first.tabGroup() {
14436 if !group.isTabBarVisible() {
14437 unsafe {
14438 first.toggleTabBar(None);
14439 }
14440 }
14441 for (i, window) in windows.iter().enumerate() {
14442 group.insertWindow_atIndex(window, i as isize);
14443 }
14444 }
14445 for window in &windows {
14448 if let Some(size) = pin_below_title_bar(window) {
14449 let node = window
14450 .delegate()
14451 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
14452 .and_then(|d| d.ivars().node)
14453 .unwrap_or(WINDOW_NODE);
14454 emit(node, Event::WindowResized(size));
14455 }
14456 }
14457 }
14458 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
14459 let Some(window) = self.ns_window_for(host) else {
14460 return Vec::new();
14461 };
14462 let windows = window.tabGroup().map(|g| g.windows());
14463 let Some(windows) = windows else {
14464 return Vec::new();
14465 };
14466 windows
14467 .iter()
14468 .filter_map(|window| {
14469 self.secondary
14470 .iter()
14471 .find(|w| std::ptr::eq(&raw const *w.window, &raw const *window))
14472 .and_then(|w| w.delegate.ivars().node)
14473 })
14474 .collect()
14475 }
14476
14477 fn close_window(&mut self, host: &Handle) {
14478 if let Some(w) = self
14481 .secondary
14482 .iter()
14483 .find(|w| ptr_of(&w.content) == ptr_of(host))
14484 {
14485 w.window.close();
14486 }
14487 }
14488
14489 fn focus_window(&mut self, host: &Handle) {
14490 if let Some(w) = self
14491 .secondary
14492 .iter()
14493 .find(|w| ptr_of(&w.content) == ptr_of(host))
14494 {
14495 w.window.makeKeyAndOrderFront(None);
14496 }
14497 }
14498
14499 fn fit_window(&mut self, host: &Handle, size: Size) {
14500 let Some(w) = self
14501 .secondary
14502 .iter()
14503 .find(|w| ptr_of(&w.content) == ptr_of(host))
14504 else {
14505 return;
14506 };
14507 unsafe {
14508 w.window
14512 .setContentSize(NSSize::new(size.width, size.height));
14513 let mask = w.window.styleMask();
14517 w.window
14518 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
14519 w.window.center();
14520 }
14521 center_on_screen_of(&w.window, self.window.as_deref());
14522 }
14523
14524 fn set_window_title(&mut self, host: &Handle, title: &str) {
14525 if let Some(w) = self
14526 .secondary
14527 .iter()
14528 .find(|w| ptr_of(&w.content) == ptr_of(host))
14529 {
14530 w.window.setTitle(&NSString::from_str(title));
14531 return;
14532 }
14533 if self
14537 .content
14538 .as_ref()
14539 .is_some_and(|c| ptr_of(c) == ptr_of(host))
14540 && let Some(w) = self.window.as_ref()
14541 {
14542 w.setTitle(&NSString::from_str(title));
14543 }
14544 }
14545
14546 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
14547 use day_spec::WindowChange as C;
14548 let Some(window) = self.ns_window_for(host) else {
14549 return;
14550 };
14551 match change {
14552 C::State(state) => set_ns_window_state(&window, *state),
14553 C::ContentProtected(on) => window.setSharingType(if *on {
14555 objc2_app_kit::NSWindowSharingType::None
14556 } else {
14557 objc2_app_kit::NSWindowSharingType::ReadOnly
14558 }),
14559 other => window_chrome::apply_property(&window, other),
14560 }
14561 }
14562
14563 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
14564 self.ns_window_for(host)
14565 .map(|w| window_chrome::frame_of(&w))
14566 }
14567
14568 fn monitors(&self) -> Vec<day_spec::Monitor> {
14569 window_chrome::monitors(self.mtm)
14570 }
14571
14572 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
14575
14576 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
14577 dock::set_app_items(self.mtm, items);
14578 }
14579
14580 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
14581 window_chrome::set_drag_region(h, drag);
14582 }
14583
14584 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
14585 status_item::set_items(self.mtm, items);
14586 }
14587
14588 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
14589 status_item::set_progress(self.mtm, progress);
14590 }
14591
14592 fn set_dock_visible(&mut self, visible: bool) {
14593 status_item::set_dock_visible(self.mtm, visible);
14594 }
14595
14596 fn set_keep_running(&mut self, keep: bool) {
14597 status_item::set_keep_running(keep);
14598 }
14599
14600 fn quit_app(&mut self) {
14601 let app = NSApplication::sharedApplication(self.mtm);
14602 unsafe { app.terminate(None) };
14603 }
14604
14605 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
14606 use present::PresentSpec;
14607 let mtm = self.mtm;
14608 let app = NSApplication::sharedApplication(mtm);
14612 let key = app.keyWindow().filter(|k| {
14613 let mut owner = k.clone();
14614 while let Some(parent) = owner.sheetParent() {
14615 owner = parent;
14616 }
14617 self.window
14618 .as_deref()
14619 .is_some_and(|w| std::ptr::eq(w, &raw const *owner))
14620 || self
14621 .secondary
14622 .iter()
14623 .any(|s| std::ptr::eq(&raw const *s.window, &raw const *owner))
14624 });
14625 let Some(mut window) = key.or_else(|| self.window.clone()) else {
14626 emit(
14627 WINDOW_NODE,
14628 Event::PresentResult {
14629 req,
14630 result: present::PresentResult::Dismissed,
14631 },
14632 );
14633 return;
14634 };
14635 while let Some(sheet) = window.attachedSheet() {
14637 window = sheet;
14638 }
14639 match spec {
14641 PresentSpec::OpenFile {
14642 filters, multiple, ..
14643 } => {
14644 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
14645 unsafe {
14646 panel.setCanChooseFiles(true);
14647 panel.setCanChooseDirectories(false);
14648 panel.setAllowsMultipleSelection(*multiple);
14649 panel.setMessage(Some(&NSString::from_str(spec.title())));
14650 }
14651 apply_allowed_file_types(&panel, filters);
14652 let p = panel.clone();
14653 let handler: block2::RcBlock<dyn Fn(isize)> =
14656 block2::RcBlock::new(move |resp: isize| {
14657 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
14658 });
14659 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14660 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
14661 return;
14662 }
14663 PresentSpec::OpenFolder { .. } => {
14665 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
14666 unsafe {
14667 panel.setCanChooseFiles(false);
14668 panel.setCanChooseDirectories(true);
14669 panel.setCanCreateDirectories(true);
14670 panel.setAllowsMultipleSelection(false);
14671 panel.setMessage(Some(&NSString::from_str(spec.title())));
14672 }
14673 let p = panel.clone();
14674 let handler: block2::RcBlock<dyn Fn(isize)> =
14675 block2::RcBlock::new(move |resp: isize| {
14676 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
14677 });
14678 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14679 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
14680 return;
14681 }
14682 PresentSpec::SaveFile { suggested_name, .. } => {
14683 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
14684 unsafe {
14685 panel.setMessage(Some(&NSString::from_str(spec.title())));
14686 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
14687 }
14688 apply_allowed_file_types(&panel, spec.filters());
14689 let p = panel.clone();
14690 let handler: block2::RcBlock<dyn Fn(isize)> =
14691 block2::RcBlock::new(move |resp: isize| {
14692 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
14694 });
14695 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14696 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
14697 return;
14698 }
14699 _ => {}
14700 }
14701 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
14702 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
14703 if let Some(msg) = spec.message() {
14704 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
14705 }
14706 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
14708 PresentSpec::Dialog { buttons, .. } => {
14709 if buttons
14710 .iter()
14711 .any(|b| b.role == present::ButtonRole::Destructive)
14712 {
14713 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
14714 }
14715 for b in buttons {
14716 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
14717 }
14718 block2::RcBlock::new(move |resp: isize| {
14719 ffi_guard::contain((), || {
14720 let idx = resp - 1000;
14722 emit(
14723 WINDOW_NODE,
14724 Event::PresentResult {
14725 req,
14726 result: present::PresentResult::Button(idx as i64),
14727 },
14728 );
14729 PRESENT_ALERTS.with(|m| {
14730 m.borrow_mut().remove(&req);
14731 });
14732 });
14733 })
14734 }
14735 PresentSpec::Prompt {
14736 placeholder,
14737 initial,
14738 ok,
14739 cancel,
14740 ..
14741 } => {
14742 let tf = unsafe { NSTextField::new(mtm) };
14743 unsafe {
14744 tf.setFrame(NSRect::new(
14745 NSPoint::new(0.0, 0.0),
14746 NSSize::new(260.0, 24.0),
14747 ));
14748 tf.setEditable(true);
14749 tf.setBezeled(true);
14750 tf.setStringValue(&NSString::from_str(initial));
14751 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
14752 alert.setAccessoryView(Some(&tf));
14753 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
14756 block2::RcBlock::new(move |resp: isize| {
14757 ffi_guard::contain((), || {
14758 let result = if resp == 1000 {
14759 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
14760 } else {
14761 present::PresentResult::Dismissed
14762 };
14763 emit(WINDOW_NODE, Event::PresentResult { req, result });
14764 PRESENT_ALERTS.with(|m| {
14765 m.borrow_mut().remove(&req);
14766 });
14767 });
14768 })
14769 }
14770 PresentSpec::OpenFile { .. }
14772 | PresentSpec::OpenFolder { .. }
14773 | PresentSpec::SaveFile { .. } => unreachable!(),
14774 };
14775 unsafe {
14776 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
14777 }
14778 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
14779 }
14780
14781 fn dismiss(&mut self, req: u64) {
14782 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
14785 if let Some(alert) = alert {
14786 let sheet = alert.window();
14787 if let Some(parent) = sheet.sheetParent() {
14788 unsafe { parent.endSheet(&sheet) };
14789 }
14790 }
14791 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
14793 if let Some(panel) = panel
14794 && let Some(parent) = panel.sheetParent()
14795 {
14796 unsafe { parent.endSheet(&panel) };
14797 }
14798 }
14799
14800 fn application_handlers(
14801 &mut self,
14802 query: &day_spec::applications::HandlerQuery,
14803 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
14804 {
14805 applications::handlers(query)
14806 }
14807
14808 fn open_url_with_application(
14809 &mut self,
14810 url: &str,
14811 application: &str,
14812 completion: day_spec::applications::OpenApplicationCompletion,
14813 ) {
14814 applications::open(url, application, completion);
14815 }
14816
14817 fn share_support(&self) -> day_spec::Support {
14818 day_spec::Support::Native
14819 }
14820 fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
14821 use objc2::{msg_send, runtime::AnyObject};
14822 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
14823 let Some(mtm) = objc2::MainThreadMarker::new() else {
14824 return false;
14825 };
14826 let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
14827 return false;
14828 };
14829 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
14830 let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
14831 return false;
14832 };
14833 unsafe {
14834 let items = NSArray::from_retained_slice(&[url]);
14835 let picker: objc2::rc::Allocated<AnyObject> =
14836 msg_send![objc2::class!(NSSharingServicePicker), alloc];
14837 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
14838 let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
14839 actions: spec.actions.clone(),
14840 });
14841 let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
14842 let _: () = msg_send![&*picker, setDelegate: &*delegate];
14843 let (view, rect, edge) = if let Some(view) = anchor {
14846 (view.clone(), view.bounds(), 1usize)
14847 } else {
14848 let bounds = window_view.bounds();
14849 let y = if window_view.isFlipped() {
14850 30.0
14851 } else {
14852 bounds.size.height - 30.0
14853 };
14854 let rect = NSRect::new(
14855 NSPoint::new(bounds.size.width - 30.0, y),
14856 NSSize::new(1.0, 1.0),
14857 );
14858 (window_view, rect, 3usize)
14859 };
14860 let _: () =
14861 msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
14862 self.sharing = Some(picker);
14864 self.sharing_delegate = Some(delegate);
14865 }
14866 true
14867 }
14868 fn open_url(&mut self, url: &str) {
14869 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
14872 if let Some(nsurl) = nsurl {
14873 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
14874 }
14875 }
14876}
14877
14878#[allow(deprecated)]
14881fn apply_allowed_file_types(
14882 panel: &objc2_app_kit::NSSavePanel,
14883 filters: &[day_spec::present::FileFilter],
14884) {
14885 let exts: Vec<Retained<NSString>> = filters
14886 .iter()
14887 .flat_map(|f| f.extensions.iter())
14888 .map(|e| NSString::from_str(e))
14889 .collect();
14890 if !exts.is_empty() {
14891 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
14892 let arr = objc2_foundation::NSArray::from_slice(&refs);
14893 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
14894 }
14895}
14896
14897fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
14901 let mut paths = Vec::new();
14902 if resp == 1 {
14903 for url in &unsafe { panel.URLs() } {
14904 if let Some(p) = unsafe { url.path() } {
14905 paths.push(p.to_string());
14906 }
14907 }
14908 }
14909 let result = if paths.is_empty() {
14910 present::PresentResult::Dismissed
14911 } else {
14912 present::PresentResult::Files(paths)
14913 };
14914 emit(WINDOW_NODE, Event::PresentResult { req, result });
14915 PRESENT_PANELS.with(|m| {
14916 m.borrow_mut().remove(&req);
14917 });
14918}
14919
14920fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
14922 let result = if resp == 1 {
14923 unsafe { panel.URL() }
14924 .and_then(|url| unsafe { url.path() })
14925 .map_or(present::PresentResult::Dismissed, |p| {
14926 present::PresentResult::Files(vec![p.to_string()])
14927 })
14928 } else {
14929 present::PresentResult::Dismissed
14930 };
14931 emit(WINDOW_NODE, Event::PresentResult { req, result });
14932 PRESENT_PANELS.with(|m| {
14933 m.borrow_mut().remove(&req);
14934 });
14935}
14936
14937impl Platform for AppKit {
14938 const TARGET: &'static str = "macos-appkit";
14939 const TOOLKIT: &'static str = "appkit";
14940
14941 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
14942 let mtm = self.mtm;
14943 self.app_name = options
14947 .app_name
14948 .clone()
14949 .unwrap_or_else(|| options.title.clone());
14950 unsafe {
14959 objc2_foundation::NSProcessInfo::processInfo()
14960 .setProcessName(&NSString::from_str(&self.app_name));
14961 let bundle = objc2_foundation::NSBundle::mainBundle();
14962 let info: Option<Retained<objc2_foundation::NSDictionary>> =
14963 msg_send![&bundle, infoDictionary];
14964 if let Some(info) = info {
14965 let key = NSString::from_str("CFBundleName");
14966 let value = NSString::from_str(&self.app_name);
14967 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
14971 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
14972 }
14973 }
14974 }
14975 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
14980 unsafe {
14981 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
14982 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
14983 .into_super()
14984 .into_super()
14985 .into_super();
14986 let dict = NSDictionary::from_retained_objects(
14987 &[
14988 &*NSString::from_str("AppleTextDirection"),
14989 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
14990 ],
14991 &[yes.clone(), yes],
14992 );
14993 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
14994 }
14995 }
14996 let app = NSApplication::sharedApplication(mtm);
14997 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
15000 || unsafe {
15001 let bundle = objc2_foundation::NSBundle::mainBundle();
15002 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
15003 &bundle,
15004 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
15005 ];
15006 value.is_some_and(|v| {
15007 let on: bool = msg_send![&v, boolValue];
15008 on
15009 })
15010 };
15011 app.setActivationPolicy(if menu_bar_app {
15012 NSApplicationActivationPolicy::Accessory
15013 } else {
15014 NSApplicationActivationPolicy::Regular
15015 });
15016 let document_delegate = documents::delegate(mtm);
15017 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
15018 if let Ok(theme) = std::env::var("DAY_THEME") {
15021 let name = match theme.as_str() {
15022 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
15023 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
15024 _ => None,
15025 };
15026 if let Some(name) = name {
15027 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
15028 unsafe { app.setAppearance(appearance.as_deref()) };
15029 }
15030 }
15031 register_bundled_fonts();
15033
15034 let app_name = self.app_name.clone();
15038 install_main_menu(mtm, &app, &app_name);
15039 install_lifecycle_observers();
15041 install_appearance_observer();
15042 install_reduce_motion_observer();
15043
15044 let (window, delegate, content) = self.make_window(&options, false, None);
15045 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
15049 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
15050 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
15051 _ => None,
15052 };
15053 if let Some(name) = appearance_name
15054 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
15055 {
15056 window.setAppearance(Some(&appearance));
15057 }
15058 std::mem::forget(delegate);
15061
15062 self.window = Some(window.clone());
15063 self.content = Some(content.clone());
15064 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
15065
15066 let layout = pin_below_title_bar(&window)
15068 .unwrap_or(Size::new(options.size.width, options.size.height));
15069 ready(self, content, layout);
15070
15071 if day_core::windows::new_window_action_id() == 0
15075 && options.tabbing == day_spec::WindowTabbing::Automatic
15076 {
15077 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
15078 }
15079 if !day_core::has_app_menu() {
15084 install_main_menu(mtm, &app, &app_name);
15085 }
15086
15087 let deterministic =
15095 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
15096 let autosave = NSString::from_str("day.main");
15097 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
15098 window.center();
15099 window_chrome::place(&window, options.placement);
15101 }
15102 if let Some(screen) = capture_screen(mtm) {
15106 let (visible, frame) = (screen.visibleFrame(), window.frame());
15107 window.setFrameOrigin(NSPoint::new(
15108 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
15109 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
15110 ));
15111 }
15112 if !deterministic {
15113 unsafe { window.setFrameAutosaveName(&autosave) };
15114 }
15115 if !options.start_hidden {
15116 window.makeKeyAndOrderFront(None);
15117 app.activate();
15118 }
15119 if let Some(content) = window.contentView() {
15124 mark_tree_needs_display(&content);
15125 }
15126 if std::env::var_os("DAY_DUMP").is_some() {
15127 std::thread::spawn(|| {
15128 std::thread::sleep(std::time::Duration::from_millis(2000));
15129 Self::post(Box::new(|| {
15130 if let Some(content) = primary_content() {
15132 let desc: Retained<NSString> =
15133 unsafe { msg_send![&*content, _subtreeDescription] };
15134 log::warn!("{desc}");
15135 }
15136 }));
15137 });
15138 }
15139 app.run();
15140 }
15141
15142 fn post(f: Box<dyn FnOnce() + Send>) {
15143 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
15146 }
15147
15148 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
15149 let when =
15153 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
15154 .unwrap_or(dispatch2::DispatchTime::FOREVER);
15155 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
15156 ffi_guard::contain((), f);
15157 }) {
15158 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
15159 }
15160 }
15161
15162 fn locale_hints(&self) -> Vec<String> {
15163 objc2_foundation::NSLocale::preferredLanguages()
15166 .iter()
15167 .map(|s| s.to_string())
15168 .collect()
15169 }
15170}
15171
15172unsafe extern "C" {
15177 fn CGWindowListCreateImage(
15178 bounds: objc2_core_foundation::CGRect,
15179 list_option: u32,
15180 window_id: u32,
15181 image_option: u32,
15182 ) -> *mut objc2_core_graphics::CGImage;
15183}
15184
15185const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
15188const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
15191
15192fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
15199 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
15200 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
15201 objc2_app_kit::NSColorRenderingIntent::Default,
15202 );
15203 let rep = srgb.as_deref().unwrap_or(rep);
15204 let data = unsafe {
15205 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
15206 }
15207 .ok_or("png encode failed")?;
15208 Ok(data.to_vec())
15209}
15210
15211fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
15224 let window = content.window().ok_or("view is not in a window")?;
15225 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
15228 return snapshot_via_window_server(&sheet, chrome);
15229 }
15230 let number = window.windowNumber();
15231 if number <= 0 {
15232 return Err(format!("window {number} is not on screen"));
15233 }
15234 unsafe { content.layoutSubtreeIfNeeded() };
15241 window.displayIfNeeded();
15242 CATransaction::flush();
15243 let null_rect = objc2_core_foundation::CGRect::new(
15245 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
15246 objc2_core_foundation::CGSize::new(0.0, 0.0),
15247 );
15248 let shot = unsafe {
15249 CGWindowListCreateImage(
15250 null_rect,
15251 CG_WINDOW_LIST_INCLUDING_WINDOW,
15252 number as u32,
15253 CG_WINDOW_IMAGE_IGNORE_FRAMING,
15254 )
15255 };
15256 if shot.is_null() {
15257 return Err("the window server has no image for this window".into());
15258 }
15259 let shot = unsafe {
15262 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
15263 };
15264
15265 if chrome {
15268 let rep = unsafe {
15269 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
15270 objc2_app_kit::NSBitmapImageRep::alloc(),
15271 &shot,
15272 )
15273 };
15274 return png_of_rep(&rep);
15275 }
15276
15277 let frame = window.frame();
15281 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
15282 return Err("zero-size window".into());
15283 }
15284 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
15285 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
15288 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
15289 let crop = objc2_core_foundation::CGRect::new(
15290 objc2_core_foundation::CGPoint::new(
15291 (in_window.origin.x * scale).round(),
15292 (from_top * scale).round(),
15293 ),
15294 objc2_core_foundation::CGSize::new(
15295 (in_window.size.width * scale).round(),
15296 (in_window.size.height * scale).round(),
15297 ),
15298 );
15299 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
15300 .ok_or("crop to the content view failed")?;
15301 let rep = unsafe {
15302 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
15303 objc2_app_kit::NSBitmapImageRep::alloc(),
15304 &cropped,
15305 )
15306 };
15307 png_of_rep(&rep)
15308}
15309
15310fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
15320 let [x, y, w, h] = base;
15321 let (sw, sh) = (w * t.sx, h * t.sy);
15322 let frame = NSRect::new(
15323 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
15324 NSSize::new(sw, sh),
15325 );
15326 unsafe {
15327 v.setFrameCenterRotation(0.0);
15330 v.setFrame(frame);
15331 v.setBoundsSize(NSSize::new(w, h));
15332 if t.rotation.degrees() != 0.0 {
15333 v.setFrameCenterRotation(t.rotation.degrees());
15334 }
15335 }
15336}
15337
15338fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
15339 objc2::rc::autoreleasepool(|_| {
15345 let modal = content
15346 .window()
15347 .and_then(|w| w.attachedSheet())
15348 .and_then(|s| s.contentView());
15349 let content = modal.as_deref().unwrap_or(content);
15350 match snapshot_via_window_server(content, false) {
15351 Ok(bytes) => Ok(bytes),
15352 Err(_) => snapshot_view_cache(content),
15353 }
15354 })
15355}
15356
15357fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
15365 objc2::rc::autoreleasepool(|_| {
15367 let modal = content
15368 .window()
15369 .and_then(|w| w.attachedSheet())
15370 .and_then(|s| s.contentView());
15371 let content = modal.as_deref().unwrap_or(content);
15372 match snapshot_via_window_server(content, true) {
15373 Ok(bytes) => Ok(bytes),
15374 Err(_) => snapshot_view_cache(content),
15375 }
15376 })
15377}
15378
15379fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
15383 let bounds = content.bounds();
15384 let rep =
15385 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
15386 let ctx =
15390 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
15391 NSGraphicsContext::saveGraphicsState_class();
15392 NSGraphicsContext::setCurrentContext(Some(&ctx));
15393 content
15394 .effectiveAppearance()
15395 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
15396 NSColor::windowBackgroundColor().setFill();
15397 objc2_app_kit::NSRectFill(bounds);
15398 }));
15399 NSGraphicsContext::restoreGraphicsState_class();
15400 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
15401 png_of_rep(&rep)
15402}
15403
15404fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
15410 let Some(screen) = primary.and_then(objc2_app_kit::NSWindow::screen) else {
15411 return;
15412 };
15413 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
15414 return;
15415 }
15416 let (visible, frame) = (screen.visibleFrame(), window.frame());
15417 window.setFrameOrigin(NSPoint::new(
15418 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
15419 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
15420 ));
15421}
15422
15423fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
15424 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
15425 .ok()?
15426 .trim()
15427 .parse()
15428 .ok()?;
15429 let key = NSString::from_str("NSScreenNumber");
15430 objc2_app_kit::NSScreen::screens(mtm)
15431 .into_iter()
15432 .find(|screen| {
15433 let number: Option<Retained<objc2_foundation::NSNumber>> =
15434 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
15435 number.is_some_and(|n| n.unsignedIntValue() == wanted)
15436 })
15437}
15438
15439fn mark_tree_needs_display(view: &NSView) {
15441 view.setNeedsDisplay(true);
15442 for sub in view.subviews() {
15443 mark_tree_needs_display(&sub);
15444 }
15445}
15446
15447#[must_use]
15452pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
15453 phase.is_universal()
15454}
15455
15456fn install_appearance_observer() {
15462 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
15463 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
15464 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15465 dispatch2::DispatchQueue::main().exec_async(|| {
15466 ffi_guard::contain((), || {
15467 day_core::note_appearance_changed();
15468 color::refresh_layers();
15469 });
15470 });
15471 });
15472 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
15473 let token = unsafe {
15474 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
15475 };
15476 std::mem::forget(token);
15477 let center = objc2_foundation::NSNotificationCenter::defaultCenter();
15479 let name = NSString::from_str("NSSystemColorsDidChangeNotification");
15480 let token = unsafe {
15481 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
15482 };
15483 std::mem::forget(token);
15484}
15485
15486fn install_reduce_motion_observer() {
15494 use objc2_foundation::NSNotification;
15495 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
15496 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15497 dispatch2::DispatchQueue::main()
15498 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
15499 });
15500 let token = unsafe {
15501 center.addObserverForName_object_queue_usingBlock(
15502 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
15503 None,
15504 None,
15505 &block,
15506 )
15507 };
15508 std::mem::forget(token);
15509}
15510
15511fn install_lifecycle_observers() {
15514 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
15515 let center = unsafe { NSNotificationCenter::defaultCenter() };
15516 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
15517 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15518 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
15519 });
15520 let token = unsafe {
15521 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
15522 };
15523 std::mem::forget(token); };
15525 unsafe {
15526 observe(
15527 NSApplicationDidBecomeActiveNotification,
15528 day_spec::Lifecycle::DidBecomeActive,
15529 );
15530 observe(
15531 NSApplicationWillResignActiveNotification,
15532 day_spec::Lifecycle::WillResignActive,
15533 );
15534 observe(
15535 NSApplicationWillTerminateNotification,
15536 day_spec::Lifecycle::WillTerminate,
15537 );
15538 observe(
15542 NSApplicationWillTerminateNotification,
15543 day_spec::Lifecycle::DidExit,
15544 );
15545 }
15546}
15547
15548day_localization_ui::locales!();
15549
15550fn install_application_menu(
15553 mtm: MainThreadMarker,
15554 menubar: &NSMenu,
15555 title: &str,
15556 about: Option<day_spec::MenuItem>,
15557 updates: Option<day_spec::MenuItem>,
15558 prefs: Option<day_spec::MenuItem>,
15559 quit: Option<day_spec::MenuItem>,
15560) -> Retained<NSMenu> {
15561 use day_spec::{MenuItem as M, MenuRole as R};
15562 let app = NSApplication::sharedApplication(mtm);
15563 let standard = |role, label| M::Action {
15564 id: None,
15565 action: 0,
15566 label,
15567 shortcut: None,
15568 enabled: true,
15569 checked: None,
15570 role: Some(role),
15571 icon: None,
15572 };
15573 let mut about =
15574 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
15575 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
15576 for (item, title) in [
15577 (&mut about, res::str::about_app(title).format()),
15578 (&mut quit, res::str::quit_app(title).format()),
15579 ] {
15580 if let M::Action { label, .. } = item {
15581 *label = title;
15582 }
15583 }
15584 if let M::Action { action, .. } = &mut about
15587 && *action == 0
15588 {
15589 *action = day_core::windows::about_action_id();
15590 }
15591 let updates_id = day_core::windows::check_for_updates_action_id();
15594 let updates = updates.or_else(|| {
15595 (updates_id != 0).then(|| {
15596 standard(
15597 R::CheckForUpdates,
15598 day_localization::t(day_localization::key::day_check_for_updates),
15599 )
15600 })
15601 });
15602 let mut head = vec![about];
15603 if let Some(mut updates) = updates {
15604 if let M::Action { action, .. } = &mut updates
15605 && *action == 0
15606 {
15607 *action = updates_id;
15608 }
15609 head.push(updates);
15610 }
15611 head.push(M::Separator);
15612 let menu = build_ns_menu(mtm, title, &head);
15613 if let Some(mut prefs) = prefs {
15614 if let M::Action { label, .. } = &mut prefs {
15615 *label = res::str::settings().format();
15616 }
15617 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
15618 for item in section.itemArray() {
15619 section.removeItem(&item);
15620 menu.addItem(&item);
15621 }
15622 }
15623 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
15626 if let Some(parent) = unsafe { services.supermenu() } {
15627 let index = parent.indexOfItemWithSubmenu(Some(&services));
15628 if index >= 0 {
15629 parent.itemAtIndex(index).unwrap().setSubmenu(None);
15630 }
15631 }
15632 let services_item = NSMenuItem::new(mtm);
15633 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
15634 services_item.setSubmenu(Some(&services));
15635 menu.addItem(&services_item);
15636 menu.addItem(&NSMenuItem::separatorItem(mtm));
15637 for (label, selector, shortcut) in [
15638 (
15639 res::str::hide_app(title).format(),
15640 sel!(hide:),
15641 Some(day_spec::Shortcut::primary("h")),
15642 ),
15643 (
15644 res::str::hide_others().format(),
15645 sel!(hideOtherApplications:),
15646 Some(day_spec::Shortcut::primary("h").alt()),
15647 ),
15648 (
15649 res::str::show_all().format(),
15650 sel!(unhideAllApplications:),
15651 None,
15652 ),
15653 ] {
15654 let item = unsafe {
15655 NSMenuItem::initWithTitle_action_keyEquivalent(
15656 NSMenuItem::alloc(mtm),
15657 &NSString::from_str(&label),
15658 Some(selector),
15659 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
15660 )
15661 };
15662 if let Some(shortcut) = shortcut {
15663 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
15664 }
15665 unsafe { item.setTarget(Some(&app)) };
15667 menu.addItem(&item);
15668 }
15669 menu.addItem(&NSMenuItem::separatorItem(mtm));
15670 let section = build_ns_menu(mtm, title, &[quit]);
15671 let quit = section.itemAtIndex(0).unwrap();
15672 section.removeItem(&quit);
15673 menu.addItem(&quit);
15674 let item = NSMenuItem::new(mtm);
15675 item.setSubmenu(Some(&menu));
15676 menubar.addItem(&item);
15677 services
15678}
15679
15680fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
15683 let menubar = NSMenu::new(mtm);
15684
15685 let prefs_id = day_core::windows::preferences_action_id();
15686 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
15687 id: None,
15688 action: prefs_id,
15689 label: res::str::settings().format(),
15690 shortcut: None,
15691 enabled: true,
15692 checked: None,
15693 role: Some(day_spec::MenuRole::Preferences),
15694 icon: None,
15695 });
15696 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
15697
15698 let new_window_id = day_core::windows::new_window_action_id();
15703 if new_window_id != 0 {
15704 let file_item = NSMenuItem::new(mtm);
15705 let file_menu = unsafe {
15706 NSMenu::initWithTitle(
15707 NSMenu::alloc(mtm),
15708 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
15709 )
15710 };
15711 let new_window = unsafe {
15712 NSMenuItem::initWithTitle_action_keyEquivalent(
15713 NSMenuItem::alloc(mtm),
15714 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
15715 Some(sel!(fire:)),
15716 &NSString::from_str("n"),
15717 )
15718 };
15719 let target = menu_target(mtm);
15720 let tobj: &objc2::runtime::AnyObject = target.as_ref();
15721 unsafe { new_window.setTarget(Some(tobj)) };
15722 new_window.setTag(new_window_id as isize);
15723 file_menu.addItem(&new_window);
15724 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
15725 let close = unsafe {
15727 NSMenuItem::initWithTitle_action_keyEquivalent(
15728 NSMenuItem::alloc(mtm),
15729 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
15730 Some(sel!(performClose:)),
15731 &NSString::from_str("w"),
15732 )
15733 };
15734 file_menu.addItem(&close);
15735 file_item.setSubmenu(Some(&file_menu));
15736 menubar.addItem(&file_item);
15737 }
15738
15739 let edit_item = NSMenuItem::new(mtm);
15740 let edit_menu = unsafe {
15741 NSMenu::initWithTitle(
15742 NSMenu::alloc(mtm),
15743 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
15744 )
15745 };
15746 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
15747 let item = unsafe {
15748 NSMenuItem::initWithTitle_action_keyEquivalent(
15749 NSMenuItem::alloc(mtm),
15750 &NSString::from_str(&day_localization::t(key)),
15751 Some(action),
15752 &NSString::from_str(accel),
15753 )
15754 };
15755 edit_menu.addItem(&item);
15756 };
15757 add("day_undo", sel!(undo:), "z");
15758 add("day_redo", sel!(redo:), "Z");
15759 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
15760 add("day_cut", sel!(cut:), "x");
15761 add("day_copy", sel!(copy:), "c");
15762 add("day_paste", sel!(paste:), "v");
15763 add("day_select_all", sel!(selectAll:), "a");
15764 edit_item.setSubmenu(Some(&edit_menu));
15765 menubar.addItem(&edit_item);
15766
15767 install_windows_menu(mtm, app, &menubar);
15768
15769 app.setMainMenu(Some(&menubar));
15770 unsafe { app.setServicesMenu(Some(&services)) };
15771}
15772
15773fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
15778 let menu = unsafe {
15779 NSMenu::initWithTitle(
15780 NSMenu::alloc(mtm),
15781 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
15782 )
15783 };
15784 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
15785 let item = unsafe {
15786 NSMenuItem::initWithTitle_action_keyEquivalent(
15787 NSMenuItem::alloc(mtm),
15788 &NSString::from_str(&day_localization::t(key)),
15789 Some(action),
15790 &NSString::from_str(accel),
15791 )
15792 };
15793 menu.addItem(&item);
15794 };
15795 add("day_minimize", sel!(performMiniaturize:), "m");
15796 add("day_zoom", sel!(performZoom:), "");
15797 menu.addItem(&NSMenuItem::separatorItem(mtm));
15798 add("day_bring_all_front", sel!(arrangeInFront:), "");
15799 let item = NSMenuItem::new(mtm);
15800 item.setTitle(&NSString::from_str(&day_localization::t(
15801 day_localization::key::day_window,
15802 )));
15803 item.setSubmenu(Some(&menu));
15804 menubar.addItem(&item);
15805 unsafe { app.setWindowsMenu(Some(&menu)) };
15806}
15807
15808fn extract_app_role(
15811 items: &mut Vec<day_spec::MenuItem>,
15812 role: day_spec::MenuRole,
15813) -> Option<day_spec::MenuItem> {
15814 use day_spec::MenuItem as M;
15815 let mut found = None;
15816 let mut remaining = Vec::new();
15817 for mut item in items.drain(..) {
15818 match &mut item {
15819 M::Action { role: Some(r), .. } if *r == role => {
15820 found.get_or_insert(item);
15821 continue;
15822 }
15823 M::Submenu { items, .. } => {
15824 let nested = extract_app_role(items, role);
15825 if found.is_none() {
15826 found = nested;
15827 }
15828 if items.is_empty() {
15829 continue;
15830 }
15831 }
15832 M::Separator
15833 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
15834 {
15835 continue;
15836 }
15837 _ => {}
15838 }
15839 remaining.push(item);
15840 }
15841 while matches!(remaining.last(), Some(M::Separator)) {
15842 remaining.pop();
15843 }
15844 *items = remaining;
15845 found
15846}
15847
15848fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
15850 items.iter().any(|it| match it {
15851 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
15852 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
15853 day_spec::MenuItem::Separator => false,
15854 })
15855}
15856
15857define_class!(
15863 #[unsafe(super(NSObject))]
15864 #[thread_kind = MainThreadOnly]
15865 #[name = "DayMenuTarget"]
15866 #[ivars = ()]
15867 struct DayMenuTarget;
15868
15869 unsafe impl NSObjectProtocol for DayMenuTarget {}
15870
15871 impl DayMenuTarget {
15872 #[unsafe(method(fire:))]
15873 fn fire(&self, sender: &NSMenuItem) {
15874 ffi_guard::contain((), || {
15875 let id = sender.tag() as u64;
15876 if id != 0 {
15877 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
15878 }
15879 });
15880 }
15881 }
15882);
15883
15884pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
15893 let content = window.contentView()?;
15894 let full = content.frame().size;
15895 let layout = unsafe { window.contentLayoutRect() }.size;
15896 let top = (full.height - layout.height).max(0.0);
15897 if window_chrome::is_overlay(window) {
15901 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
15902 window_chrome::report_title_bar_inset(window, top);
15903 return Some(Size::new(full.width, full.height));
15904 }
15905 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
15906 Some(Size::new(full.width, (full.height - top).max(0.0)))
15907}
15908
15909fn native_text(h: &NSView) -> Option<String> {
15913 if h.downcast_ref::<NSSecureTextField>().is_some() {
15914 return None;
15915 }
15916 if let Some(tf) = h.downcast_ref::<NSTextField>() {
15917 return Some(tf.stringValue().to_string());
15919 }
15920 if let Some(btn) = h.downcast_ref::<NSButton>() {
15921 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
15922 return None;
15923 }
15924 return Some(btn.title().to_string());
15925 }
15926 let sv = h.downcast_ref::<NSScrollView>()?;
15928 let doc = sv.documentView()?;
15929 let tv = doc.downcast_ref::<NSTextView>()?;
15930 Some(tv.string().to_string())
15931}
15932
15933fn native_number(h: &NSView) -> Option<f64> {
15936 if let Some(sl) = h.downcast_ref::<NSSlider>() {
15937 return Some(sl.doubleValue());
15938 }
15939 let pi = h.downcast_ref::<NSProgressIndicator>()?;
15940 (!pi.isIndeterminate()).then(|| pi.doubleValue())
15941}
15942
15943fn native_frame(h: &NSView) -> Option<Rect> {
15947 let content = h.window()?.contentView()?;
15948 let r = h.convertRect_toView(h.bounds(), Some(&content));
15949 let y = if content.isFlipped() {
15950 r.origin.y
15951 } else {
15952 let b = content.bounds();
15953 b.origin.y + b.size.height - (r.origin.y + r.size.height)
15954 };
15955 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
15956}
15957
15958fn title_bar_inset(content: &NSView) -> f64 {
15960 (-content.bounds().origin.y).max(0.0)
15961}
15962
15963fn primary_content() -> Option<Retained<NSView>> {
15964 PRIMARY_CONTENT.with(|c| c.borrow().clone())
15965}
15966
15967fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
15968 MENU_TARGET.with(|t| {
15969 t.borrow_mut()
15970 .get_or_insert_with(|| {
15971 let this = DayMenuTarget::alloc(mtm).set_ivars(());
15972 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
15973 obj
15974 })
15975 .clone()
15976 })
15977}
15978
15979fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
15980 use objc2_app_kit::NSEventModifierFlags as F;
15981 let mut m = F::empty();
15982 if s.primary {
15983 m |= F::Command;
15984 }
15985 if s.shift {
15986 m |= F::Shift;
15987 }
15988 if s.alt {
15989 m |= F::Option;
15990 }
15991 if s.control {
15992 m |= F::Control;
15993 }
15994 m
15995}
15996
15997fn ns_key_equivalent(key: &str) -> String {
16000 match key {
16001 "Return" | "Enter" => "\r".into(),
16002 "Tab" => "\t".into(),
16003 "Delete" | "Backspace" => "\u{8}".into(),
16004 "Escape" => "\u{1b}".into(),
16005 "Space" => " ".into(),
16006 k if k.chars().count() == 1 => k.to_lowercase(),
16007 _ => String::new(), }
16009}
16010
16011fn role_spec(
16014 role: day_spec::MenuRole,
16015) -> (
16016 &'static str,
16017 Option<objc2::runtime::Sel>,
16018 Option<day_spec::Shortcut>,
16019) {
16020 use day_spec::MenuRole as R;
16021 use day_spec::Shortcut as S;
16022 match role {
16023 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
16024 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
16025 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
16026 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
16027 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
16028 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
16029 R::Delete => ("Delete", Some(sel!(delete:)), None),
16030 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
16031 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
16032 R::Preferences => ("Settings…", None, Some(S::primary(","))),
16033 R::Minimize => (
16034 "Minimize",
16035 Some(sel!(performMiniaturize:)),
16036 Some(S::primary("m")),
16037 ),
16038 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
16039 R::Fullscreen => (
16040 "Enter Full Screen",
16041 Some(sel!(toggleFullScreen:)),
16042 Some(S::primary("f").control()),
16043 ),
16044 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
16047 R::CheckForUpdates => ("Check for Updates…", None, None),
16049 }
16050}
16051
16052pub(crate) fn build_ns_menu(
16053 mtm: MainThreadMarker,
16054 title: &str,
16055 items: &[day_spec::MenuItem],
16056) -> Retained<NSMenu> {
16057 use day_spec::MenuItem as MI;
16058 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
16059 let target = menu_target(mtm);
16060 for item in items {
16061 match item {
16062 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
16063 MI::Submenu { label, items, .. } => {
16064 let sub = build_ns_menu(mtm, label, items);
16065 let it = NSMenuItem::new(mtm);
16066 it.setTitle(&NSString::from_str(label));
16067 it.setSubmenu(Some(&sub));
16068 menu.addItem(&it);
16069 }
16070 MI::Action {
16071 action,
16072 label,
16073 shortcut,
16074 enabled,
16075 checked,
16076 role,
16077 icon,
16078 ..
16079 } => {
16080 let (mut lbl, sel, mut sc) = match role {
16082 Some(r) => {
16083 let (dl, ds, dsc) = role_spec(*r);
16084 (dl.to_string(), ds, dsc)
16085 }
16086 None => (String::new(), None, None),
16087 };
16088 if !label.is_empty() {
16089 lbl.clone_from(label);
16090 }
16091 if shortcut.is_some() {
16092 sc.clone_from(shortcut);
16093 }
16094 let responder_role = matches!(
16100 role,
16101 Some(
16102 day_spec::MenuRole::Undo
16103 | day_spec::MenuRole::Redo
16104 | day_spec::MenuRole::Cut
16105 | day_spec::MenuRole::Copy
16106 | day_spec::MenuRole::Paste
16107 | day_spec::MenuRole::SelectAll
16108 )
16109 );
16110 let custom = *action != 0 && !responder_role;
16111 let key = sc.as_ref().map_or_default(|s| ns_key_equivalent(&s.key));
16112 let it = unsafe {
16113 NSMenuItem::initWithTitle_action_keyEquivalent(
16114 NSMenuItem::alloc(mtm),
16115 &NSString::from_str(&lbl),
16116 if custom { Some(sel!(fire:)) } else { sel },
16117 &NSString::from_str(&key),
16118 )
16119 };
16120 if let Some(s) = &sc {
16121 it.setKeyEquivalentModifierMask(ns_modifiers(s));
16122 it.setAllowsAutomaticKeyEquivalentLocalization(true);
16128 it.setAllowsAutomaticKeyEquivalentMirroring(true);
16129 }
16130 if custom {
16131 let tobj: &objc2::runtime::AnyObject = target.as_ref();
16132 unsafe { it.setTarget(Some(tobj)) };
16133 it.setTag(*action as isize);
16134 }
16135 it.setEnabled(*enabled);
16136 if let Some(on) = checked {
16139 it.setState(if *on {
16140 NSControlStateValueOn
16141 } else {
16142 NSControlStateValueOff
16143 });
16144 }
16145 if let Some(icon) = icon
16148 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
16149 {
16150 img.setSize(NSSize::new(16.0, 16.0));
16151 it.setImage(Some(&img));
16152 }
16153 menu.addItem(&it);
16154 }
16155 }
16156 }
16157 menu
16158}
16159
16160fn release_bitmap(id: day_spec::BitmapId) {
16163 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
16164}
16165
16166#[cfg(test)]
16167mod splice_tests {
16168 use super::{SpliceRows, splice_fits};
16169 use day_spec::props::RowDelta::{Insert, Move, Remove};
16170
16171 #[test]
16172 fn a_splice_fits_only_the_rows_it_was_made_for() {
16173 let deltas = [Insert(0), Move(3, 0), Remove(2)];
16175 assert!(splice_fits(3, &deltas, 3));
16176 assert!(splice_fits(3, &[Insert(3), Insert(4)], 5));
16178 assert!(splice_fits(0, &[], 0));
16179 assert!(!splice_fits(2, &deltas, 2));
16181 assert!(!splice_fits(3, &[Insert(5)], 4));
16182 assert!(!splice_fits(3, &[Remove(3)], 2));
16183 assert!(!splice_fits(3, &[Move(0, 3)], 3));
16184 assert!(!splice_fits(3, &[Insert(0)], 3));
16185 }
16186
16187 #[test]
16188 fn a_splice_in_flight_maps_each_row_to_the_source_row_it_ends_at() {
16189 let deltas = [
16192 Insert(4),
16193 Insert(4),
16194 Insert(4),
16195 Insert(4),
16196 Insert(4),
16197 Insert(2),
16198 Insert(2),
16199 ];
16200 let mut rows = SpliceRows::new(4, &deltas);
16201 let shown = |rows: &SpliceRows| -> Vec<Option<usize>> {
16202 (0..rows.entries.len())
16203 .map(|r| rows.source_row(r))
16204 .collect()
16205 };
16206 assert!(shown(&rows).into_iter().eq([0, 1, 4, 5].map(Some)));
16208 rows.apply(deltas[0]);
16210 assert!(shown(&rows).into_iter().eq([0, 1, 4, 5, 10].map(Some)));
16211 for delta in &deltas[1..] {
16212 rows.apply(*delta);
16213 }
16214 assert!(shown(&rows).into_iter().eq((0..11).map(Some)));
16215
16216 let deltas = [Remove(3), Remove(1), Move(1, 0)];
16218 let mut rows = SpliceRows::new(4, &deltas);
16219 assert!(shown(&rows).into_iter().eq([Some(1), None, Some(0), None]));
16220 rows.apply(deltas[0]);
16221 rows.apply(deltas[1]);
16222 assert!(shown(&rows).into_iter().eq([1, 0].map(Some)));
16223 rows.apply(deltas[2]);
16224 assert!(shown(&rows).into_iter().eq([0, 1].map(Some)));
16225 }
16226}
16227
16228#[cfg(test)]
16229mod bitmap_teardown_tests {
16230 use super::*;
16231
16232 #[test]
16233 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
16234 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
16236 if std::env::var_os(CHILD).is_some() {
16237 struct LateRelease;
16238 impl Drop for LateRelease {
16239 fn drop(&mut self) {
16240 assert!(BITMAPS.try_with(|_| ()).is_err());
16241 release_bitmap(day_spec::BitmapId(1));
16243 }
16244 }
16245 std::thread_local! {
16246 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
16247 }
16248 std::thread::spawn(|| {
16249 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
16250 BITMAPS.with(|_| ()); })
16252 .join()
16253 .unwrap();
16254 return;
16255 }
16256 let output = std::process::Command::new(std::env::current_exe().unwrap())
16257 .args([
16258 "--exact",
16259 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
16260 "--nocapture",
16261 ])
16262 .env(CHILD, "1")
16263 .output()
16264 .unwrap();
16265 assert!(
16266 output.status.success(),
16267 "{}",
16268 String::from_utf8_lossy(&output.stderr)
16269 );
16270 }
16271}
16272
16273#[cfg(test)]
16274mod canvas_ink_tests {
16275 use super::*;
16276 use day_spec::{Affine, BlendMode, Color, ConicGradient, Shadow, Shape};
16277
16278 const RED: Color = Color::rgb(1.0, 0.0, 0.0);
16279 const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);
16280 const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
16281 const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0);
16282
16283 fn rect(x: f64, y: f64, w: f64, h: f64) -> Shape {
16284 Shape::Rect(day_spec::Rect::new(x, y, w, h))
16285 }
16286
16287 fn quarters() -> ConicGradient {
16289 let stops = [RED, GREEN, BLUE, YELLOW]
16290 .iter()
16291 .enumerate()
16292 .flat_map(|(i, c)| [(i as f64 * 0.25, *c), (i as f64 * 0.25 + 0.25, *c)])
16293 .collect::<Vec<_>>();
16294 ConicGradient::centered(day_spec::Angle::deg(0.0), stops)
16295 }
16296
16297 fn painted(ops: &[DrawOp], size: Size, scale: f64, at: &[(usize, usize)]) -> Vec<[u8; 4]> {
16300 let image = render_bitmap_cgimage(ops, size, scale).unwrap();
16301 let rep = unsafe {
16302 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
16303 objc2_app_kit::NSBitmapImageRep::alloc(),
16304 &image,
16305 )
16306 };
16307 let (data, stride) = (rep.bitmapData(), rep.bytesPerRow() as usize);
16308 assert_eq!(rep.bitsPerPixel(), 32);
16309 at.iter()
16310 .map(|(x, y)| {
16311 let mut px = [0u8; 4];
16312 unsafe {
16315 data.add(y * stride + x * 4)
16316 .copy_to_nonoverlapping(px.as_mut_ptr(), 4);
16317 };
16318 px
16319 })
16320 .collect()
16321 }
16322
16323 fn near(px: [u8; 4], want: [u8; 4]) -> bool {
16324 px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 24)
16325 }
16326
16327 #[test]
16328 fn replay_mirrors_save_and_restore() {
16329 let mut replay = Replay::new(1.0);
16330 replay.save();
16331 replay.ink.shadow = true;
16332 replay.save();
16333 replay.ink.blend = BlendMode::Erase;
16334 assert!(replay.restore());
16335 assert_eq!(
16336 replay.ink,
16337 Ink {
16338 shadow: true,
16339 blend: BlendMode::Normal
16340 }
16341 );
16342 assert!(replay.restore());
16343 assert_eq!(replay.ink, Ink::default());
16344 assert!(!replay.restore());
16346 assert_eq!(replay.ink, Ink::default());
16347 }
16348
16349 #[test]
16350 fn pdf_leaves_out_what_erase_draws() {
16351 let plain = [DrawOp::Fill(rect(0.0, 0.0, 9.0, 9.0), RED.into())];
16352 assert!(matches!(pdf_ops(&plain), std::borrow::Cow::Borrowed(_)));
16353 let ops = [
16354 DrawOp::Fill(rect(0.0, 0.0, 9.0, 9.0), RED.into()),
16355 DrawOp::Save,
16356 DrawOp::Blend(BlendMode::Erase),
16357 DrawOp::Fill(rect(1.0, 1.0, 2.0, 2.0), GREEN.into()),
16358 DrawOp::Restore,
16359 DrawOp::Fill(rect(3.0, 3.0, 2.0, 2.0), BLUE.into()),
16360 ];
16361 let kept = pdf_ops(&ops);
16362 assert_eq!(kept.len(), 5);
16363 assert!(!kept.contains(&ops[3]));
16364 assert!(kept.contains(&ops[5]));
16365 }
16366
16367 #[test]
16368 fn conic_pixels_turn_clockwise_from_the_start() {
16369 let px = conic_pixels(
16371 &quarters(),
16372 Point::new(2.0, 2.0),
16373 Point::new(0.0, 0.0),
16374 1.0,
16375 4,
16376 4,
16377 );
16378 let at = |x: usize, y: usize| <[u8; 4]>::try_from(&px[(y * 4 + x) * 4..][..4]).unwrap();
16379 assert_eq!(px.len(), 4 * 4 * 4);
16380 assert_eq!(at(3, 3), [255, 0, 0, 255]);
16381 assert_eq!(at(0, 3), [0, 255, 0, 255]);
16382 assert_eq!(at(0, 0), [0, 0, 255, 255]);
16383 assert_eq!(at(3, 0), [255, 255, 0, 255]);
16384 let half = Color::rgba(1.0, 0.0, 0.0, 0.5);
16386 let faint =
16387 ConicGradient::centered(day_spec::Angle::deg(90.0), vec![(0.0, half), (1.0, half)]);
16388 let px = conic_pixels(
16389 &faint,
16390 Point::new(0.5, 0.5),
16391 Point::new(0.0, 0.0),
16392 1.0,
16393 1,
16394 1,
16395 );
16396 assert_eq!(px, [128, 0, 0, 128]);
16397 let turned = ConicGradient::centered(day_spec::Angle::deg(90.0), quarters().stops);
16399 let px = conic_pixels(
16400 &turned,
16401 Point::new(1.0, 1.0),
16402 Point::new(0.0, 0.0),
16403 1.0,
16404 2,
16405 2,
16406 );
16407 assert_eq!(px[8..12], [255, 0, 0, 255]);
16408 }
16409
16410 #[test]
16411 fn stamp_bounds_join_every_copy() {
16412 let mut stamp = day_spec::Stamp {
16413 shape: Shape::Ellipse(day_spec::Rect::new(-3.0, -3.0, 6.0, 6.0)),
16414 at: vec![Point::new(10.0, 50.0), Point::new(40.0, 20.0)],
16415 paint: RED.into(),
16416 stroke: None,
16417 };
16418 assert_eq!(
16419 stamp_bounds(&stamp),
16420 Some(day_spec::Rect::new(7.0, 17.0, 36.0, 36.0))
16421 );
16422 stamp.at.clear();
16423 assert_eq!(stamp_bounds(&stamp), None);
16424 }
16425
16426 #[test]
16427 fn export_paints_conic_quadrants() {
16428 let size = Size::new(100.0, 100.0);
16429 let ops = [DrawOp::Fill(
16430 rect(0.0, 0.0, 100.0, 100.0),
16431 quarters().into(),
16432 )];
16433 let px = painted(&ops, size, 1.0, &[(75, 75), (25, 75), (25, 25), (75, 25)]);
16434 assert!(near(px[0], [255, 0, 0, 255]), "{px:?}");
16435 assert!(near(px[1], [0, 255, 0, 255]), "{px:?}");
16436 assert!(near(px[2], [0, 0, 255, 255]), "{px:?}");
16437 assert!(near(px[3], [255, 255, 0, 255]), "{px:?}");
16438 }
16439
16440 fn fanned(gradient: &ConicGradient, at: &[(usize, usize)]) -> Vec<[u8; 4]> {
16443 use objc2_core_graphics::{
16444 CGBitmapContextCreate, CGBitmapContextGetBytesPerRow, CGBitmapContextGetData,
16445 CGColorSpace, CGContext, CGImageAlphaInfo,
16446 };
16447 let space =
16448 CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
16449 let cg = unsafe {
16450 CGBitmapContextCreate(
16451 std::ptr::null_mut(),
16452 100,
16453 100,
16454 8,
16455 0,
16456 space.as_deref(),
16457 CGImageAlphaInfo::PremultipliedLast.0,
16458 )
16459 }
16460 .unwrap();
16461 CGContext::translate_ctm(Some(&cg), 0.0, 100.0);
16462 CGContext::scale_ctm(Some(&cg), 1.0, -1.0);
16463 CGContext::add_ellipse_in_rect(
16464 Some(&cg),
16465 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(100.0, 100.0)),
16466 );
16467 CGContext::clip(Some(&cg));
16468 draw_conic_pixels(&cg, gradient, Point::new(50.0, 50.0));
16469 let (data, stride) = (
16470 CGBitmapContextGetData(Some(&cg)).cast::<u8>(),
16471 CGBitmapContextGetBytesPerRow(Some(&cg)),
16472 );
16473 at.iter()
16474 .map(|(x, y)| {
16475 let mut px = [0u8; 4];
16476 unsafe {
16478 data.add(y * stride + x * 4)
16479 .copy_to_nonoverlapping(px.as_mut_ptr(), 4);
16480 };
16481 px
16482 })
16483 .collect()
16484 }
16485
16486 #[test]
16487 fn emulated_conic_paints_the_same_quadrants() {
16488 let px = fanned(
16489 &quarters(),
16490 &[(75, 75), (25, 75), (25, 25), (75, 25), (2, 2)],
16491 );
16492 assert_eq!(px[0], [255, 0, 0, 255]);
16493 assert_eq!(px[1], [0, 255, 0, 255]);
16494 assert_eq!(px[2], [0, 0, 255, 255]);
16495 assert_eq!(px[3], [255, 255, 0, 255]);
16496 assert_eq!(px[4], [0, 0, 0, 0]);
16498 }
16499
16500 #[test]
16501 fn emulated_conic_is_one_even_coat() {
16502 let half = Color::rgba(0.0, 0.0, 0.0, 0.5);
16505 let gradient =
16506 ConicGradient::centered(day_spec::Angle::deg(17.0), vec![(0.0, half), (1.0, half)]);
16507 let inside: Vec<(usize, usize)> = (20..80)
16508 .flat_map(|y| (20..80).map(move |x| (x, y)))
16509 .collect();
16510 for (px, at) in fanned(&gradient, &inside).iter().zip(&inside) {
16511 assert!(
16512 px[3].abs_diff(128) <= 1,
16513 "uneven at {at:?}: alpha {}",
16514 px[3]
16515 );
16516 }
16517 }
16518
16519 #[test]
16520 fn export_shadow_is_in_points_and_scoped() {
16521 let ops = [
16524 DrawOp::Fill(rect(0.0, 0.0, 200.0, 100.0), Color::WHITE.into()),
16525 DrawOp::Save,
16526 DrawOp::Concat(Affine::scale(2.0, 2.0)),
16527 DrawOp::Save,
16528 DrawOp::Shadow(Some(
16529 Shadow::new(Color::rgb(0.0, 0.0, 0.0), 2.0).offset(0.0, 20.0),
16530 )),
16531 DrawOp::Fill(rect(15.0, 10.0, 20.0, 15.0), BLUE.into()),
16532 DrawOp::Restore,
16533 DrawOp::Restore,
16534 DrawOp::Fill(rect(130.0, 20.0, 40.0, 30.0), BLUE.into()),
16535 ];
16536 let at = [(100, 70), (100, 120), (100, 170), (300, 70), (300, 120)];
16537 let px = painted(&ops, Size::new(200.0, 100.0), 2.0, &at);
16538 assert!(near(px[0], [0, 0, 255, 255]), "{px:?}");
16539 assert!(near(px[1], [0, 0, 0, 255]), "{px:?}");
16540 assert!(near(px[2], [255, 255, 255, 255]), "{px:?}");
16541 assert!(near(px[3], [0, 0, 255, 255]), "{px:?}");
16542 assert!(near(px[4], [255, 255, 255, 255]), "{px:?}");
16543 }
16544
16545 #[test]
16546 fn export_gradient_casts_a_whole_shadow() {
16547 let ops = [
16549 DrawOp::Shadow(Some(Shadow::new(BLUE, 0.0).offset(0.0, 30.0))),
16550 DrawOp::Fill(rect(10.0, 10.0, 40.0, 20.0), quarters().into()),
16551 ];
16552 let px = painted(&ops, Size::new(60.0, 80.0), 1.0, &[(30, 50), (30, 70)]);
16553 assert!(near(px[0], [0, 0, 255, 255]), "{px:?}");
16554 assert_eq!(px[1], [0, 0, 0, 0]);
16555 }
16556
16557 #[test]
16558 fn export_blends_path_object_shapes_too() {
16559 let round = |x: f64| Shape::RoundedRect(day_spec::Rect::new(x, 0.0, 30.0, 30.0), 4.0);
16561 let ops = [
16562 DrawOp::Fill(rect(0.0, 0.0, 60.0, 60.0), YELLOW.into()),
16563 DrawOp::Save,
16564 DrawOp::Blend(BlendMode::Multiply),
16565 DrawOp::Fill(round(0.0), Color::rgb(0.0, 1.0, 1.0).into()),
16566 DrawOp::Blend(BlendMode::Erase),
16567 DrawOp::Fill(round(30.0), RED.into()),
16568 DrawOp::Restore,
16569 DrawOp::Shadow(Some(Shadow::new(BLUE, 0.0).offset(0.0, 30.0))),
16570 DrawOp::Fill(round(0.0), RED.into()),
16571 ];
16572 let px = painted(
16573 &ops,
16574 Size::new(60.0, 60.0),
16575 1.0,
16576 &[(15, 15), (45, 15), (15, 45)],
16577 );
16578 assert!(near(px[0], [255, 0, 0, 255]), "{px:?}");
16579 assert_eq!(px[1], [0, 0, 0, 0], "{px:?}");
16580 assert!(near(px[2], [0, 0, 255, 255]), "{px:?}");
16581 }
16582
16583 #[test]
16584 fn export_blends_and_erases() {
16585 let ops = [
16586 DrawOp::Fill(rect(0.0, 0.0, 90.0, 30.0), Color::WHITE.into()),
16587 DrawOp::Fill(rect(0.0, 0.0, 30.0, 30.0), YELLOW.into()),
16588 DrawOp::Save,
16589 DrawOp::Blend(BlendMode::Multiply),
16590 DrawOp::Fill(rect(0.0, 0.0, 30.0, 30.0), Color::rgb(0.0, 1.0, 1.0).into()),
16591 DrawOp::Restore,
16592 DrawOp::Fill(rect(30.0, 0.0, 30.0, 30.0), RED.into()),
16593 DrawOp::Save,
16594 DrawOp::Blend(BlendMode::Add),
16595 DrawOp::Fill(rect(30.0, 0.0, 30.0, 30.0), BLUE.into()),
16596 DrawOp::Restore,
16597 DrawOp::Save,
16598 DrawOp::Blend(BlendMode::Erase),
16599 DrawOp::Fill(rect(60.0, 0.0, 15.0, 30.0), GREEN.into()),
16600 DrawOp::Fill(rect(75.0, 0.0, 15.0, 15.0), quarters().into()),
16602 DrawOp::Restore,
16603 DrawOp::Fill(rect(80.0, 20.0, 10.0, 10.0), BLUE.into()),
16604 ];
16605 let at = [(15, 15), (45, 15), (67, 15), (82, 7), (78, 25), (85, 25)];
16606 let px = painted(&ops, Size::new(90.0, 30.0), 1.0, &at);
16607 assert!(near(px[0], [0, 255, 0, 255]), "{px:?}");
16608 assert!(near(px[1], [255, 0, 255, 255]), "{px:?}");
16609 assert_eq!(px[2], [0, 0, 0, 0], "{px:?}");
16610 assert!(near(px[3], [0, 0, 0, 0]), "{px:?}");
16611 assert!(near(px[4], [255, 255, 255, 255]), "{px:?}");
16612 assert!(near(px[5], [0, 0, 255, 255]), "{px:?}");
16614 }
16615}