1#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
27use objc2::{
28 AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSTextInputClient;
36use objc2_app_kit::NSUserInterfaceItemIdentification as _;
37use objc2_app_kit::{
38 NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
39 NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
40};
41use objc2_app_kit::{
42 NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
43 NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
44 NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
45 NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
46 NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
47 NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
48 NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
49 NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
50 NSWindowDelegate, NSWindowStyleMask,
51};
52use objc2_app_kit::{
53 NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
54 NSApplicationWillTerminateNotification,
55};
56use objc2_app_kit::{
57 NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
58};
59use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
60use objc2_core_foundation::CGAffineTransform;
61use objc2_foundation::{
62 NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
63 NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
64};
65use objc2_quartz_core::{
66 CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
67 kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
68 kCAMediaTimingFunctionLinear,
69};
70
71use day_spec::ffi_guard;
72use day_spec::present;
73use day_spec::props::*;
74use day_spec::sidetable::SideTable;
75use day_spec::{
76 A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
77 InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
78 Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
79 WindowOptions, kinds, props_of,
80};
81
82pub type Handle = Retained<NSView>;
83
84pub use toolbar::image_for as toolbar_image;
86
87mod dock;
89mod documents;
90mod frame;
91mod picker;
92mod status_item;
93mod textarea;
94mod toolbar;
95mod transfer;
96mod window_chrome;
97use objc2_app_kit::NSDraggingSource;
98
99pub mod ext;
100pub use ext::*;
101
102type Sink = Rc<dyn Fn(NodeId, Event)>;
108
109day_core::tls_group! {
110 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
111 static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
113 static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
118 RefCell::new(HashMap::new());
119 static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
121 static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
125
126 static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
129 static APP_LABELED: SideTable<()> = SideTable::new();
132 static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
138 static TRANSFORMS: SideTable<Transform> = SideTable::new();
142 static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
145 static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
146 static SHEET_NODES: SideTable<NodeId> = SideTable::new();
148 static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149 static PAN_NODES: SideTable<NodeId> = SideTable::new();
152 static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
153 static HOVER_NODES: SideTable<NodeId> = SideTable::new();
157 static ROTATE_NODES: SideTable<NodeId> = SideTable::new();
162 static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
165 static KEY_NODES: SideTable<NodeId> = SideTable::new();
169 static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
174 static MARKED: SideTable<String> = SideTable::new();
178 static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
181
182 static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
184 RefCell::new(HashMap::new());
185
186 static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
187 static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
189 RefCell::new(std::collections::HashSet::new());
190 static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
196
197 static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
198 static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
201
202 static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
204 static SPLIT_PANES: SideTable<bool> = SideTable::new();
206
207 static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
211
212 static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
213 static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
215
216 static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
221 static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
225 const { RefCell::new(Vec::new()) };
226 static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
229 static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
232
233 static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
235
236 static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
238 const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
239 static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
240 const { std::cell::RefCell::new(None) };
241
242 static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
244 RefCell::new(HashMap::new());
245 static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
247 RefCell::new(HashMap::new());
248
249 static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
252 const { std::cell::RefCell::new(None) };
253 static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
257 const { std::cell::RefCell::new(None) };
258
259}
260
261pub fn emit(id: NodeId, ev: Event) {
263 let sink = SINK.with(|s| s.borrow().clone());
264 if let Some(sink) = sink {
265 sink(id, ev);
266 }
267}
268
269fn ptr_of(v: &NSView) -> usize {
270 (v as *const NSView).cast::<()>() as usize
271}
272
273fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
278 ffi_guard::contain((), || {
279 let key = ptr_of(btn);
281 let Some(items) =
282 day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(key)).is_some())
283 else {
284 return;
285 };
286 let menu = build_ns_menu(btn.mtm(), "", &items);
287 let bounds = btn.bounds();
288 let y = if btn.isFlipped() {
289 bounds.size.height + 2.0
290 } else {
291 -2.0
292 };
293 unsafe {
294 btn.highlight(true);
295 menu.popUpMenuPositioningItem_atLocation_inView(
297 None,
298 objc2_foundation::NSPoint::new(0.0, y),
299 Some(btn),
300 );
301 btn.highlight(false);
302 }
303 });
304}
305
306#[derive(Clone, Copy)]
308struct ImageMode {
309 template: bool,
310 tinted: bool,
311}
312
313impl ImageMode {
314 fn renders_template(self) -> bool {
317 self.template || self.tinted
318 }
319}
320
321struct AppKitBitmap {
328 image: Retained<objc2_app_kit::NSImage>,
329 rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
330 info: day_spec::BitmapInfo,
331}
332
333fn scaled_rep(
339 image: &objc2_app_kit::NSImage,
340 pixels: Size,
341 scale: f64,
342) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
343 use objc2::AllocAnyThread as _;
344 let w = (pixels.width * scale).round().max(1.0);
345 let h = (pixels.height * scale).round().max(1.0);
346 let rep = unsafe {
347 objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
348 objc2_app_kit::NSBitmapImageRep::alloc(),
349 std::ptr::null_mut(),
350 w as isize,
351 h as isize,
352 8,
353 4,
354 true,
355 false,
356 objc2_app_kit::NSDeviceRGBColorSpace,
357 0,
358 0,
359 )
360 }?;
361 let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
362 NSGraphicsContext::saveGraphicsState_class();
363 objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
364 unsafe {
365 image.drawInRect_fromRect_operation_fraction(
366 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
367 NSRect::ZERO,
368 objc2_app_kit::NSCompositingOperation::SourceOver,
369 1.0,
370 );
371 }
372 NSGraphicsContext::restoreGraphicsState_class();
373 Some(rep)
374}
375
376fn encode_bitmap(
381 id: day_spec::BitmapId,
382 spec: &day_spec::EncodeSpec,
383) -> Result<Vec<u8>, day_spec::ImageError> {
384 use day_spec::ImageFormat as F;
385 use objc2_app_kit::NSBitmapImageFileType as T;
386 let file_type = match spec.format {
387 F::Png => T::PNG,
388 F::Jpeg => T::JPEG,
389 F::Tiff => T::TIFF,
390 F::Bmp => T::BMP,
391 F::Gif => T::GIF,
392 _ => return Err(day_spec::ImageError::Encode),
396 };
397 let held = BITMAPS.with(|m| {
398 m.borrow()
399 .get(&id.0)
400 .map(|b| (b.rep.clone(), b.image.clone(), b.info))
401 });
402 let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
403 let rep = rep.ok_or(day_spec::ImageError::Encode)?;
404
405 let rep = match spec.fit {
408 Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
409 let scale = (fit.width / info.pixels.width)
410 .min(fit.height / info.pixels.height)
411 .min(1.0);
412 if scale < 1.0 {
413 scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
414 } else {
415 rep
416 }
417 }
418 _ => rep,
419 };
420
421 let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
422 Some(q) => {
424 let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
425 let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
426 let value: &objc2::runtime::AnyObject = &number;
427 NSDictionary::from_slices::<NSString>(&[key], &[value])
428 }
429 None => NSDictionary::new(),
430 };
431 let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
432 .ok_or(day_spec::ImageError::Encode)?;
433 Ok(data.to_vec())
434}
435
436fn paint_ops(ops: &[DrawOp]) {
440 let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
442 let Some(cg) = cg else {
443 for op in ops {
444 draw_op(op);
445 }
446 return;
447 };
448 cg_begin_replay(&cg);
449 for op in ops {
450 if !cg_fast_op(&cg, op) {
451 draw_op(op);
452 }
453 }
454}
455
456fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
465 use objc2_core_graphics::{CGContext, CGImage};
466 match op {
467 DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
468 let Some(even_odd) = cg_add_shape(cg, shape) else {
469 return false;
470 };
471 let c = [color.r, color.g, color.b, color.a];
472 unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
474 if even_odd {
475 CGContext::eo_fill_path(Some(cg));
476 } else {
477 CGContext::fill_path(Some(cg));
478 }
479 true
480 }
481 DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
482 if cg_add_shape(cg, shape).is_none() {
483 return false;
484 }
485 let c = [color.r, color.g, color.b, color.a];
486 unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
488 cg_stroke_style(cg, style);
489 CGContext::stroke_path(Some(cg));
490 true
491 }
492 DrawOp::Clip(shape) => {
493 let Some(even_odd) = cg_add_shape(cg, shape) else {
494 return false;
495 };
496 if even_odd {
497 CGContext::eo_clip(Some(cg));
498 } else {
499 CGContext::clip(Some(cg));
500 }
501 true
502 }
503 DrawOp::Image {
504 image,
505 rect,
506 opacity,
507 source,
508 } => {
509 let Some((cg_image, pixels)) = BITMAPS.with(|m| {
512 m.borrow().get(&image.0).and_then(|b| {
513 let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
515 Some((cg, b.info.pixels))
516 })
517 }) else {
518 return false;
519 };
520 let (cropped, dest) = match source {
524 None => (None, *rect),
525 Some(src) => {
526 let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
527 else {
528 return true;
529 };
530 let crop = CGImage::with_image_in_rect(
531 Some(&cg_image),
532 NSRect::new(
533 NSPoint::new(src.origin.x, src.origin.y),
534 NSSize::new(src.size.width, src.size.height),
535 ),
536 );
537 let Some(crop) = crop else {
538 return true;
539 };
540 (Some(crop), dest)
541 }
542 };
543 if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
544 return true;
545 }
546 CGContext::save_g_state(Some(cg));
549 CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
550 CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
551 CGContext::scale_ctm(Some(cg), 1.0, -1.0);
552 CGContext::draw_image(
553 Some(cg),
554 NSRect::new(
555 NSPoint::new(0.0, 0.0),
556 NSSize::new(dest.size.width, dest.size.height),
557 ),
558 Some(cropped.as_deref().unwrap_or(&cg_image)),
559 );
560 CGContext::restore_g_state(Some(cg));
561 true
562 }
563 _ => false,
564 }
565}
566
567fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
569 use objc2_core_graphics::{CGColorSpace, CGContext};
570 let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
572 CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
573 CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
574}
575
576fn cg_add_shape(cg: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
579 use day_spec::{PathSeg, Shape};
580 use objc2_core_graphics::CGContext;
581 CGContext::begin_path(Some(cg));
582 match shape {
583 Shape::Rect(r) => CGContext::add_rect(Some(cg), ns_rect(*r)),
584 Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(cg), ns_rect(*r)),
585 Shape::Line(a, b) => {
586 CGContext::move_to_point(Some(cg), a.x, a.y);
587 CGContext::add_line_to_point(Some(cg), b.x, b.y);
588 }
589 Shape::Polygon(pts) => {
590 let (first, rest) = pts.split_first()?;
591 if rest.is_empty() {
592 return None;
593 }
594 CGContext::move_to_point(Some(cg), first.x, first.y);
595 for p in rest {
596 CGContext::add_line_to_point(Some(cg), p.x, p.y);
597 }
598 CGContext::close_path(Some(cg));
599 }
600 Shape::Path(path) => {
601 if path.segs.is_empty() {
602 return None;
603 }
604 for seg in &path.segs {
605 match seg {
606 PathSeg::Move(a) => CGContext::move_to_point(Some(cg), a.x, a.y),
607 PathSeg::Line(a) => CGContext::add_line_to_point(Some(cg), a.x, a.y),
608 PathSeg::Quad(c, a) => {
609 CGContext::add_quad_curve_to_point(Some(cg), c.x, c.y, a.x, a.y)
610 }
611 PathSeg::Cubic(c1, c2, a) => {
612 CGContext::add_curve_to_point(Some(cg), c1.x, c1.y, c2.x, c2.y, a.x, a.y)
613 }
614 PathSeg::Close => CGContext::close_path(Some(cg)),
615 }
616 }
617 return Some(path.rule == day_spec::FillRule::EvenOdd);
618 }
619 Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
620 }
621 Some(false)
622}
623
624fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
628 use day_spec::{LineCap, LineJoin};
629 use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
630 CGContext::set_line_width(Some(cg), style.width);
631 CGContext::set_line_cap(
632 Some(cg),
633 match style.cap {
634 LineCap::Butt => CGLineCap::Butt,
635 LineCap::Round => CGLineCap::Round,
636 LineCap::Square => CGLineCap::Square,
637 },
638 );
639 CGContext::set_line_join(
640 Some(cg),
641 match style.join {
642 LineJoin::Miter => CGLineJoin::Miter,
643 LineJoin::Round => CGLineJoin::Round,
644 LineJoin::Bevel => CGLineJoin::Bevel,
645 },
646 );
647 CGContext::set_miter_limit(Some(cg), style.miter_limit);
648 if style.dash.is_empty() {
649 unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
651 } else {
652 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
653 unsafe {
655 CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len())
656 };
657 }
658}
659
660fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
668 use objc2_core_graphics::CGContext;
669 CGContext::save_g_state(Some(cg));
670 CGContext::translate_ctm(Some(cg), 0.0, height);
671 CGContext::scale_ctm(Some(cg), scale, -scale);
672 let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
673 NSGraphicsContext::saveGraphicsState_class();
674 NSGraphicsContext::setCurrentContext(Some(&ns));
675 paint_ops(ops);
676 NSGraphicsContext::restoreGraphicsState_class();
677 CGContext::restore_g_state(Some(cg));
678}
679
680struct Sendable<T>(T);
682
683unsafe impl<T> Send for Sendable<T> {}
689
690struct OffscreenResources {
695 images: Vec<(u64, AppKitBitmap)>,
696 fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
697}
698
699impl OffscreenResources {
700 fn collect(ops: &[DrawOp]) -> Self {
703 let mut images: Vec<(u64, AppKitBitmap)> = Vec::new();
704 let mut fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)> = Vec::new();
705 for op in ops {
706 match op {
707 DrawOp::Image { image, .. } => {
708 if images.iter().any(|(id, _)| *id == image.0) {
709 continue;
710 }
711 let held = BITMAPS.with(|m| {
712 m.borrow().get(&image.0).map(|b| AppKitBitmap {
713 image: b.image.clone(),
714 rep: b.rep.clone(),
715 info: b.info,
716 })
717 });
718 if let Some(bitmap) = held {
719 images.push((image.0, bitmap));
720 }
721 }
722 DrawOp::Text { size, font, .. } => {
723 let key = (size.to_bits(), font.clone());
724 if fonts.iter().any(|(k, _)| *k == key) {
725 continue;
726 }
727 let resolved = canvas_nsfont(*size, font);
728 fonts.push((key, resolved));
729 }
730 _ => {}
731 }
732 }
733 Self { images, fonts }
734 }
735
736 fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
740 let mut added_images = Vec::with_capacity(self.images.len());
741 BITMAPS.with(|m| {
742 let mut m = m.borrow_mut();
743 for (id, bitmap) in self.images {
744 if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
745 slot.insert(bitmap);
746 added_images.push(id);
747 }
748 }
749 });
750 let added_fonts = self.fonts.len();
751 OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
752 let out = paint();
753 OFFSCREEN_FONTS.with(|t| {
754 let mut t = t.borrow_mut();
755 let keep = t.len().saturating_sub(added_fonts);
756 t.truncate(keep);
757 });
758 BITMAPS.with(|m| {
759 let mut m = m.borrow_mut();
760 for id in added_images {
761 m.remove(&id);
762 }
763 });
764 out
765 }
766}
767
768fn render_bitmap_cgimage(
779 ops: &[DrawOp],
780 size: Size,
781 scale: f64,
782) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, day_spec::ExportError>
783{
784 use objc2_core_graphics::{
785 CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
786 };
787 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
788 let (pw, ph) = day_spec::export_pixels(size, scale);
789 let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
791 .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
792 let cg = unsafe {
795 CGBitmapContextCreate(
796 std::ptr::null_mut(),
797 pw as usize,
798 ph as usize,
799 8,
800 0,
801 Some(&space),
802 CGImageAlphaInfo::PremultipliedLast.0,
803 )
804 }
805 .ok_or_else(|| {
806 day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
807 })?;
808 paint_flipped(&cg, ph as f64, scale, ops);
810 CGBitmapContextCreateImage(Some(&cg))
811 .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
812}
813
814fn bitmap_from_cgimage(cg_image: &objc2_core_graphics::CGImage, scale: f64) -> AppKitBitmap {
818 use objc2::AllocAnyThread as _;
819 let rep = unsafe {
820 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
821 objc2_app_kit::NSBitmapImageRep::alloc(),
822 cg_image,
823 )
824 };
825 let (pw, ph) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
826 let points = NSSize::new(pw / scale, ph / scale);
829 unsafe { rep.setSize(points) };
830 let image =
831 unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
832 unsafe { image.addRepresentation(&rep) };
833 AppKitBitmap {
834 image,
835 rep: Some(rep),
836 info: day_spec::BitmapInfo {
837 pixels: Size::new(pw, ph),
838 scale,
839 format: None,
840 has_alpha: true,
841 },
842 }
843}
844
845fn render_pdf_bytes(
850 pages: &[day_spec::PdfPage],
851 info: &day_spec::PdfInfo,
852) -> Result<Vec<u8>, day_spec::ExportError> {
853 use objc2_core_foundation::{
854 CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
855 };
856 use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
857 let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
858 let media =
859 |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
860 let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
861 let data = CFMutableData::new(None, 0)
862 .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
863 let consumer = CGDataConsumer::with_cf_data(Some(&data))
864 .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
865
866 let mut keys: Vec<&CFString> = Vec::new();
867 let mut values: Vec<CFRetained<CFString>> = Vec::new();
868 let (title_key, author_key) = unsafe {
870 (
871 objc2_core_graphics::kCGPDFContextTitle,
872 objc2_core_graphics::kCGPDFContextAuthor,
873 )
874 };
875 for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
876 if let Some(value) = value {
877 keys.push(key);
878 values.push(CFString::from_str(value));
879 }
880 }
881 let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
882 let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
883
884 let first_box = media(first.size);
885 let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
888 .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
889 for page in pages {
890 let page_box = media(page.size);
891 unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
893 paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
894 CGContext::end_page(Some(&pdf));
895 }
896 CGPDFContextClose(Some(&pdf));
898 drop(pdf);
899 drop(consumer);
900 Ok(data.to_vec())
901}
902
903thread_local! {
904 static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
907 std::cell::RefCell::new(std::collections::HashMap::new());
908}
909
910fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
923 use objc2_app_kit::{
924 NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
925 };
926 let label = |text: &str, size: f64, secondary: bool| {
927 let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
928 unsafe {
929 tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
930 if secondary {
931 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
932 }
933 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
934 }
935 tf
936 };
937 let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
938 let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
939 const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
940 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
941 const STRETCH: f32 = 1.0;
944 const HOLD: f32 = 750.0;
945 let stack = NSStackView::new(mtm);
946 stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
947 stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
948 stack.setAlignment(NSLayoutAttribute::CenterY);
949 stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
950 stack.setSpacing(6.0);
951 stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
953 top: 4.0,
954 left: 0.0,
955 bottom: 4.0,
956 right: 0.0,
957 });
958 let icon = unsafe { NSImageView::new(mtm) };
959 unsafe {
960 icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
961 icon.widthAnchor()
962 .constraintEqualToConstant(16.0)
963 .setActive(true);
964 icon.heightAnchor()
965 .constraintEqualToConstant(16.0)
966 .setActive(true);
967 }
968 stack.addArrangedSubview(&icon);
969 let texts = NSStackView::new(mtm);
972 texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
973 texts.setAlignment(NSLayoutAttribute::Width);
974 texts.setSpacing(1.0);
975 texts.setHuggingPriority_forOrientation(
978 HOLD,
979 objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
980 );
981 let title = label("", size, false);
982 let subtitle = label("", small, true);
983 for line in [&title, &subtitle] {
985 line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
986 line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
987 }
988 texts.addArrangedSubview(&title);
989 texts.addArrangedSubview(&subtitle);
990 stack.addArrangedSubview(&texts);
991 let detail = label("", size, true);
992 detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
993 detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
994 stack.addArrangedSubview(&detail);
995 let check = unsafe { NSImageView::new(mtm) };
996 unsafe {
997 check.setImage(
998 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
999 &NSString::from_str("checkmark"),
1000 None,
1001 )
1002 .as_deref(),
1003 );
1004 check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1005 }
1006 check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1007 check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1008 stack.addArrangedSubview(&check);
1009 let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1010 LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1011 dress_list_item(&view, p, mtm);
1012 view
1013}
1014
1015fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1017 use objc2_app_kit::{NSImageView, NSStackView};
1018 let Some(stack) = view.downcast_ref::<NSStackView>() else {
1019 return;
1020 };
1021 let parts = stack.arrangedSubviews();
1022 if parts.len() < 4 {
1023 return;
1024 }
1025 let icon = parts.objectAtIndex(0);
1026 if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1027 let image = p
1028 .icon
1029 .as_ref()
1030 .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1031 unsafe {
1032 iv.setImage(image.as_deref());
1033 iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
1034 }
1035 }
1036 icon.setHidden(p.icon.is_none());
1037 if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1038 let lines = texts.arrangedSubviews();
1039 if lines.len() == 2 {
1040 if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1041 tf.setStringValue(&NSString::from_str(&p.title));
1042 }
1043 let sub = lines.objectAtIndex(1);
1044 if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1045 tf.setStringValue(&NSString::from_str(&p.subtitle));
1046 }
1047 sub.setHidden(p.subtitle.is_empty());
1048 }
1049 }
1050 let detail = parts.objectAtIndex(2);
1051 if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1052 tf.setStringValue(&NSString::from_str(&p.detail));
1053 }
1054 detail.setHidden(p.detail.is_empty());
1055 parts.objectAtIndex(3).setHidden(!p.checked);
1056 let words = [&p.title, &p.subtitle, &p.detail]
1057 .into_iter()
1058 .filter(|w| !w.is_empty())
1059 .map(String::as_str)
1060 .collect::<Vec<_>>()
1061 .join(", ");
1062 unsafe {
1063 view.setAccessibilityElement(true);
1064 view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1065 view.setAccessibilitySelected(p.checked);
1066 }
1067}
1068
1069fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1075 use objc2::AllocAnyThread as _;
1076 match source {
1077 day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1082 .or_else(|| day_spec::resource::resolve_image_file(name))
1083 .and_then(|path| unsafe {
1084 objc2_app_kit::NSImage::initWithContentsOfFile(
1085 objc2_app_kit::NSImage::alloc(),
1086 &NSString::from_str(&path.to_string_lossy()),
1087 )
1088 }),
1089 day_spec::ImageSource::Bytes(bytes) => unsafe {
1092 objc2_app_kit::NSImage::initWithData(
1093 objc2_app_kit::NSImage::alloc(),
1094 &NSData::with_bytes(bytes),
1095 )
1096 },
1097 day_spec::ImageSource::Decoded(id) => {
1099 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1100 }
1101 }
1102}
1103
1104fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1107 use day_spec::Role;
1108 use objc2_app_kit::{
1109 NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1110 NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1111 NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1112 NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1113 };
1114 unsafe {
1115 Some(match role {
1116 Role::Button => NSAccessibilityButtonRole,
1117 Role::Toggle => NSAccessibilityCheckBoxRole,
1118 Role::Tab => NSAccessibilityRadioButtonRole,
1121 Role::TabList => NSAccessibilityTabGroupRole,
1122 Role::Slider => NSAccessibilitySliderRole,
1123 Role::TextInput => NSAccessibilityTextFieldRole,
1124 Role::Heading(_) => NSAccessibilityHeadingRole,
1129 Role::Image => NSAccessibilityImageRole,
1130 Role::Meter => NSAccessibilityLevelIndicatorRole,
1131 Role::Group => NSAccessibilityGroupRole,
1132 Role::Tree => NSAccessibilityOutlineRole,
1135 Role::TreeItem => NSAccessibilityRowRole,
1136 Role::None => return None,
1137 })
1138 }
1139}
1140
1141fn day_role_from_ns(ax: &str) -> day_spec::Role {
1143 use day_spec::Role;
1144 match ax {
1145 "AXButton" => Role::Button,
1146 "AXCheckBox" => Role::Toggle,
1147 "AXSlider" => Role::Slider,
1148 "AXTextField" => Role::TextInput,
1149 "AXStaticText" | "AXHeading" => Role::Heading(0),
1152 "AXOutline" => Role::Tree,
1153 "AXImage" => Role::Image,
1154 "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1155 "AXGroup" => Role::Group,
1156 "AXRadioButton" => Role::Tab,
1157 "AXTabGroup" => Role::TabList,
1158 _ => Role::None,
1159 }
1160}
1161
1162struct TargetIvars {
1167 node: NodeId,
1168}
1169
1170define_class!(
1171 #[unsafe(super(NSObject))]
1172 #[thread_kind = MainThreadOnly]
1173 #[name = "DayTarget"]
1174 #[ivars = TargetIvars]
1175 struct DayTarget;
1176
1177 unsafe impl NSObjectProtocol for DayTarget {}
1178 unsafe impl NSTextFieldDelegate for DayTarget {}
1179
1180 unsafe impl NSTabViewDelegate for DayTarget {
1185 #[unsafe(method(tabView:didSelectTabViewItem:))]
1186 fn tab_view_did_select(
1187 &self,
1188 tab_view: &objc2_app_kit::NSTabView,
1189 item: Option<&objc2_app_kit::NSTabViewItem>,
1190 ) {
1191 ffi_guard::contain((), || {
1192 if TAB_PICK_SUPPRESS.with(|s| s.get()) {
1193 return;
1194 }
1195 if let Some(item) = item {
1196 let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1197 if idx >= 0 {
1198 emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1199 }
1200 }
1201 })
1202 }
1203 }
1204
1205 impl DayTarget {
1206 #[unsafe(method(action:))]
1211 fn action(&self, sender: &NSControl) {
1212 ffi_guard::contain((), || {
1213 let node = self.ivars().node;
1214 if sender.downcast_ref::<NSSwitch>().is_some() {
1215 emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1216 } else if sender.downcast_ref::<NSSlider>().is_some() {
1217 let value = unsafe { sender.doubleValue() };
1218 emit(node, Event::ValueChanged(value));
1220 if slider_value_settled() {
1226 emit(node, Event::ValueCommitted(value));
1227 }
1228 } else if let (Some(f), Some(btn)) = (
1229 BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1230 sender.downcast_ref::<NSButton>(),
1231 ) {
1232 pop_button_menu(btn, &f);
1234 } else {
1235 emit(node, Event::Pressed);
1236 let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1239 if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1240 unsafe {
1241 btn.setState(if on {
1242 NSControlStateValueOn
1243 } else {
1244 NSControlStateValueOff
1245 })
1246 };
1247 }
1248 }
1249 })
1250 }
1251
1252 #[unsafe(method(navBack:))]
1255 fn nav_back(&self, _sender: &NSControl) {
1256 ffi_guard::contain((), || {
1257 emit(
1258 self.ivars().node,
1259 Event::NavBack {
1260 already_popped: false,
1261 },
1262 );
1263 })
1264 }
1265 }
1266
1267 unsafe impl NSControlTextEditingDelegate for DayTarget {
1268 #[unsafe(method(controlTextDidChange:))]
1269 fn control_text_did_change(&self, notification: &NSNotification) {
1270 ffi_guard::contain((), || {
1271 let node = self.ivars().node;
1272 if let Some(obj) = unsafe { notification.object() }
1273 && let Ok(tf) = obj.downcast::<NSTextField>() {
1274 emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1275 }
1276 })
1277 }
1278
1279 #[unsafe(method(control:textView:doCommandBySelector:))]
1285 fn control_do_command(
1286 &self,
1287 _control: &NSControl,
1288 _tv: &NSTextView,
1289 command: objc2::runtime::Sel,
1290 ) -> objc2::runtime::Bool {
1291 ffi_guard::contain(objc2::runtime::Bool::NO, || {
1292 let node = self.ivars().node;
1293 let key = if command == sel!(moveUp:) {
1294 "ArrowUp"
1295 } else if command == sel!(moveDown:) {
1296 "ArrowDown"
1297 } else if command == sel!(cancelOperation:) {
1298 "Escape"
1299 } else {
1300 return objc2::runtime::Bool::NO;
1301 };
1302 if !day_spec::keys::field_claims(node, key, 0) {
1303 return objc2::runtime::Bool::NO;
1304 }
1305 emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1306 objc2::runtime::Bool::YES
1307 })
1308 }
1309
1310 #[unsafe(method(controlTextDidEndEditing:))]
1314 fn control_text_did_end_editing(&self, notification: &NSNotification) {
1315 ffi_guard::contain((), || {
1316 let node = self.ivars().node;
1317 let movement = unsafe { notification.userInfo() }
1318 .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1319 .and_then(|n| n.downcast::<NSNumber>().ok())
1320 .map(|n| NSTextMovement(n.integerValue()))
1321 .unwrap_or(NSTextMovement::Other);
1322 if movement == NSTextMovement::Return {
1323 emit(node, Event::Submitted);
1324 } else {
1325 emit(node, Event::FocusChanged(false));
1326 }
1327 })
1328 }
1329 }
1330);
1331
1332impl DayTarget {
1333 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1334 let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1335 unsafe { msg_send![super(this), init] }
1336 }
1337}
1338
1339struct CursorIvars {
1344 cursor: RefCell<Option<Retained<NSCursor>>>,
1346 hidden: Cell<bool>,
1348 hiding: Cell<bool>,
1350}
1351
1352define_class!(
1358 #[unsafe(super(NSObject))]
1359 #[thread_kind = MainThreadOnly]
1360 #[name = "DayCursorOwner"]
1361 #[ivars = CursorIvars]
1362 struct DayCursorOwner;
1363
1364 unsafe impl NSObjectProtocol for DayCursorOwner {}
1365
1366 impl DayCursorOwner {
1367 #[unsafe(method(cursorUpdate:))]
1368 fn cursor_update(&self, _event: &NSEvent) {
1369 let iv = self.ivars();
1370 if iv.hidden.get() {
1371 if !iv.hiding.replace(true) {
1372 NSCursor::hide();
1373 }
1374 return;
1375 }
1376 if let Some(c) = iv.cursor.borrow().as_ref() {
1377 c.set();
1378 }
1379 }
1380
1381 #[unsafe(method(mouseExited:))]
1382 fn mouse_exited(&self, _event: &NSEvent) {
1383 if self.ivars().hiding.replace(false) {
1384 NSCursor::unhide();
1385 }
1386 }
1387 }
1388);
1389
1390impl DayCursorOwner {
1391 fn new(mtm: MainThreadMarker) -> Retained<Self> {
1392 let this = Self::alloc(mtm).set_ivars(CursorIvars {
1393 cursor: RefCell::new(None),
1394 hidden: Cell::new(false),
1395 hiding: Cell::new(false),
1396 });
1397 unsafe { msg_send![super(this), init] }
1398 }
1399}
1400
1401#[allow(deprecated)]
1409fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1410 let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1411 Some(match c {
1412 Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1413 Cursor::Pointer => NSCursor::pointingHandCursor(),
1414 Cursor::Text => NSCursor::IBeamCursor(),
1415 Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1416 Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1417 Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1418 Cursor::Grabbing => NSCursor::closedHandCursor(),
1419 Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1420 Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1421 Cursor::Copy => NSCursor::dragCopyCursor(),
1422 Cursor::Alias => NSCursor::dragLinkCursor(),
1423 Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1424 Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1425 Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1426 Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1427 Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1428 Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1429 NSCursor::frameResizeCursorFromPosition_inDirections(
1430 NSCursorFrameResizePosition::TopRight,
1431 NSCursorFrameResizeDirections::All,
1432 )
1433 }
1434 Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1435 NSCursor::frameResizeCursorFromPosition_inDirections(
1436 NSCursorFrameResizePosition::TopLeft,
1437 NSCursorFrameResizeDirections::All,
1438 )
1439 }
1440 Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1441 Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1442 Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1443 Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1444 Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1445 Cursor::None => return None,
1446 Cursor::Native(name) => match &**name {
1447 "disappearingItem" => NSCursor::disappearingItemCursor(),
1448 "dragCopy" => NSCursor::dragCopyCursor(),
1449 "dragLink" => NSCursor::dragLinkCursor(),
1450 "contextualMenu" => NSCursor::contextualMenuCursor(),
1451 "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1452 _ => return None,
1453 },
1454 })
1455}
1456
1457fn slider_value_settled() -> bool {
1464 let Some(mtm) = MainThreadMarker::new() else {
1465 return false;
1466 };
1467 let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1468 return false;
1469 };
1470 matches!(
1471 unsafe { event.r#type() },
1472 NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1473 )
1474}
1475
1476struct FieldIvars {
1481 node: NodeId,
1482}
1483
1484struct SharePickerIvars {
1487 actions: Vec<day_spec::share::ShareAction>,
1488}
1489
1490define_class!(
1491 #[unsafe(super(NSObject))]
1492 #[thread_kind = MainThreadOnly]
1493 #[name = "DaySharePickerDelegate"]
1494 #[ivars = SharePickerIvars]
1495 struct DaySharePickerDelegate;
1496
1497 unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1498
1499 impl DaySharePickerDelegate {
1500 #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1501 fn services(
1502 &self,
1503 _picker: &AnyObject,
1504 _items: &AnyObject,
1505 proposed: &objc2_foundation::NSArray<AnyObject>,
1506 ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1507 let mut services: Vec<Retained<AnyObject>> = Vec::new();
1508 for action in &self.ivars().actions {
1509 let id = action.id;
1510 let handler = block2::RcBlock::new(move || {
1511 ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1512 });
1513 let image = action.symbol.and_then(|s| {
1514 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1515 &NSString::from_str(day_spec::sf_symbol_name(s)),
1516 None,
1517 )
1518 });
1519 let service: Option<Retained<AnyObject>> = unsafe {
1522 let alloc: objc2::rc::Allocated<AnyObject> =
1523 msg_send![objc2::class!(NSSharingService), alloc];
1524 msg_send![
1525 alloc,
1526 initWithTitle: &*NSString::from_str(&action.title),
1527 image: image.as_deref(),
1528 alternateImage: None::<&AnyObject>,
1529 handler: &*handler
1530 ]
1531 };
1532 services.extend(service);
1533 }
1534 let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1537 all.extend(services);
1538 objc2_foundation::NSArray::from_retained_slice(&all)
1539 }
1540 }
1541);
1542
1543define_class!(
1544 #[unsafe(super(NSTextField))]
1545 #[thread_kind = MainThreadOnly]
1546 #[name = "DayTextField"]
1547 #[ivars = FieldIvars]
1548 struct DayTextField;
1549
1550 impl DayTextField {
1551 #[unsafe(method(becomeFirstResponder))]
1556 fn become_first_responder(&self) -> bool {
1557 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1558 if ok {
1559 field_gained_focus(self.ivars().node);
1560 }
1561 ok
1562 }
1563 }
1564);
1565
1566impl DayTextField {
1567 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1568 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1569 unsafe { msg_send![super(this), init] }
1570 }
1571}
1572
1573define_class!(
1578 #[unsafe(super(NSSecureTextField))]
1579 #[thread_kind = MainThreadOnly]
1580 #[name = "DaySecureTextField"]
1581 #[ivars = FieldIvars]
1582 struct DaySecureTextField;
1583
1584 impl DaySecureTextField {
1585 #[unsafe(method(becomeFirstResponder))]
1587 fn become_first_responder(&self) -> bool {
1588 let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1589 if ok {
1590 field_gained_focus(self.ivars().node);
1591 }
1592 ok
1593 }
1594 }
1595);
1596
1597impl DaySecureTextField {
1598 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1599 let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1600 unsafe { msg_send![super(this), init] }
1601 }
1602}
1603
1604thread_local! {
1605 static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1608}
1609
1610fn field_gained_focus(node: NodeId) {
1613 if FIELD_SWAP.with(|s| s.get()) {
1614 return;
1615 }
1616 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1619}
1620
1621fn text_field_node(v: &NSView) -> Option<NodeId> {
1624 v.downcast_ref::<DayTextField>()
1625 .map(|f| f.ivars().node)
1626 .or_else(|| {
1627 v.downcast_ref::<DaySecureTextField>()
1628 .map(|f| f.ivars().node)
1629 })
1630}
1631
1632fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1636 let target = DayTarget::new(mtm, node);
1637 let tf: Retained<NSTextField> = if secure {
1640 Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1641 } else {
1642 Retained::into_super(DayTextField::new(mtm, node))
1643 };
1644 unsafe {
1645 tf.setEditable(true);
1646 tf.setBezeled(true);
1647 tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1648 }
1649 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1650 tf
1651}
1652
1653fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1657 window.firstResponder().is_some_and(|fr| {
1658 if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1659 return true;
1660 }
1661 fr.downcast::<NSText>().is_ok_and(|text| {
1662 unsafe { text.delegate() }
1663 .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1664 })
1665 })
1666}
1667
1668fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1673 unsafe extern "C" {
1674 fn dlsym(
1675 handle: *mut std::ffi::c_void,
1676 symbol: *const std::ffi::c_char,
1677 ) -> *mut std::ffi::c_void;
1678 }
1679 const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1681 unsafe {
1685 let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1686 if slot.is_null() {
1687 None
1688 } else {
1689 (*slot).as_ref()
1690 }
1691 }
1692}
1693
1694fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1696 if let Some(v) = table.take(old) {
1697 table.insert(new, v);
1698 }
1699}
1700
1701struct LabelIvars {
1706 node: NodeId,
1707 has_links: Cell<bool>,
1708 has_runs: Cell<bool>,
1709 selectable: Cell<bool>,
1710}
1711
1712define_class!(
1713 #[unsafe(super(NSTextField))]
1714 #[thread_kind = MainThreadOnly]
1715 #[name = "DayLabel"]
1716 #[ivars = LabelIvars]
1717 struct DayLabel;
1718
1719 impl DayLabel {
1720 #[unsafe(method_id(menuForEvent:))]
1721 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1722 ffi_guard::contain(None, || {
1723 if !self.isSelectable()
1724 && let Some(menu) = inherited_context_menu(self, event)
1725 {
1726 return menu;
1727 }
1728 unsafe { msg_send![super(self), menuForEvent: event] }
1729 })
1730 }
1731
1732 #[unsafe(method(drawRect:))]
1733 fn draw_rect(&self, dirty: NSRect) {
1734 let mut ancestor = unsafe { self.superview() };
1738 let mut selection_color = None;
1739 if !self.ivars().has_runs.get() {
1740 while let Some(view) = ancestor {
1741 if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1742 if unsafe { row.isSelected() } {
1743 selection_color = Some(unsafe {
1744 if row.isEmphasized() {
1745 objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1746 } else {
1747 objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1748 }
1749 });
1750 }
1751 break;
1752 }
1753 ancestor = unsafe { view.superview() };
1754 }
1755 }
1756 let cell = unsafe { self.cell() }
1757 .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1758 if let (Some(color), Some(cell)) = (selection_color, cell) {
1759 let original = unsafe { cell.textColor() };
1760 unsafe {
1763 cell.setTextColor(Some(&color));
1764 let _: () = msg_send![super(self), drawRect: dirty];
1765 cell.setTextColor(original.as_deref());
1766 }
1767 } else {
1768 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1769 }
1770 }
1771 }
1772
1773 unsafe impl NSObjectProtocol for DayLabel {}
1774 unsafe impl NSTextDelegate for DayLabel {}
1775
1776 unsafe impl NSTextViewDelegate for DayLabel {
1777 #[unsafe(method(textView:clickedOnLink:atIndex:))]
1778 fn clicked_on_link(
1779 &self,
1780 _tv: &NSTextView,
1781 link: &objc2::runtime::AnyObject,
1782 _index: usize,
1783 ) -> bool {
1784 ffi_guard::contain(true, || {
1785 let url: Retained<NSString> = unsafe { msg_send![link, description] };
1787 emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1788 true })
1790 }
1791 }
1792);
1793
1794impl DayLabel {
1795 fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1796 let this = Self::alloc(mtm).set_ivars(LabelIvars {
1797 node,
1798 has_links: Cell::new(false),
1799 has_runs: Cell::new(false),
1800 selectable: Cell::new(false),
1801 });
1802 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1803 unsafe {
1804 this.setStringValue(&NSString::from_str(text));
1805 this.setEditable(false);
1806 this.setSelectable(false);
1807 this.setBordered(false);
1808 this.setBezeled(false);
1809 this.setDrawsBackground(false);
1810 }
1811 this
1812 }
1813
1814 fn set_links(&self, has_links: bool) {
1815 self.ivars().has_links.set(has_links);
1816 unsafe {
1817 self.setSelectable(has_links || self.ivars().selectable.get());
1818 self.setAllowsEditingTextAttributes(has_links);
1819 }
1820 }
1821}
1822
1823struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1824impl Drop for PanMonitor {
1825 fn drop(&mut self) {
1826 unsafe { NSEvent::removeMonitor(&self.0) };
1827 }
1828}
1829
1830fn install_sheet_escape_monitor() {
1835 SHEET_ESCAPE_MONITOR.with(|slot| {
1836 if slot.borrow().is_some() {
1837 return;
1838 }
1839 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1840 let event = unsafe { raw.as_ref() };
1841 ffi_guard::contain(raw.as_ptr(), || {
1842 let Some(mtm) = MainThreadMarker::new() else {
1843 return raw.as_ptr();
1844 };
1845 let escape = unsafe { event.charactersIgnoringModifiers() }
1846 .is_some_and(|s| s.to_string() == "\u{1b}");
1847 let Some(window) = event.window(mtm).filter(|_| escape) else {
1848 return raw.as_ptr();
1849 };
1850 let app = NSApplication::sharedApplication(mtm);
1851 if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1852 return raw.as_ptr();
1853 }
1854 match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1855 Some(node) => {
1856 emit(
1857 node,
1858 Event::NavBack {
1859 already_popped: false,
1860 },
1861 );
1862 std::ptr::null_mut()
1863 }
1864 None => raw.as_ptr(),
1865 }
1866 })
1867 });
1868 let monitor = unsafe {
1869 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1870 objc2_app_kit::NSEventMask::KeyDown,
1871 &block,
1872 )
1873 };
1874 *slot.borrow_mut() = monitor.map(PanMonitor);
1875 });
1876}
1877
1878fn install_container_pan_monitor() {
1881 PAN_MONITOR.with(|slot| {
1882 if slot.borrow().is_some() {
1883 return;
1884 }
1885 let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1886 let event = unsafe { raw.as_ref() };
1887 ffi_guard::contain(raw.as_ptr(), || {
1888 let dx = unsafe { event.scrollingDeltaX() };
1889 let dy = unsafe { event.scrollingDeltaY() };
1890 if dx.abs() <= dy.abs() {
1891 return raw.as_ptr();
1892 }
1893 let Some(mtm) = MainThreadMarker::new() else {
1894 return raw.as_ptr();
1895 };
1896 let Some(window) = event.window(mtm) else {
1897 return raw.as_ptr();
1898 };
1899 let Some(content) = window.contentView() else {
1900 return raw.as_ptr();
1901 };
1902 let point =
1903 content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1904 let mut view = content.hitTest(point);
1905 while let Some(v) = view {
1906 if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1907 if v.downcast_ref::<DayCanvas>().is_some() {
1908 return raw.as_ptr();
1909 }
1910 let raw_phase = unsafe { event.phase() };
1911 let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1912 day_spec::DragPhase::Began
1913 } else if raw_phase.intersects(
1914 objc2_app_kit::NSEventPhase::Ended
1915 | objc2_app_kit::NSEventPhase::Cancelled,
1916 ) {
1917 day_spec::DragPhase::Ended
1918 } else {
1919 day_spec::DragPhase::Changed
1920 };
1921 let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1922 emit(
1923 node,
1924 Event::Pan {
1925 phase,
1926 delta: Point::new(dx, dy),
1927 location: Point::new(p.x, p.y),
1928 },
1929 );
1930 return std::ptr::null_mut();
1931 }
1932 view = unsafe { v.superview() };
1933 }
1934 raw.as_ptr()
1935 })
1936 });
1937 *slot.borrow_mut() = unsafe {
1938 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1939 objc2_app_kit::NSEventMask::ScrollWheel,
1940 &block,
1941 )
1942 }
1943 .map(PanMonitor);
1944 });
1945}
1946
1947type Surface = (f64, f64, f64, f64, f64);
1953
1954#[derive(Default)]
1955struct FlippedIvars {
1956 surface: Cell<Option<Surface>>,
1957 section_card: Cell<Option<f64>>,
1960 pane_backdrop: Cell<bool>,
1967}
1968
1969define_class!(
1970 #[unsafe(super(NSView))]
1971 #[thread_kind = MainThreadOnly]
1972 #[name = "DayFlipped"]
1973 #[ivars = FlippedIvars]
1974 struct DayFlipped;
1975
1976 impl DayFlipped {
1977 #[unsafe(method_id(menuForEvent:))]
1978 fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1979 ffi_guard::contain(None, || {
1980 inherited_context_menu(self, event)
1981 .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1982 })
1983 }
1984
1985 #[unsafe(method(isFlipped))]
1986 fn is_flipped(&self) -> bool {
1987 true
1988 }
1989
1990 #[unsafe(method(acceptsFirstResponder))]
1994 fn accepts_first_responder(&self) -> bool {
1995 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1996 FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1997 }
1998
1999 #[unsafe(method(mouseDown:))]
2003 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2004 if transfer::pressed(self, event) { return; }
2005 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2006 if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2007 && let Some(window) = self.window()
2008 {
2009 window.makeFirstResponder(Some(self));
2010 }
2011 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2012 }
2013
2014 #[unsafe(method(becomeFirstResponder))]
2015 fn become_first_responder(&self) -> bool {
2016 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2017 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2018 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2019 }
2020 true
2021 }
2022
2023 #[unsafe(method(resignFirstResponder))]
2024 fn resign_first_responder(&self) -> bool {
2025 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2026 if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2027 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2028 }
2029 true
2030 }
2031
2032 #[unsafe(method(keyDown:))]
2036 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2037 let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2038 let handled = ffi_guard::contain(false, || {
2039 let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2040 return false;
2041 };
2042 let Some(key) = key_name(event) else {
2043 return false;
2044 };
2045 if !day_spec::keys::handled(node) {
2046 return false;
2047 }
2048 emit(
2049 node,
2050 Event::Key(day_spec::KeyEvent::named(
2051 key,
2052 key_modifiers(event.modifierFlags()),
2053 )),
2054 );
2055 true
2056 });
2057 if !handled {
2058 let _: () = unsafe { msg_send![super(self), keyDown: event] };
2059 }
2060 }
2061
2062 #[unsafe(method(rightMouseDown:))]
2066 fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2067 if let Some(menu) = self.menuForEvent(event) {
2068 unsafe {
2069 objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
2070 };
2071 } else {
2072 let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2073 }
2074 }
2075
2076 #[unsafe(method(drawRect:))]
2077 fn draw_rect(&self, _dirty: NSRect) {
2078 let paint = || {
2079 if self.ivars().pane_backdrop.get() {
2080 let bounds = self.bounds();
2081 unsafe {
2082 NSColor::windowBackgroundColor().setFill();
2085 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2086 }
2087 }
2088 if let Some(radius) = self.ivars().section_card.get() {
2089 let bounds = self.bounds();
2090 unsafe {
2091 let cls = objc2::class!(NSColor);
2094 let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2095 let color: objc2::rc::Retained<NSColor> = if has {
2096 msg_send![cls, quaternarySystemFillColor]
2097 } else {
2098 msg_send![cls, controlBackgroundColor]
2099 };
2100 color.setFill();
2101 let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2102 bounds, radius, radius,
2103 );
2104 path.fill();
2105 }
2106 }
2107 if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
2108 let bounds = self.bounds();
2109 unsafe {
2110 NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
2111 let path = if radius > 0.0 {
2112 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2113 bounds, radius, radius,
2114 )
2115 } else {
2116 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
2117 };
2118 path.fill();
2119 }
2120 }
2121 };
2122 unsafe {
2131 let names = objc2_foundation::NSArray::from_slice(&[
2132 objc2_app_kit::NSAppearanceNameAqua,
2133 objc2_app_kit::NSAppearanceNameDarkAqua,
2134 ]);
2135 let standard = self
2136 .effectiveAppearance()
2137 .bestMatchFromAppearancesWithNames(&names)
2138 .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
2139 match standard {
2140 Some(appearance) => {
2141 let block = block2::StackBlock::new(paint);
2142 appearance.performAsCurrentDrawingAppearance(&block);
2143 }
2144 None => paint(),
2145 }
2146 }
2147 }
2148 }
2149 unsafe impl NSObjectProtocol for DayFlipped {}
2150 unsafe impl NSDraggingSource for DayFlipped {
2151 #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2152 fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2153 }
2154 impl DayFlipped {
2155 #[unsafe(method(mouseDragged:))]
2156 fn transfer_dragged(&self, event: &NSEvent) {
2157 if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
2158 }
2159 #[unsafe(method(draggingEntered:))]
2160 fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2161 #[unsafe(method(draggingUpdated:))]
2162 fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2163 #[unsafe(method(performDragOperation:))]
2164 fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
2165 }
2166
2167);
2168
2169impl DayFlipped {
2170 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2171 let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
2172 unsafe { msg_send![super(this), init] }
2173 }
2174
2175 fn set_section_card(&self, corner_radius: f64) {
2181 self.ivars().section_card.set(Some(corner_radius));
2182 unsafe {
2183 let _: () = msg_send![self, setNeedsDisplay: true];
2184 }
2185 }
2186
2187 fn set_pane_backdrop(&self) {
2189 self.ivars().pane_backdrop.set(true);
2190 unsafe {
2191 let _: () = msg_send![self, setNeedsDisplay: true];
2192 }
2193 }
2194
2195 fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
2196 self.ivars()
2197 .surface
2198 .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
2199 unsafe {
2200 let _: () = msg_send![self, setNeedsDisplay: true];
2201 if clips || corner_radius > 0.0 {
2202 let _: () = msg_send![self, setWantsLayer: true];
2203 let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
2204 if !layer.is_null() {
2205 let _: () = msg_send![layer, setCornerRadius: corner_radius];
2206 let _: () = msg_send![layer, setMasksToBounds: true];
2207 }
2208 }
2209 }
2210 }
2211}
2212
2213struct CanvasIvars;
2218
2219define_class!(
2220 #[unsafe(super(NSView))]
2221 #[thread_kind = MainThreadOnly]
2222 #[name = "DayCanvas"]
2223 #[ivars = CanvasIvars]
2224 struct DayCanvas;
2225
2226 impl DayCanvas {
2227 #[unsafe(method(isFlipped))]
2228 fn is_flipped(&self) -> bool {
2229 true
2230 }
2231
2232 #[unsafe(method_id(menuForEvent:))]
2236 fn menu_for_event(
2237 &self,
2238 event: &objc2_app_kit::NSEvent,
2239 ) -> Option<Retained<NSMenu>> {
2240 let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
2241 let Some(f) = f else {
2242 return unsafe { msg_send![super(self), menuForEvent: event] };
2243 };
2244 ffi_guard::contain(None, || {
2246 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2247 let items = f(day_spec::Point::new(p.x, p.y));
2248 if items.is_empty() {
2249 return None;
2250 }
2251 Some(build_ns_menu(self.mtm(), "", &items))
2252 })
2253 }
2254
2255 #[unsafe(method(acceptsFirstResponder))]
2260 fn accepts_first_responder(&self) -> bool {
2261 true
2262 }
2263
2264 #[unsafe(method(mouseDown:))]
2268 fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2269 if let Some(window) = self.window() {
2270 window.makeFirstResponder(Some(self));
2271 }
2272 let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2273 }
2274
2275 #[unsafe(method(becomeFirstResponder))]
2278 fn become_first_responder(&self) -> bool {
2279 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2280 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2281 ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2282 }
2283 true
2284 }
2285
2286 #[unsafe(method(resignFirstResponder))]
2287 fn resign_first_responder(&self) -> bool {
2288 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2289 if MARKED.with(|t| t.remove(ptr)).is_some()
2292 && let Some(context) = self.inputContext()
2293 {
2294 context.discardMarkedText();
2295 }
2296 if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2297 ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2298 }
2299 true
2300 }
2301
2302 #[unsafe(method(keyDown:))]
2308 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2309 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2310 let handled = ffi_guard::contain(false, || {
2311 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2312 return false;
2313 };
2314 if !day_spec::keys::handled(node) {
2318 return false;
2319 }
2320 if day_spec::keys::text(node) {
2321 return full_route_key_down(self, node, event);
2322 }
2323 let Some(key) = key_name(event) else {
2324 return false;
2325 };
2326 emit(
2327 node,
2328 Event::Key(day_spec::KeyEvent::named(
2329 key,
2330 key_modifiers(event.modifierFlags()),
2331 )),
2332 );
2333 true
2334 });
2335 if !handled {
2336 let _: () = unsafe { msg_send![super(self), keyDown: event] };
2337 }
2338 }
2339
2340 #[unsafe(method_id(inputContext))]
2345 fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
2346 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2347 let takes_keyboard = KEY_NODES
2348 .with(|t| t.get(ptr))
2349 .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
2350 if takes_keyboard {
2351 unsafe { msg_send![super(self), inputContext] }
2352 } else {
2353 None
2354 }
2355 }
2356
2357 #[unsafe(method(drawRect:))]
2358 fn draw_rect(&self, _dirty: NSRect) {
2359 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2360 let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
2361 paint_ops(&ops);
2362 }
2363
2364 #[unsafe(method(mouseEntered:))]
2367 fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
2368 self.report_hover(event, day_spec::DragPhase::Began);
2369 }
2370
2371 #[unsafe(method(mouseMoved:))]
2372 fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
2373 self.report_hover(event, day_spec::DragPhase::Changed);
2374 }
2375
2376 #[unsafe(method(mouseExited:))]
2377 fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
2378 self.report_hover(event, day_spec::DragPhase::Ended);
2379 }
2380
2381 #[unsafe(method(rotateWithEvent:))]
2386 fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
2387 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2388 let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
2389 let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
2390 return;
2391 };
2392 ffi_guard::contain((), || {
2393 let tick = -f64::from(event.rotation()).to_radians();
2394 let raw = event.phase();
2395 let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2396 ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
2397 (day_spec::DragPhase::Began, tick)
2398 } else if raw.intersects(
2399 objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
2400 ) {
2401 let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
2402 (day_spec::DragPhase::Ended, total)
2403 } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
2404 let total = ROTATE_ANGLE
2405 .with(|t| {
2406 t.with(ptr, |a| {
2407 *a += tick;
2408 *a
2409 })
2410 })
2411 .unwrap_or(tick);
2412 (day_spec::DragPhase::Changed, total)
2413 } else {
2414 (day_spec::DragPhase::Changed, tick)
2415 };
2416 let win = event.locationInWindow();
2417 let loc = self.convertPoint_fromView(win, None);
2418 emit(
2419 node,
2420 Event::Rotate {
2421 phase,
2422 rotation,
2423 location: Point::new(loc.x, loc.y),
2424 },
2425 );
2426 })
2427 }
2428
2429 #[unsafe(method(scrollWheel:))]
2430 fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
2431 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2432 let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
2433 let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
2434 return;
2435 };
2436 ffi_guard::contain((), || {
2437 let raw = unsafe { event.phase() };
2440 let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2441 day_spec::DragPhase::Began
2442 } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
2443 || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
2444 {
2445 day_spec::DragPhase::Ended
2446 } else {
2447 day_spec::DragPhase::Changed
2448 };
2449 let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
2450 event.scrollingDeltaY()
2451 });
2452 let win = unsafe { event.locationInWindow() };
2453 let loc = self.convertPoint_fromView(win, None);
2454 emit(
2455 node,
2456 Event::Pan {
2457 phase,
2458 delta,
2459 location: Point::new(loc.x, loc.y),
2460 },
2461 );
2462 })
2463 }
2464 }
2465
2466 unsafe impl NSObjectProtocol for DayCanvas {}
2467
2468 unsafe impl NSTextInputClient for DayCanvas {
2472 #[unsafe(method(insertText:replacementRange:))]
2473 unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
2474 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2475 MARKED.with(|t| t.remove(ptr));
2476 let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2477 return;
2478 };
2479 let text = text_of_input_string(string);
2480 if text.is_empty() {
2481 return;
2482 }
2483 ffi_guard::contain((), || {
2484 let interpreting = INTERPRETING.with(|i| i.borrow().clone());
2485 let event = match interpreting {
2486 Some((key, mods)) if text.chars().count() == 1 => {
2488 day_spec::KeyEvent::typed_by(key, text, mods)
2489 }
2490 Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
2491 None => day_spec::KeyEvent::typed_text(text, 0),
2493 };
2494 emit(node, Event::Key(event));
2495 });
2496 }
2497
2498 #[unsafe(method(doCommandBySelector:))]
2503 unsafe fn do_command_by_selector(&self, _selector: Sel) {}
2504
2505 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
2506 unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2507 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2508 let text = text_of_input_string(string);
2509 if text.is_empty() {
2510 MARKED.with(|t| t.remove(ptr));
2511 } else {
2512 MARKED.with(|t| t.insert(ptr, text));
2513 }
2514 }
2515
2516 #[unsafe(method(unmarkText))]
2517 fn unmark_text(&self) {
2518 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2519 MARKED.with(|t| t.remove(ptr));
2520 }
2521
2522 #[unsafe(method(selectedRange))]
2523 fn selected_range(&self) -> NSRange {
2524 NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2525 }
2526
2527 #[unsafe(method(markedRange))]
2528 fn marked_range(&self) -> NSRange {
2529 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2530 match MARKED.with(|t| t.get(ptr)) {
2531 Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2532 None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2533 }
2534 }
2535
2536 #[unsafe(method(hasMarkedText))]
2537 fn has_marked_text(&self) -> bool {
2538 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2539 MARKED.with(|t| t.contains(ptr))
2540 }
2541
2542 #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2543 unsafe fn attributed_substring(
2544 &self,
2545 _range: NSRange,
2546 _actual: objc2_foundation::NSRangePointer,
2547 ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2548 None
2549 }
2550
2551 #[unsafe(method_id(validAttributesForMarkedText))]
2552 fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2553 NSArray::new()
2554 }
2555
2556 #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2559 unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2560 let bounds = self.bounds();
2561 let in_window = self.convertRect_toView(bounds, None);
2562 match self.window() {
2563 Some(window) => window.convertRectToScreen(in_window),
2564 None => in_window,
2565 }
2566 }
2567
2568 #[unsafe(method(characterIndexForPoint:))]
2569 fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2570 objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2571 }
2572 }
2573);
2574
2575impl DayCanvas {
2576 fn new(mtm: MainThreadMarker) -> Retained<Self> {
2577 let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2578 unsafe { msg_send![super(this), init] }
2579 }
2580
2581 fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2589 let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2590 let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2591 return;
2592 };
2593 ffi_guard::contain((), || {
2594 let win = unsafe { event.locationInWindow() };
2595 let loc = self.convertPoint_fromView(win, None);
2596 let b = self.bounds();
2597 let inside = loc.x >= b.origin.x
2598 && loc.x <= b.origin.x + b.size.width
2599 && loc.y >= b.origin.y
2600 && loc.y <= b.origin.y + b.size.height;
2601 if !inside && phase != day_spec::DragPhase::Ended {
2604 return;
2605 }
2606 emit(
2607 node,
2608 Event::Hover {
2609 phase,
2610 location: Point::new(loc.x, loc.y),
2611 },
2612 );
2613 });
2614 }
2615}
2616
2617fn install_tracking_area(h: &NSView) {
2621 let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2622 | NSTrackingAreaOptions::MouseMoved
2623 | NSTrackingAreaOptions::ActiveInKeyWindow
2624 | NSTrackingAreaOptions::InVisibleRect;
2625 let any: &objc2::runtime::AnyObject = h;
2626 let area = unsafe {
2627 NSTrackingArea::initWithRect_options_owner_userInfo(
2628 NSTrackingArea::alloc(),
2629 NSRect::ZERO,
2630 opts,
2631 Some(any),
2632 None,
2633 )
2634 };
2635 unsafe { h.addTrackingArea(&area) };
2636}
2637
2638struct GestureIvars {
2643 node: NodeId,
2644 kind: day_spec::GestureKind,
2645}
2646
2647define_class!(
2648 #[unsafe(super(NSObject))]
2649 #[thread_kind = MainThreadOnly]
2650 #[name = "DayGesture"]
2651 #[ivars = GestureIvars]
2652 struct DayGesture;
2653
2654 unsafe impl NSObjectProtocol for DayGesture {}
2655
2656 impl DayGesture {
2657 #[unsafe(method(fire:))]
2658 fn fire(&self, g: &NSGestureRecognizer) {
2659 ffi_guard::contain((), || {
2660 let node = self.ivars().node;
2661 let view = g.view();
2662 let loc = g.locationInView(view.as_deref());
2663 let at = Point::new(loc.x, loc.y);
2664 let phase = match g.state() {
2665 NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2666 NSGestureRecognizerState::Ended
2667 | NSGestureRecognizerState::Cancelled
2668 | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2669 _ => day_spec::DragPhase::Changed,
2670 };
2671 let obj: &objc2::runtime::AnyObject = g.as_ref();
2672 match self.ivars().kind {
2673 day_spec::GestureKind::Drag => {
2674 let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2675 let t = unsafe { pan.translationInView(view.as_deref()) };
2676 Point::new(t.x, t.y)
2677 } else {
2678 Point::ZERO
2679 };
2680 emit(node, Event::Drag { phase, location: at, translation });
2681 }
2682 day_spec::GestureKind::Pinch => {
2683 let scale = if let Some(m) =
2686 obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2687 {
2688 1.0 + unsafe { m.magnification() }
2689 } else {
2690 1.0
2691 };
2692 emit(node, Event::Pinch { phase, scale, location: at });
2693 }
2694 _ => emit(node, Event::Tap(at)),
2695 }
2696 })
2697 }
2698 }
2699);
2700
2701impl DayGesture {
2702 fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2703 let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2704 unsafe { msg_send![super(this), init] }
2705 }
2706}
2707
2708struct NavHeader {
2717 bar: Retained<NSView>,
2718 title: Retained<NSTextField>,
2719 titles: Vec<String>,
2721 _target: Retained<DayTarget>,
2722}
2723
2724const NAV_HEADER_H: f64 = 34.0;
2726
2727use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2731
2732fn take_list_placement(state: &mut NavState) -> Option<f64> {
2736 if !state.list_visible || state.list_positioned {
2737 return None;
2738 }
2739 state.list_positioned = true;
2740 state.list_width
2741}
2742
2743const NAV_TABVIEW_INSET: f64 = 12.0;
2746const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2747
2748struct TabHost {
2760 view: Retained<objc2_app_kit::NSTabView>,
2761 target: Option<Retained<DayTarget>>,
2764}
2765
2766thread_local! {
2767 static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2770}
2771
2772fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2776 unsafe {
2777 let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2778 for (i, title) in titles.iter().enumerate().take(n) {
2779 tabs.view
2780 .tabViewItemAtIndex(i as isize)
2781 .setLabel(&NSString::from_str(title));
2782 }
2783 if n > 0 {
2784 TAB_PICK_SUPPRESS.with(|s| s.set(true));
2785 tabs.view
2786 .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2787 TAB_PICK_SUPPRESS.with(|s| s.set(false));
2788 }
2789 }
2790}
2791
2792fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2796 let Some((titles, node)) = NAV_MENUS.with(|m| {
2797 m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2798 let ivars = d.ivars();
2799 (
2800 ivars
2801 .items
2802 .borrow()
2803 .iter()
2804 .map(|s| s.to_string())
2805 .collect::<Vec<String>>(),
2806 ivars.node,
2807 )
2808 })
2809 }) else {
2810 return;
2811 };
2812 let mut up = unsafe { menu.superview() };
2813 while let Some(v) = up {
2814 let reached = NAV_STATE.with(|m| {
2815 let mut m = m.borrow_mut();
2816 let Some(s) = m.get_mut(&ptr_of(&v)) else {
2817 return false;
2818 };
2819 let selected = s.selected;
2820 if let Some(tabs) = s.tabs.as_mut() {
2821 if tabs.target.is_none() {
2822 let target = DayTarget::new(mtm, node);
2823 unsafe {
2824 tabs.view
2825 .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2826 };
2827 tabs.target = Some(target);
2828 }
2829 sync_tab_labels(tabs, &titles, selected);
2830 }
2831 true
2832 });
2833 if reached {
2834 return;
2835 }
2836 up = unsafe { v.superview() };
2837 }
2838}
2839
2840struct NavState {
2841 sidebar_wrap: Retained<NSView>,
2842 detail_wrap: Retained<NSView>,
2843 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2848 sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2852 list_wrap: Option<Retained<NSView>>,
2858 list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2859 list_width: Option<f64>,
2862 list_visible: bool,
2866 list_positioned: bool,
2872 pages: Vec<Retained<NSView>>,
2875 sidebar_page: Option<Retained<NSView>>,
2878 list_page: Option<Retained<NSView>>,
2881 positioned: bool,
2882 presentation: NavPresentation,
2886 selected: usize,
2889 tabs: Option<TabHost>,
2893 header: Option<NavHeader>,
2895 root_title: String,
2898 node: NodeId,
2900 title_strip: f64,
2904}
2905
2906fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2918 let pane = view_of(DayFlipped::new(mtm));
2919 unsafe {
2920 wrap.setFrame(pane.bounds());
2921 wrap.setAutoresizingMask(
2922 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2923 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2924 );
2925 pane.addSubview(wrap);
2926 }
2927 pane
2928}
2929
2930fn place_below_strip(wrap: &NSView, strip: f64) {
2932 let Some(pane) = (unsafe { wrap.superview() }) else {
2933 return;
2934 };
2935 let b = pane.bounds();
2936 unsafe {
2937 wrap.setFrame(NSRect::new(
2938 NSPoint::new(0.0, strip),
2939 NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2940 ))
2941 };
2942}
2943
2944fn build_nav_header(
2952 mtm: MainThreadMarker,
2953 id: NodeId,
2954 detail_wrap: &NSView,
2955 root_title: &str,
2956) -> NavHeader {
2957 let bar = view_of(DayFlipped::new(mtm));
2958 let target = DayTarget::new(mtm, id);
2959 let back = unsafe {
2960 let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2963 .expect("NSGoBackTemplate");
2964 let tobj: &objc2::runtime::AnyObject = target.as_ref();
2965 objc2_app_kit::NSButton::buttonWithImage_target_action(
2966 &img,
2967 Some(tobj),
2968 Some(sel!(navBack:)),
2969 mtm,
2970 )
2971 };
2972 let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2973 unsafe {
2974 back.setFrame(NSRect::new(
2975 NSPoint::new(6.0, 4.0),
2976 NSSize::new(30.0, NAV_HEADER_H - 8.0),
2977 ));
2978 title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2979 title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2980 title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2981 title.setFrame(NSRect::new(
2982 NSPoint::new(44.0, 9.0),
2983 NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2984 ));
2985 title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2986 bar.setFrame(NSRect::new(
2987 NSPoint::new(0.0, 0.0),
2988 NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2989 ));
2990 bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2991 bar.addSubview(&back);
2992 bar.addSubview(&title);
2993 bar.setHidden(true);
2994 detail_wrap.addSubview(&bar);
2995 }
2996 NavHeader {
2997 bar,
2998 title,
2999 titles: vec![root_title.to_string()],
3000 _target: target,
3001 }
3002}
3003
3004fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
3008 let b = wrap.bounds();
3009 let top = if header_visible { NAV_HEADER_H } else { 0.0 };
3010 NSRect::new(
3011 NSPoint::new(0.0, top),
3012 NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
3013 )
3014}
3015
3016fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
3023 fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
3024 if out.is_some() {
3025 return;
3026 }
3027 let found = NAV_MENUS.with(|m| {
3028 m.borrow()
3029 .get(&(v as *const NSView as usize))
3030 .map(|(_, d)| {
3031 let ivars = d.ivars();
3032 (
3033 ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
3034 ivars.node,
3035 )
3036 })
3037 });
3038 if found.is_some() {
3039 *out = found;
3040 return;
3041 }
3042 for sub in unsafe { v.subviews() }.iter() {
3043 walk(&sub, out);
3044 }
3045 }
3046 let mut out = None;
3047 walk(page, &mut out);
3048 out
3049}
3050
3051fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
3054 let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
3055 unsafe {
3056 item.setCanCollapse(shown);
3057 item.setCollapsed(!shown);
3058 match pres {
3059 NavPresentation::Split => {
3060 item.setAllowsFullHeightLayout(true);
3061 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3062 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3063 }
3064 NavPresentation::Rail => {
3070 item.setAllowsFullHeightLayout(true);
3071 item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3072 item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3073 }
3074 NavPresentation::Stack | NavPresentation::Tabs => {
3077 item.setMinimumThickness(0.0);
3078 item.setMaximumThickness(0.0);
3079 }
3080 }
3081 }
3082}
3083
3084pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
3090 NAV_STATE.with(|m| {
3091 m.borrow()
3092 .values()
3093 .find(|st| {
3094 st.list_item.is_some()
3095 && st
3096 .sidebar_wrap
3097 .window()
3098 .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
3099 })
3100 .map(|st| unsafe { st._split_vc.splitView() })
3101 })
3102}
3103
3104fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
3105 let visible = pages.len() >= 2;
3106 hdr.bar.setHidden(!visible);
3107 unsafe {
3108 hdr.title.setStringValue(&NSString::from_str(
3109 hdr.titles.last().map(String::as_str).unwrap_or(""),
3110 ));
3111 }
3112 let frame = nav_page_frame(wrap, visible);
3113 for page in pages {
3114 unsafe { page.setFrame(frame) };
3115 }
3116}
3117
3118fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
3133 let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
3134 NAV_STATE.with(|m| {
3135 let st = m.borrow();
3136 let s = st.get(&ptr_of(host))?;
3137 Some((
3138 s.sidebar_page.clone(),
3139 s.detail_wrap.clone(),
3140 s.sidebar_wrap.clone(),
3141 s.sidebar_item.clone(),
3142 s.presentation,
3143 s.root_title.clone(),
3144 s.node,
3145 s.selected,
3146 ))
3147 })
3148 else {
3149 return;
3150 };
3151 if was == next {
3152 return;
3153 }
3154 apply_sidebar_item(&sidebar_item, next);
3155 NAV_STATE.with(|m| {
3160 if let Some(s) = m.borrow().get(&ptr_of(host)) {
3161 unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
3162 }
3163 });
3164 let stacked = next == NavPresentation::Stack;
3167 let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
3168 if stacked && header.is_none() {
3169 header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
3170 }
3171 if let Some(hdr) = header.as_ref() {
3172 hdr.bar.setHidden(true);
3173 }
3174 let mut pages = NAV_STATE.with(|m| {
3180 m.borrow()
3181 .get(&ptr_of(host))
3182 .map(|s| s.pages.clone())
3183 .unwrap_or_default()
3184 });
3185 let shown_page = pages.get(sel).cloned();
3186 if let Some(page) = sidebar_page {
3189 pages.retain(|p| ptr_of(p) != ptr_of(&page));
3190 unsafe {
3191 if stacked {
3192 detail_wrap.addSubview(&page);
3193 pages.insert(0, page.clone());
3194 } else {
3195 page.setFrame(sidebar_wrap.bounds());
3196 sidebar_wrap.addSubview(&page);
3197 }
3198 }
3199 page.setHidden(false);
3201 }
3202 let shown = shown_page
3203 .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
3204 .unwrap_or_else(|| pages.len().saturating_sub(1));
3205 for (i, page) in pages.iter().enumerate() {
3206 page.setHidden(i != shown);
3207 }
3208 NAV_STATE.with(|m| {
3209 let mut m = m.borrow_mut();
3210 if let Some(s) = m.get_mut(&ptr_of(host)) {
3211 s.presentation = next;
3212 s.pages = pages;
3213 s.selected = shown;
3214 s.header = header;
3215 if let Some(hdr) = s.header.as_ref() {
3216 if stacked {
3218 sync_nav_header(hdr, &s.detail_wrap, &s.pages);
3219 } else {
3220 hdr.bar.setHidden(true);
3221 }
3222 }
3223 if !stacked {
3224 let frame = nav_page_frame(&s.detail_wrap, false);
3227 for page in &s.pages {
3228 unsafe { page.setFrame(frame) };
3229 }
3230 }
3231 }
3232 });
3233}
3234
3235struct CoverSheet(Retained<NSWindow>);
3244impl Drop for CoverSheet {
3245 fn drop(&mut self) {
3246 let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
3248 let raw = Retained::into_raw(self.0.clone()) as usize;
3251 dispatch2::DispatchQueue::main().exec_async(move || {
3252 ffi_guard::contain((), || unsafe {
3253 let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
3254 if let Some(parent) = window.sheetParent() {
3255 parent.endSheet(&window);
3256 }
3257 window.orderOut(None);
3258 window.setContentView(None);
3259 });
3260 });
3261 }
3262}
3263struct NavPageIvars {
3264 node: NodeId,
3265 top_inset: Cell<f64>,
3269 sheet: Cell<bool>,
3270 half: Cell<bool>,
3272 large: Cell<bool>,
3275}
3276
3277define_class!(
3278 #[unsafe(super(NSView))]
3279 #[thread_kind = MainThreadOnly]
3280 #[name = "DayNavPage"]
3281 #[ivars = NavPageIvars]
3282 struct DayNavPage;
3283
3284 impl DayNavPage {
3285 #[unsafe(method(isFlipped))]
3286 fn is_flipped(&self) -> bool {
3287 true
3288 }
3289
3290 #[unsafe(method(setFrameSize:))]
3291 fn set_frame_size(&self, size: NSSize) {
3292 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3293 ffi_guard::contain((), || {
3296 let inset = self.ivars().top_inset.get();
3297 emit(
3298 self.ivars().node,
3299 Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
3300 );
3301 })
3302 }
3303 }
3304);
3305
3306impl DayNavPage {
3307 fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
3308 let this = Self::alloc(mtm).set_ivars(NavPageIvars {
3309 node,
3310 top_inset: Cell::new(0.0),
3311 sheet: Cell::new(false),
3312 half: Cell::new(false),
3313 large: Cell::new(false),
3314 });
3315 unsafe { msg_send![super(this), init] }
3316 }
3317}
3318
3319struct InspectorState {
3328 content_wrap: Handle,
3329 panel_wrap: Handle,
3330 _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3332 panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
3333}
3334
3335struct SplitState {
3343 split: Retained<objc2_app_kit::NSSplitView>,
3344 first_wrap: Handle,
3345 second_wrap: Handle,
3346 delegate: Retained<DaySplitDelegate>,
3347}
3348
3349struct SplitDelegateIvars {
3350 node: NodeId,
3351 min_pane: f64,
3352 share: Cell<f64>,
3355 positioned: Cell<bool>,
3357 suppress: Cell<bool>,
3359}
3360
3361define_class!(
3362 #[unsafe(super(NSObject))]
3363 #[thread_kind = MainThreadOnly]
3364 #[name = "DaySplitDelegate"]
3365 #[ivars = SplitDelegateIvars]
3366 struct DaySplitDelegate;
3367
3368 unsafe impl NSObjectProtocol for DaySplitDelegate {}
3369
3370 unsafe impl NSSplitViewDelegate for DaySplitDelegate {
3371 #[unsafe(method(splitViewDidResizeSubviews:))]
3372 fn did_resize(&self, notification: &NSNotification) {
3373 ffi_guard::contain((), || {
3374 let Some(obj) = notification.object() else {
3375 return;
3376 };
3377 let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
3378 return;
3379 };
3380 let iv = self.ivars();
3381 let usable = split_usable(&sv);
3382 if usable <= 0.0 {
3383 return;
3384 }
3385 if !iv.positioned.replace(true) {
3387 split_place(&sv, iv);
3388 return;
3389 }
3390 if iv.suppress.get() {
3391 return;
3392 }
3393 let Some(first) = sv.subviews().iter().next() else {
3394 return;
3395 };
3396 let f = first.frame();
3397 let a = if sv.isVertical() {
3398 f.size.width
3399 } else {
3400 f.size.height
3401 };
3402 let share = (a / usable).clamp(0.0, 1.0);
3403 if (share - iv.share.get()).abs() > 1e-4 {
3404 iv.share.set(share);
3405 emit(iv.node, Event::ValueChanged(share));
3406 }
3407 })
3408 }
3409
3410 #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
3411 fn constrain_min(
3412 &self,
3413 _sv: &objc2_app_kit::NSSplitView,
3414 proposed: f64,
3415 _index: isize,
3416 ) -> f64 {
3417 proposed.max(self.ivars().min_pane)
3418 }
3419
3420 #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
3421 fn constrain_max(
3422 &self,
3423 sv: &objc2_app_kit::NSSplitView,
3424 proposed: f64,
3425 _index: isize,
3426 ) -> f64 {
3427 proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
3428 }
3429 }
3430);
3431
3432impl DaySplitDelegate {
3433 fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
3434 let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
3435 node,
3436 min_pane,
3437 share: Cell::new(share.clamp(0.0, 1.0)),
3438 positioned: Cell::new(false),
3439 suppress: Cell::new(false),
3440 });
3441 unsafe { msg_send![super(this), init] }
3442 }
3443}
3444
3445fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
3447 let frame = sv.frame();
3448 let len = if sv.isVertical() {
3449 frame.size.width
3450 } else {
3451 frame.size.height
3452 };
3453 (len - sv.dividerThickness()).max(0.0)
3454}
3455
3456fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
3458 let usable = split_usable(sv);
3459 if usable <= 0.0 {
3460 return;
3461 }
3462 iv.suppress.set(true);
3463 unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
3464 iv.suppress.set(false);
3465}
3466
3467struct NavMenuIvars {
3474 node: NodeId,
3475 items: RefCell<Vec<Retained<NSString>>>,
3476 icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3480 icon_fills: RefCell<Vec<f64>>,
3483 tints: RefCell<Vec<Option<day_spec::Color>>>,
3486 badges: RefCell<Vec<Option<Retained<NSString>>>>,
3488 icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
3491 badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3492 badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
3494 menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
3497 movable: RefCell<Vec<bool>>,
3499 regroup: std::cell::Cell<bool>,
3501 sorted: RefCell<Vec<bool>>,
3503 rows: RefCell<Vec<Option<usize>>>,
3507 row_objects: RefCell<Vec<Retained<NSString>>>,
3509 row_ids: RefCell<Vec<Retained<NSNumber>>>,
3514 suppress: std::cell::Cell<bool>,
3516}
3517
3518struct NavCellIvars {
3519 accessory: RefCell<Option<Retained<NSView>>>,
3522 count: RefCell<Option<Retained<NSTextField>>>,
3524 icon_fill: std::cell::Cell<f64>,
3526}
3527
3528define_class!(
3529 #[unsafe(super(objc2_app_kit::NSTableCellView))]
3534 #[thread_kind = MainThreadOnly]
3535 #[name = "DayNavCell"]
3536 #[ivars = NavCellIvars]
3537 struct DayNavCell;
3538
3539 unsafe impl NSObjectProtocol for DayNavCell {}
3540
3541 impl DayNavCell {
3542 #[unsafe(method(layout))]
3543 fn layout(&self) {
3544 let _: () = unsafe { msg_send![super(self), layout] };
3545 ffi_guard::contain((), || self.fit_accessories());
3546 }
3547 }
3548);
3549
3550impl DayNavCell {
3551 fn new(mtm: MainThreadMarker) -> Retained<Self> {
3552 let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3553 accessory: RefCell::new(None),
3554 count: RefCell::new(None),
3555 icon_fill: std::cell::Cell::new(1.0),
3556 });
3557 unsafe { msg_send![super(this), init] }
3558 }
3559
3560 fn fit_accessories(&self) {
3565 let label = unsafe { self.textField() };
3566 if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3567 let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3568 (f.pointSize() - 2.0).max(9.0)
3569 });
3570 if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
3571 unsafe {
3572 count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3573 size,
3574 objc2_app_kit::NSFontWeightRegular,
3575 )));
3576 }
3577 self.layoutSubtreeIfNeeded();
3578 }
3579 }
3580 if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3581 let mut frame = label.frame();
3582 let end = accessory.frame().origin.x - 6.0;
3583 if frame.origin.x + frame.size.width > end {
3584 frame.size.width = (end - frame.origin.x).max(0.0);
3585 label.setFrame(frame);
3586 }
3587 }
3588 if let Some(icon) = unsafe { self.imageView() } {
3589 fit_nav_icon(&icon, self.ivars().icon_fill.get());
3590 nav_progress::fit(&icon);
3591 }
3592 }
3593}
3594
3595thread_local! {
3596 static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3598}
3599
3600fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3609 let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3610 return;
3611 };
3612 let slot = icon.frame();
3613 let key = config.hash() as u64;
3616 let side = NAV_GLYPH_SIDES
3617 .with(|m| m.borrow().get(&key).copied())
3618 .or_else(|| {
3619 let symbol =
3620 objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3621 &NSString::from_str("gearshape"),
3622 None,
3623 )?;
3624 let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3625 NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3626 Some(side)
3627 });
3628 let Some(side) = side
3631 .filter(|s| *s > 0.0)
3632 .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3633 else {
3634 return;
3635 };
3636 if slot.size.width <= side && slot.size.height <= side {
3637 return;
3638 }
3639 icon.setFrame(NSRect::new(
3640 NSPoint::new(
3641 (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3642 (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3643 ),
3644 NSSize::new(side, side),
3645 ));
3646}
3647
3648define_class!(
3649 #[unsafe(super(objc2_app_kit::NSTableRowView))]
3650 #[thread_kind = MainThreadOnly]
3651 #[name = "DayNavRowView"]
3652 struct DayNavRowView;
3653
3654 unsafe impl NSObjectProtocol for DayNavRowView {}
3655
3656 impl DayNavRowView {
3657 #[unsafe(method(isEmphasized))]
3663 fn is_emphasized(&self) -> bool {
3664 true
3665 }
3666 }
3667);
3668
3669define_class!(
3670 #[unsafe(super(objc2_app_kit::NSOutlineView))]
3671 #[thread_kind = MainThreadOnly]
3672 #[name = "DayNavOutlineView"]
3673 struct DayNavOutlineView;
3674
3675 unsafe impl NSObjectProtocol for DayNavOutlineView {}
3676
3677 impl DayNavOutlineView {
3678 #[unsafe(method_id(menuForEvent:))]
3682 fn menu_for_event(
3683 &self,
3684 event: &objc2_app_kit::NSEvent,
3685 ) -> Option<Retained<NSMenu>> {
3686 ffi_guard::contain(None, || {
3687 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3688 let row = unsafe { self.rowAtPoint(point) };
3689 let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3690 match data {
3692 None => None,
3693 Some(d) => {
3694 let items = d
3695 .item_of_row(row)
3696 .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3697 .unwrap_or_default();
3698 if items.is_empty() {
3699 None
3700 } else {
3701 Some(build_ns_menu(d.mtm(), "", &items))
3702 }
3703 }
3704 }
3705 })
3706 }
3707 }
3708);
3709
3710define_class!(
3711 #[unsafe(super(NSObject))]
3712 #[thread_kind = MainThreadOnly]
3713 #[name = "DayNavMenuData"]
3714 #[ivars = NavMenuIvars]
3715 struct DayNavMenuData;
3716
3717 unsafe impl NSObjectProtocol for DayNavMenuData {}
3718
3719 unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3720 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3721 fn number_of_children(
3722 &self,
3723 _ov: &objc2_app_kit::NSOutlineView,
3724 item: Option<&objc2::runtime::AnyObject>,
3725 ) -> isize {
3726 if item.is_none() {
3727 self.ivars().row_objects.borrow().len() as isize
3728 } else {
3729 0
3730 }
3731 }
3732
3733 #[unsafe(method_id(outlineView:child:ofItem:))]
3734 fn child_of_item(
3735 &self,
3736 _ov: &objc2_app_kit::NSOutlineView,
3737 index: isize,
3738 _item: Option<&objc2::runtime::AnyObject>,
3739 ) -> Retained<objc2::runtime::AnyObject> {
3740 let ids = self.ivars().row_ids.borrow();
3741 let id = ids
3745 .get(index as usize)
3746 .cloned()
3747 .unwrap_or_else(|| NSNumber::new_isize(-1));
3748 unsafe { objc2::rc::Retained::cast_unchecked(id) }
3749 }
3750
3751 #[unsafe(method(outlineView:isItemExpandable:))]
3752 fn is_expandable(
3753 &self,
3754 _ov: &objc2_app_kit::NSOutlineView,
3755 _item: &objc2::runtime::AnyObject,
3756 ) -> bool {
3757 false
3758 }
3759
3760 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3767 fn pasteboard_writer_for_item(
3768 &self,
3769 _ov: &objc2_app_kit::NSOutlineView,
3770 item: &objc2::runtime::AnyObject,
3771 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3772 let make = || {
3773 let row = Self::outline_row(item);
3774 let index = self.item_of_row(row)?;
3775 if !self.is_movable(index) {
3776 return None;
3777 }
3778 let pbitem = objc2_app_kit::NSPasteboardItem::new();
3779 unsafe {
3780 pbitem.setString_forType(
3781 &NSString::from_str(&row.to_string()),
3782 &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3783 );
3784 }
3785 Some(ProtocolObject::from_retained(pbitem))
3786 };
3787 ffi_guard::contain(None, make)
3788 }
3789
3790 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3791 fn validate_drop(
3792 &self,
3793 ov: &objc2_app_kit::NSOutlineView,
3794 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3795 item: Option<&objc2::runtime::AnyObject>,
3796 child_index: isize,
3797 ) -> objc2_app_kit::NSDragOperation {
3798 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3799 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3800 return objc2_app_kit::NSDragOperation::None;
3801 };
3802 if drop.retarget {
3804 unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3805 }
3806 objc2_app_kit::NSDragOperation::Move
3807 })
3808 }
3809
3810 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3811 fn accept_drop(
3812 &self,
3813 ov: &objc2_app_kit::NSOutlineView,
3814 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3815 item: Option<&objc2::runtime::AnyObject>,
3816 child_index: isize,
3817 ) -> bool {
3818 ffi_guard::contain(false, || {
3819 let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3820 return false;
3821 };
3822 match drop.moves {
3825 Some(NavMove::Reorder { from, to }) => {
3826 emit(self.ivars().node, Event::ListReorder { from, to });
3827 }
3828 Some(NavMove::Regroup {
3829 from,
3830 section,
3831 before,
3832 }) => emit(
3833 self.ivars().node,
3834 Event::NavRegroup {
3835 from,
3836 section,
3837 before,
3838 },
3839 ),
3840 None => {}
3841 }
3842 true
3843 })
3844 }
3845 }
3846
3847 unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3848
3849 unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3850 #[unsafe(method(outlineView:isGroupItem:))]
3853 fn is_group_item(
3854 &self,
3855 _ov: &objc2_app_kit::NSOutlineView,
3856 item: &objc2::runtime::AnyObject,
3857 ) -> bool {
3858 let row = Self::outline_row(item);
3859 row >= 0 && self.item_of_row(row).is_none()
3860 }
3861
3862 #[unsafe(method(outlineView:shouldSelectItem:))]
3863 fn should_select(
3864 &self,
3865 _ov: &objc2_app_kit::NSOutlineView,
3866 item: &objc2::runtime::AnyObject,
3867 ) -> bool {
3868 self.item_of_row(Self::outline_row(item)).is_some()
3869 }
3870
3871 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3872 fn view_for(
3873 &self,
3874 ov: &objc2_app_kit::NSOutlineView,
3875 _col: Option<&objc2_app_kit::NSTableColumn>,
3876 item: &objc2::runtime::AnyObject,
3877 ) -> Option<Retained<NSView>> {
3878 let mtm = self.mtm();
3879 let row = Self::outline_row(item);
3880 let text = self
3881 .ivars()
3882 .row_objects
3883 .borrow()
3884 .get(usize::try_from(row).unwrap_or(usize::MAX))
3885 .cloned();
3886 text.map(|text| {
3888 let text: &NSString = &text;
3889 let Some(index) = self.item_of_row(row) else {
3890 let cell = DayNavCell::new(mtm);
3893 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3894 unsafe {
3895 label.cell().inspect(|c| {
3896 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3897 });
3898 cell.addSubview(&label);
3899 cell.setTextField(Some(&label));
3900 }
3901 return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3902 };
3903 let icon = self
3904 .ivars()
3905 .icons
3906 .borrow()
3907 .get(index)
3908 .and_then(|o| o.clone());
3909 let badge = self
3910 .ivars()
3911 .badges
3912 .borrow()
3913 .get(index)
3914 .and_then(|o| o.clone());
3915 let badge_icon = self
3916 .ivars()
3917 .badge_icons
3918 .borrow()
3919 .get(index)
3920 .and_then(|o| o.clone());
3921 let badge_tint = self
3922 .ivars()
3923 .badge_tints
3924 .borrow()
3925 .get(index)
3926 .copied()
3927 .flatten();
3928 let cell = DayNavCell::new(mtm);
3932 let label = unsafe { NSTextField::labelWithString(text, mtm) };
3933 unsafe {
3934 label.cell().inspect(|c| {
3937 c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3938 });
3939 cell.addSubview(&label);
3940 cell.setTextField(Some(&label));
3941 let accessory = objc2_app_kit::NSStackView::new(mtm);
3948 accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3949 accessory.setOrientation(
3950 objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3951 );
3952 accessory.setSpacing(4.0);
3953 let mut has_accessory = false;
3954 let trailing: Retained<NSView> = match &badge {
3955 Some(text) => {
3956 let b = NSTextField::labelWithString(text, mtm);
3957 b.setTranslatesAutoresizingMaskIntoConstraints(false);
3958 b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3959 b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3960 b.setFont(Some(
3961 &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3962 objc2_app_kit::NSFont::smallSystemFontSize(),
3963 objc2_app_kit::NSFontWeightRegular,
3964 ),
3965 ));
3966 b.setContentCompressionResistancePriority_forOrientation(
3967 objc2_app_kit::NSLayoutPriorityRequired,
3968 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3969 );
3970 *cell.ivars().count.borrow_mut() = Some(b.clone());
3971 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3972 objc2::rc::Retained::into_super(b),
3973 ));
3974 has_accessory = true;
3975 let v: Retained<NSView> =
3976 objc2::rc::Retained::into_super(accessory.clone());
3977 v
3978 }
3979 None => objc2::rc::Retained::into_super(accessory.clone()),
3980 };
3981 if let Some(img) = &badge_icon {
3986 let iv = objc2_app_kit::NSImageView::new(mtm);
3987 iv.setImage(Some(img));
3988 iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3989 if let Some(c) = badge_tint {
3990 iv.setContentTintColor(Some(&nscolor(c)));
3991 }
3992 iv.setContentCompressionResistancePriority_forOrientation(
3993 objc2_app_kit::NSLayoutPriorityRequired,
3994 objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3995 );
3996 accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3997 has_accessory = true;
3998 }
3999 cell.addSubview(&trailing);
4000 if has_accessory {
4001 *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
4002 }
4003 objc2_app_kit::NSLayoutConstraint::activateConstraints(
4004 &objc2_foundation::NSArray::from_retained_slice(&[
4005 trailing
4006 .trailingAnchor()
4007 .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
4008 trailing
4009 .centerYAnchor()
4010 .constraintEqualToAnchor(&cell.centerYAnchor()),
4011 ]),
4012 );
4013 }
4014 if let Some(img) = icon {
4015 let fill = self.ivars().icon_fills.borrow().get(index).copied();
4016 cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
4017 let tint = self.ivars().tints.borrow().get(index).copied().flatten();
4018 let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
4019 unsafe {
4020 iv.setImage(Some(&img));
4021 if let Some(t) = tint {
4024 iv.setContentTintColor(Some(&nscolor(t)));
4025 }
4026 iv.setImageScaling(
4027 objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
4028 );
4029 cell.addSubview(&iv);
4030 cell.setImageView(Some(&iv));
4031 let progress = self
4032 .ivars()
4033 .icon_progress
4034 .borrow()
4035 .iter()
4036 .find(|(row, _)| *row == index)
4037 .map(|(_, f)| *f);
4038 nav_progress::update(&iv, progress);
4039 }
4040 }
4041 objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
4042 })
4043 }
4044
4045 #[unsafe(method_id(outlineView:rowViewForItem:))]
4046 fn row_view_for(
4047 &self,
4048 _ov: &objc2_app_kit::NSOutlineView,
4049 _item: &objc2::runtime::AnyObject,
4050 ) -> Retained<objc2_app_kit::NSTableRowView> {
4051 let row: Retained<DayNavRowView> =
4052 unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
4053 objc2::rc::Retained::into_super(row)
4054 }
4055
4056 #[unsafe(method(outlineViewSelectionDidChange:))]
4057 fn selection_did_change(&self, notification: &NSNotification) {
4058 ffi_guard::contain((), || {
4059 if self.ivars().suppress.get() {
4060 return;
4061 }
4062 let Some(obj) = (unsafe { notification.object() }) else {
4063 return;
4064 };
4065 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
4066 return;
4067 };
4068 let row = unsafe { ov.selectedRow() };
4069 if let Some(item) = self.item_of_row(row) {
4070 emit(self.ivars().node, Event::SelectionChanged(item as i64));
4071 }
4072 })
4073 }
4074 }
4075);
4076
4077thread_local! {
4078 static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
4081}
4082
4083fn nav_icon_fills(
4085 names: &[Option<String>],
4086 images: &[Option<Retained<objc2_app_kit::NSImage>>],
4087) -> Vec<f64> {
4088 names
4089 .iter()
4090 .zip(images)
4091 .map(|(name, image)| match (name, image) {
4092 (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
4093 *m.borrow_mut()
4094 .entry(name.clone())
4095 .or_insert_with(|| nav_icon_fill(image))
4096 }),
4097 _ => 1.0,
4098 })
4099 .collect()
4100}
4101
4102fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
4107 const PX: f64 = 64.0;
4108 let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
4109 return 1.0;
4110 };
4111 let (w, h) = (
4112 rep.pixelsWide().max(0) as usize,
4113 rep.pixelsHigh().max(0) as usize,
4114 );
4115 let stride = rep.bytesPerRow().max(0) as usize;
4116 let data = unsafe { rep.bitmapData() };
4117 if data.is_null() || stride < w * 4 {
4118 return 1.0;
4119 }
4120 let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
4123 let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
4124 for y in 0..h {
4125 for x in 0..w {
4126 if bytes[y * stride + x * 4 + 3] > 24 {
4127 (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
4128 }
4129 }
4130 }
4131 if x1 <= x0 || y1 <= y0 {
4132 return 1.0;
4133 }
4134 let size = image.size();
4137 let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
4138 let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
4139 ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
4140}
4141
4142fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
4143 icons
4145 .iter()
4146 .map(|ic| {
4147 let name = ic.as_deref()?;
4148 let path = day_spec::resource::resolve_vector_svg(name)
4150 .or_else(|| day_spec::resource::resolve_image_file(name))?;
4151 use objc2::AllocAnyThread as _;
4152 let img = unsafe {
4153 objc2_app_kit::NSImage::initWithContentsOfFile(
4154 objc2_app_kit::NSImage::alloc(),
4155 &NSString::from_str(&path.to_string_lossy()),
4156 )
4157 }?;
4158 unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
4160 Some(img)
4161 })
4162 .collect()
4163}
4164
4165impl DayNavMenuData {
4166 #[allow(clippy::too_many_arguments)]
4167 fn new(
4168 mtm: MainThreadMarker,
4169 node: NodeId,
4170 items: &[String],
4171 icons: &[Option<String>],
4172 badges: &[Option<String>],
4173 badge_icons: &[Option<String>],
4174 badge_tints: &[Option<day_spec::Color>],
4175 sections: &[Option<String>],
4176 tints: &[Option<day_spec::Color>],
4177 menus: &[Vec<day_spec::MenuItem>],
4178 ) -> Retained<Self> {
4179 let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
4180 node,
4181 items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
4182 icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
4183 icons: RefCell::new(resolve_nav_icons(icons)),
4184 tints: RefCell::new(tints.to_vec()),
4185 menus: RefCell::new(menus.to_vec()),
4186 movable: RefCell::new(Vec::new()),
4187 regroup: std::cell::Cell::new(false),
4188 sorted: RefCell::new(Vec::new()),
4189 badges: RefCell::new(ns_badges(badges)),
4190 icon_progress: RefCell::new(Vec::new()),
4191 badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
4192 badge_tints: RefCell::new(badge_tints.to_vec()),
4193 rows: RefCell::new(Vec::new()),
4194 row_objects: RefCell::new(Vec::new()),
4195 row_ids: RefCell::new(Vec::new()),
4196 suppress: std::cell::Cell::new(false),
4197 });
4198 let this: Retained<Self> = unsafe { msg_send![super(this), init] };
4199 this.rebuild_rows(items, sections);
4200 this
4201 }
4202
4203 #[allow(clippy::too_many_arguments)]
4207 fn set_items(
4208 &self,
4209 items: &[String],
4210 icons: &[Option<String>],
4211 badges: &[Option<String>],
4212 badge_icons: &[Option<String>],
4213 badge_tints: &[Option<day_spec::Color>],
4214 sections: &[Option<String>],
4215 tints: &[Option<day_spec::Color>],
4216 menus: &[Vec<day_spec::MenuItem>],
4217 ) {
4218 *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
4219 let resolved = resolve_nav_icons(icons);
4220 *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
4221 *self.ivars().icons.borrow_mut() = resolved;
4222 *self.ivars().tints.borrow_mut() = tints.to_vec();
4223 *self.ivars().menus.borrow_mut() = menus.to_vec();
4224 *self.ivars().badges.borrow_mut() = ns_badges(badges);
4225 self.ivars().icon_progress.borrow_mut().clear();
4226 *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
4227 *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
4228 self.rebuild_rows(items, sections);
4229 }
4230
4231 fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
4235 let mut rows = Vec::with_capacity(items.len());
4236 let mut objects = Vec::with_capacity(items.len());
4237 for (i, label) in items.iter().enumerate() {
4238 if let Some(Some(header)) = sections.get(i) {
4239 rows.push(None);
4240 objects.push(NSString::from_str(header));
4241 }
4242 rows.push(Some(i));
4243 objects.push(NSString::from_str(label));
4244 }
4245 let ids = (0..objects.len())
4246 .map(|i| NSNumber::new_isize(i as isize))
4247 .collect();
4248 *self.ivars().rows.borrow_mut() = rows;
4249 *self.ivars().row_objects.borrow_mut() = objects;
4250 *self.ivars().row_ids.borrow_mut() = ids;
4251 }
4252
4253 fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
4256 item.downcast_ref::<NSNumber>()
4257 .map(|n| n.integerValue())
4258 .unwrap_or(-1)
4259 }
4260
4261 fn item_of_row(&self, row: isize) -> Option<usize> {
4263 if row < 0 {
4264 return None;
4265 }
4266 self.ivars()
4267 .rows
4268 .borrow()
4269 .get(row as usize)
4270 .copied()
4271 .flatten()
4272 }
4273
4274 fn row_of_item(&self, item: usize) -> Option<usize> {
4276 self.ivars()
4277 .rows
4278 .borrow()
4279 .iter()
4280 .position(|r| *r == Some(item))
4281 }
4282
4283 fn is_movable(&self, item: usize) -> bool {
4284 self.ivars()
4285 .movable
4286 .borrow()
4287 .get(item)
4288 .copied()
4289 .unwrap_or(false)
4290 }
4291
4292 fn nav_drop(
4297 &self,
4298 ov: &objc2_app_kit::NSOutlineView,
4299 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4300 item: Option<&objc2::runtime::AnyObject>,
4301 child_index: isize,
4302 ) -> Option<NavDrop> {
4303 let src = unsafe { info.draggingSource() }?;
4304 if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
4305 != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
4306 {
4307 return None;
4308 }
4309 let pb = unsafe { info.draggingPasteboard() };
4310 let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
4311 .to_string()
4312 .parse::<usize>()
4313 .ok()?;
4314 let rows = self.ivars().rows.borrow();
4315 let proposed = match item {
4318 Some(item) => Self::outline_row(item),
4319 None => child_index,
4320 };
4321 let proposed = usize::try_from(proposed).unwrap_or(rows.len());
4322 if self.ivars().regroup.get() {
4323 regroup_gap(
4324 &rows,
4325 &self.ivars().movable.borrow(),
4326 &self.ivars().sorted.borrow(),
4327 from_row,
4328 proposed,
4329 item.is_some(),
4330 )
4331 } else {
4332 reorder_gap(
4333 &rows,
4334 &self.ivars().movable.borrow(),
4335 from_row,
4336 proposed,
4337 item.is_some(),
4338 )
4339 }
4340 }
4341}
4342
4343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4345struct NavDrop {
4346 gap: usize,
4348 retarget: bool,
4350 moves: Option<NavMove>,
4352}
4353
4354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4356enum NavMove {
4357 Reorder { from: usize, to: usize },
4359 Regroup {
4362 from: usize,
4363 section: usize,
4364 before: Option<usize>,
4365 },
4366}
4367
4368fn reorder_gap(
4373 rows: &[Option<usize>],
4374 movable: &[bool],
4375 from_row: usize,
4376 proposed: usize,
4377 onto: bool,
4378) -> Option<NavDrop> {
4379 let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
4380 let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
4381 let in_run = |r: usize| rows[r].is_some_and(is_movable);
4382 let first = (0..from_row)
4383 .rev()
4384 .take_while(|r| in_run(*r))
4385 .last()
4386 .unwrap_or(from_row);
4387 let last = (from_row + 1..rows.len())
4388 .take_while(|r| in_run(*r))
4389 .last()
4390 .unwrap_or(from_row);
4391 let gap = proposed.clamp(first, last + 1);
4392 let target_row = if gap > from_row { gap - 1 } else { gap };
4394 let moves = (target_row != from_row)
4395 .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
4396 .flatten();
4397 Some(NavDrop {
4398 gap,
4399 retarget: gap != proposed || onto,
4400 moves,
4401 })
4402}
4403
4404fn regroup_gap(
4412 rows: &[Option<usize>],
4413 movable: &[bool],
4414 sorted: &[bool],
4415 from_row: usize,
4416 proposed: usize,
4417 onto: bool,
4418) -> Option<NavDrop> {
4419 let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
4420 let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
4421 let gap = match rows.get(proposed) {
4422 Some(None) if onto => proposed + 1,
4423 _ => proposed.min(rows.len()),
4424 };
4425 let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
4427 Some(header) => Some(header + 1),
4428 None => rows.first().copied().flatten().map(|_| 0),
4429 };
4430 let first = section_start(gap)?;
4431 let end = (first..rows.len())
4432 .find(|r| rows[*r].is_none())
4433 .unwrap_or(rows.len());
4434 let section = rows.get(first).copied().flatten()?;
4435 if !rows[first..end]
4436 .iter()
4437 .all(|r| r.is_some_and(|i| flag(movable, i)))
4438 {
4439 return None;
4440 }
4441 let own = section_start(from_row) == Some(first);
4442 if own && flag(sorted, from) {
4443 return None;
4444 }
4445 let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
4446 from,
4447 section,
4448 before: rows.get(gap).copied().flatten(),
4449 });
4450 Some(NavDrop {
4451 gap,
4452 retarget: gap != proposed || onto,
4453 moves,
4454 })
4455}
4456
4457#[cfg(test)]
4458mod nav_gap_tests {
4459 use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
4460
4461 const ROWS: [Option<usize>; 10] = [
4463 Some(0),
4464 None,
4465 Some(1),
4466 Some(2),
4467 Some(3),
4468 None,
4469 Some(4),
4470 Some(5),
4471 None,
4472 Some(6),
4473 ];
4474 const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
4476 const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
4477 const UNSORTED: [bool; 7] = [false; 7];
4478
4479 fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
4480 Some(NavMove::Regroup {
4481 from,
4482 section,
4483 before,
4484 })
4485 }
4486
4487 #[test]
4488 fn regroup_gaps_name_the_section_above_and_the_row_below() {
4489 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4490 assert_eq!(
4492 at(2, 6),
4493 Some(NavDrop {
4494 gap: 6,
4495 retarget: false,
4496 moves: regroup(1, 4, Some(4)),
4497 })
4498 );
4499 assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
4501 assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
4503 assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
4504 }
4505
4506 #[test]
4507 fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4508 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4509 for gap in [0, 1, 9, 10] {
4511 assert_eq!(at(2, gap), None, "gap {gap}");
4512 }
4513 for gap in [2, 3, 4, 5] {
4515 assert_eq!(at(2, gap), None, "gap {gap}");
4516 }
4517 assert_eq!(at(0, 6), None);
4519 assert_eq!(at(1, 6), None);
4520 assert_eq!(at(9, 6), None);
4521 }
4522
4523 #[test]
4524 fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4525 let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4526 assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
4528 assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
4530 for gap in [2, 3] {
4532 let drop = at(2, gap).expect("offered");
4533 assert_eq!(drop.moves, None, "gap {gap}");
4534 }
4535 }
4536
4537 #[test]
4538 fn regroup_drops_onto_a_row_move_to_a_gap() {
4539 assert_eq!(
4541 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4542 Some(NavDrop {
4543 gap: 6,
4544 retarget: true,
4545 moves: regroup(1, 4, Some(4)),
4546 })
4547 );
4548 assert_eq!(
4549 regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4550 Some(NavDrop {
4551 gap: 7,
4552 retarget: true,
4553 moves: regroup(1, 4, Some(5)),
4554 })
4555 );
4556 }
4557
4558 #[test]
4559 fn regroup_offers_nothing_above_a_leading_header() {
4560 let rows = [None, Some(0), None, Some(1)];
4562 let movable = [true, true];
4563 let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4564 assert_eq!(at(0), None);
4565 assert_eq!(at(1).map(|d| d.moves), Some(None));
4566 assert_eq!(at(2).map(|d| d.moves), Some(None));
4567 assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
4568 assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
4569 }
4570
4571 #[test]
4572 fn reorder_gaps_clamp_to_the_run() {
4573 assert_eq!(
4575 reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4576 Some(NavDrop {
4577 gap: 5,
4578 retarget: true,
4579 moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4580 })
4581 );
4582 assert_eq!(
4584 reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4585 Some(None)
4586 );
4587 assert_eq!(
4589 reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4590 Some(NavMove::Reorder { from: 2, to: 1 })
4591 );
4592 assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4593 }
4594}
4595
4596const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4598
4599fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4601 badges
4602 .iter()
4603 .map(|b| b.as_deref().map(NSString::from_str))
4604 .collect()
4605}
4606
4607fn post_realize_visible_rows(key: usize) {
4613 <AppKit as Platform>::post(Box::new(move || {
4614 if let Some((table, data)) = list_entry(key) {
4615 unsafe { table.layoutSubtreeIfNeeded() };
4616 let range = unsafe { table.rowsInRect(table.visibleRect()) };
4617 if let Some(source) = data.ivars().source.borrow().clone()
4618 && let Some(report) = &source.first_visible
4619 {
4620 report(range.location.min((source.len)().saturating_sub(1)));
4621 }
4622 for row in range.location..range.location + range.length {
4623 let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4624 if let Some(cell) = cell
4628 && cell.subviews().is_empty()
4629 {
4630 let source = data.ivars().source.borrow().clone();
4631 if let Some(source) = source {
4632 (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4633 }
4634 }
4635 }
4636 }
4637 day_core::pump_events();
4640 }));
4641}
4642
4643fn post_settle_list_drop(key: usize) {
4648 <AppKit as Platform>::post(Box::new(move || {
4649 day_core::pump_events();
4652 let Some((table, data)) = list_entry(key) else {
4653 return;
4654 };
4655 let Some(scroll) = table.enclosingScrollView() else {
4656 return;
4657 };
4658 let clip = scroll.contentView();
4659 let origin = clip.bounds().origin;
4660 let selected = table.selectedRowIndexes();
4661 let suppressed = data.ivars().suppress.replace(true);
4662 table.reloadData();
4663 table.layoutSubtreeIfNeeded();
4665 let restored = objc2_foundation::NSMutableIndexSet::new();
4666 for row in 0..table.numberOfRows().max(0) as usize {
4667 if selected.containsIndex(row) {
4668 restored.addIndex(row);
4669 }
4670 }
4671 table.selectRowIndexes_byExtendingSelection(&restored, false);
4672 let mut bounds = clip.bounds();
4673 bounds.origin = origin;
4674 clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4675 scroll.reflectScrolledClipView(&clip);
4676 data.ivars().suppress.set(suppressed);
4677 post_realize_visible_rows(key);
4678 }));
4679}
4680
4681define_class!(
4690 #[unsafe(super(NSTableView))]
4691 #[thread_kind = MainThreadOnly]
4692 #[name = "DayListView"]
4693 struct DayListView;
4694 unsafe impl NSObjectProtocol for DayListView {}
4695 impl DayListView {
4696 #[unsafe(method_id(menuForEvent:))]
4699 fn menu_for_event(
4700 &self,
4701 event: &objc2_app_kit::NSEvent,
4702 ) -> Option<Retained<NSMenu>> {
4703 ffi_guard::contain(None, || {
4704 let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4705 let row = unsafe { self.rowAtPoint(point) };
4706 let provider = if row >= 0 {
4707 unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4708 .and_then(|cell| list_row_menu_provider(&cell))
4709 } else {
4710 None
4711 };
4712 match provider {
4713 Some((view, provider)) => {
4714 let point = view.convertPoint_fromView(
4715 unsafe { event.locationInWindow() }, None,
4716 );
4717 let items = provider(day_spec::Point::new(point.x, point.y));
4718 if items.is_empty() {
4719 None
4720 } else {
4721 Some(build_ns_menu(self.mtm(), "", &items))
4722 }
4723 }
4724 None => unsafe { msg_send![super(self), menuForEvent: event] },
4725 }
4726 })
4727 }
4728
4729 #[unsafe(method(becomeFirstResponder))]
4730 fn become_first_responder(&self) -> bool {
4731 let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4732 if accepted {
4733 self.report_focus(true);
4734 }
4735 accepted
4736 }
4737
4738 #[unsafe(method(resignFirstResponder))]
4739 fn resign_first_responder(&self) -> bool {
4740 let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4741 if accepted {
4742 self.report_focus(false);
4743 }
4744 accepted
4745 }
4746
4747 #[unsafe(method(keyDown:))]
4748 fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4749 ffi_guard::contain((), || {
4750 let key = unsafe { event.keyCode() };
4751 if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4752 let row = unsafe { self.selectedRow() };
4753 if row >= 0 && let Some(target) = unsafe { self.target() } {
4754 let _: () = unsafe { msg_send![&*target, activateRow: self] };
4755 return;
4756 }
4757 }
4758 let _: () = unsafe { msg_send![super(self), keyDown: event] };
4759 });
4760 }
4761 }
4762);
4763
4764fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4767 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4768 return Some((view.retain(), provider));
4769 }
4770 view.subviews()
4771 .iter()
4772 .find_map(|view| list_row_menu_provider(&view))
4773}
4774
4775fn inherited_context_menu(
4779 view: &NSView,
4780 event: &objc2_app_kit::NSEvent,
4781) -> Option<Option<Retained<NSMenu>>> {
4782 let mut current = Some(view.retain());
4783 while let Some(view) = current {
4784 if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4785 let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4786 let items = provider(day_spec::Point::new(point.x, point.y));
4787 return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4788 }
4789 current = unsafe { view.superview() };
4790 }
4791 None
4792}
4793
4794impl DayListView {
4795 fn report_focus(&self, focused: bool) {
4796 ffi_guard::contain((), || {
4797 if let Some(target) = unsafe { self.target() }
4798 && let Some(data) = target.downcast_ref::<DayListData>()
4799 {
4800 emit(data.ivars().node, Event::FocusChanged(focused));
4801 }
4802 });
4803 }
4804}
4805
4806struct ListIvars {
4807 node: NodeId,
4808 source: RefCell<Option<ListSource>>,
4810 selectable: std::cell::Cell<bool>,
4811 multi: std::cell::Cell<bool>,
4813 suppress: std::cell::Cell<bool>,
4815 tokens: RefCell<Vec<u64>>,
4818 automatic: bool,
4822 sections: bool,
4826 header_estimate: std::cell::Cell<f64>,
4828 heights: RefCell<std::collections::HashMap<u64, f64>>,
4831 cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4834 estimate: std::cell::Cell<f64>,
4837 heights_pending: std::cell::Cell<bool>,
4839}
4840
4841define_class!(
4842 #[unsafe(super(NSObject))]
4843 #[thread_kind = MainThreadOnly]
4844 #[name = "DayListData"]
4845 #[ivars = ListIvars]
4846 struct DayListData;
4847
4848 unsafe impl NSObjectProtocol for DayListData {}
4849 unsafe impl NSControlTextEditingDelegate for DayListData {}
4850
4851 impl DayListData {
4852 #[unsafe(method(respondsToSelector:))]
4856 fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4857 if selector == objc2::sel!(tableView:heightOfRow:)
4858 && !self.ivars().automatic
4859 && !self.ivars().sections
4860 {
4861 false
4862 } else {
4863 unsafe { msg_send![super(self), respondsToSelector: selector] }
4864 }
4865 }
4866
4867 #[unsafe(method(listViewportChanged:))]
4868 fn list_viewport_changed(&self, notification: &NSNotification) {
4869 ffi_guard::contain((), || {
4870 let source = self.ivars().source.borrow().clone();
4871 if let Some(source) = source && let Some(report) = &source.first_visible
4872 && let Some(object) = notification.object()
4873 && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4874 && let Some(document) = clip.documentView()
4875 && let Some(table) = document.downcast_ref::<NSTableView>() {
4876 let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4877 report(visible.location.min((source.len)().saturating_sub(1)));
4878 }
4879 });
4880 }
4881
4882 #[unsafe(method(activateRow:))]
4883 fn activate_row(&self, table: &NSTableView) {
4884 ffi_guard::contain((), || {
4885 let row = unsafe { table.selectedRow() };
4886 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4887 });
4888 }
4889 #[unsafe(method(doubleClickRow:))]
4890 fn double_click_row(&self, table: &NSTableView) {
4891 ffi_guard::contain((), || {
4892 let row = unsafe { table.clickedRow() };
4893 if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4894 });
4895 }
4896 }
4897
4898 unsafe impl NSTableViewDataSource for DayListData {
4899 #[unsafe(method(numberOfRowsInTableView:))]
4900 fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4901 ffi_guard::contain(0, || {
4905 self.ivars()
4906 .source
4907 .borrow()
4908 .as_ref()
4909 .map(|s| (s.len)() as isize)
4910 .unwrap_or(0)
4911 })
4912 }
4913
4914 #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4920 fn pasteboard_writer_for_row(
4921 &self,
4922 _tv: &NSTableView,
4923 row: isize,
4924 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4925 let make = || {
4928 let reorderable = self
4930 .ivars()
4931 .source
4932 .borrow()
4933 .as_ref()
4934 .is_some_and(|s| s.reorder.is_some());
4935 if !reorderable || row < 0 || self.is_header(row) {
4937 return None;
4938 }
4939 let item = objc2_app_kit::NSPasteboardItem::new();
4940 unsafe {
4941 item.setString_forType(
4942 &NSString::from_str(&row.to_string()),
4943 &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4944 );
4945 }
4946 Some(ProtocolObject::from_retained(item))
4947 };
4948 ffi_guard::contain(None, make)
4949 }
4950
4951 #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4952 fn validate_drop(
4953 &self,
4954 tv: &NSTableView,
4955 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4956 row: isize,
4957 _op: objc2_app_kit::NSTableViewDropOperation,
4958 ) -> objc2_app_kit::NSDragOperation {
4959 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4961 let Some((from, len)) = self.drag_context(tv, info) else {
4962 return objc2_app_kit::NSDragOperation::None;
4963 };
4964 let ins = row.clamp(0, len as isize) as usize;
4967 let to = insertion_to_target(from, ins, len);
4968 let accepted = self.can_move(from, to);
4969 if accepted < 0 {
4970 return objc2_app_kit::NSDragOperation::None;
4971 }
4972 let accepted = (accepted as usize).min(len.saturating_sub(1));
4973 if accepted != to {
4974 unsafe {
4976 tv.setDropRow_dropOperation(
4977 target_to_insertion(from, accepted) as isize,
4978 objc2_app_kit::NSTableViewDropOperation::Above,
4979 );
4980 }
4981 }
4982 objc2_app_kit::NSDragOperation::Move
4983 })
4984 }
4985
4986 #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4987 fn accept_drop(
4988 &self,
4989 tv: &NSTableView,
4990 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4991 row: isize,
4992 _op: objc2_app_kit::NSTableViewDropOperation,
4993 ) -> bool {
4994 let drop = || {
4996 let Some((from, len)) = self.drag_context(tv, info) else {
4997 return false;
4998 };
4999 let ins = row.clamp(0, len as isize) as usize;
5000 let to = insertion_to_target(from, ins, len);
5001 let accepted = self.can_move(from, to);
5002 if accepted < 0 {
5003 return false;
5004 }
5005 let accepted = (accepted as usize).min(len.saturating_sub(1));
5006 if accepted == from {
5007 return true; }
5009 let mv = self
5013 .ivars()
5014 .source
5015 .borrow()
5016 .as_ref()
5017 .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
5018 let Some(mv) = mv else { return false };
5019 mv(from, accepted);
5020 {
5023 let mut toks = self.ivars().tokens.borrow_mut();
5024 if from < toks.len() && accepted < toks.len() {
5025 let t = toks.remove(from);
5026 toks.insert(accepted, t);
5027 }
5028 }
5029 unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
5030 if let Some(scroll) = tv.enclosingScrollView() {
5031 post_settle_list_drop(ptr_of(&scroll));
5032 }
5033 true
5034 };
5035 ffi_guard::contain(false, drop)
5037 }
5038 }
5039
5040 unsafe impl NSTableViewDelegate for DayListData {
5041 #[unsafe(method(tableView:heightOfRow:))]
5046 fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
5047 ffi_guard::contain(44.0, || {
5048 let ivars = self.ivars();
5049 let header = self.is_header(row);
5050 if !header && !ivars.automatic {
5052 return unsafe { tv.rowHeight() };
5053 }
5054 let token = ivars
5055 .source
5056 .borrow()
5057 .as_ref()
5058 .filter(|s| row >= 0 && (row as usize) < (s.len)())
5059 .map(|s| (s.token_at)(row as usize));
5060 token
5061 .and_then(|t| ivars.heights.borrow().get(&t).copied())
5062 .unwrap_or_else(|| {
5063 if header {
5064 ivars.header_estimate.get()
5065 } else {
5066 ivars.estimate.get()
5067 }
5068 })
5069 })
5070 }
5071
5072 #[unsafe(method(tableView:isGroupRow:))]
5076 fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
5077 ffi_guard::contain(false, || self.is_header(row))
5078 }
5079
5080 #[unsafe(method(tableView:shouldSelectRow:))]
5082 fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
5083 ffi_guard::contain(true, || !self.is_header(row))
5084 }
5085
5086 #[unsafe(method_id(tableView:viewForTableColumn:row:))]
5087 fn view_for_row(
5088 &self,
5089 tv: &NSTableView,
5090 _col: Option<&NSTableColumn>,
5091 row: isize,
5092 ) -> Option<Retained<NSView>> {
5093 ffi_guard::contain(None, || {
5095 let mtm = self.mtm();
5096 let header = self.is_header(row);
5098 let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
5099 let cell: Retained<NSView> =
5101 unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5102 let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
5103 unsafe { v.setIdentifier(Some(&ident)) };
5104 v
5105 });
5106 let source = self.ivars().source.borrow().clone();
5110 if let Some(source) = source {
5111 let raw = Retained::as_ptr(&cell) as RawHandle;
5112 (source.bind_row)(row as usize, raw);
5113 if self.ivars().automatic || header {
5114 self.note_row_height(tv, &source, row, raw, header);
5115 }
5116 }
5117 Some(cell)
5118 })
5119 }
5120
5121 #[unsafe(method(tableView:didRemoveRowView:forRow:))]
5122 fn did_remove_row_view(
5123 &self,
5124 _tv: &NSTableView,
5125 row_view: &objc2_app_kit::NSTableRowView,
5126 _row: isize,
5127 ) {
5128 ffi_guard::contain((), || {
5134 let Some(cell) = row_view.subviews().iter().find(|sub| {
5135 sub.identifier()
5136 .map(|i| {
5137 let i = i.to_string();
5138 i == DAY_ROW_CELL || i == DAY_HEADER_CELL
5139 })
5140 .unwrap_or(false)
5141 }) else {
5142 return;
5143 };
5144 let cell = Retained::into_raw(cell) as usize;
5147 let Some(this) = (unsafe {
5148 Retained::retain(self as *const DayListData as *mut DayListData)
5149 }) else {
5150 return;
5151 };
5152 let this = Retained::into_raw(this) as usize;
5153 <AppKit as Platform>::post(Box::new(move || {
5154 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5156 let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
5157 let (Some(this), Some(cell)) = (this, cell) else {
5158 return;
5159 };
5160 if cell.window().is_some() {
5161 return; }
5163 let recycle = this
5164 .ivars()
5165 .source
5166 .borrow()
5167 .as_ref()
5168 .map(|s| s.recycle.clone());
5169 if let Some(recycle) = recycle {
5170 recycle(Retained::as_ptr(&cell) as RawHandle);
5171 }
5172 }));
5173 })
5174 }
5175
5176 #[unsafe(method(tableViewSelectionDidChange:))]
5177 fn selection_did_change(&self, notification: &NSNotification) {
5178 ffi_guard::contain((), || {
5179 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5180 return;
5181 }
5182 let Some(obj) = (unsafe { notification.object() }) else {
5183 return;
5184 };
5185 let Ok(tv) = obj.downcast::<NSTableView>() else {
5186 return;
5187 };
5188 if self.ivars().multi.get() {
5189 let idx = unsafe { tv.selectedRowIndexes() };
5191 let mut rows = Vec::with_capacity(idx.count());
5192 let mut i = idx.firstIndex();
5193 while i != objc2_foundation::NSNotFound as usize {
5194 rows.push(i as i64);
5195 i = unsafe { idx.indexGreaterThanIndex(i) };
5196 }
5197 emit(self.ivars().node, Event::SelectionSet(rows));
5198 } else {
5199 let row = unsafe { tv.selectedRow() };
5200 if row >= 0 {
5201 emit(self.ivars().node, Event::SelectionChanged(row as i64));
5202 } else {
5203 emit(self.ivars().node, Event::SelectionSet(Vec::new()));
5211 }
5212 }
5213 })
5214 }
5215
5216 #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
5222 fn row_actions_for_row(
5223 &self,
5224 tv: &NSTableView,
5225 row: isize,
5226 edge: objc2_app_kit::NSTableRowActionEdge,
5227 ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
5228 ffi_guard::contain(NSArray::new(), || {
5230 let sw = self
5231 .ivars()
5232 .source
5233 .borrow()
5234 .as_ref()
5235 .and_then(|s| s.swipe.clone());
5236 let Some(sw) = sw else {
5237 return NSArray::new();
5238 };
5239 if row < 0 {
5240 return NSArray::new();
5241 }
5242 let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
5244 day_spec::SwipeEdge::Leading
5245 } else {
5246 day_spec::SwipeEdge::Trailing
5247 };
5248 let offer = (sw.actions_at)(row as usize, day_edge);
5249 let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
5250 .iter()
5251 .enumerate()
5252 .map(|(i, a)| {
5253 let style = if a.destructive {
5254 objc2_app_kit::NSTableViewRowActionStyle::Destructive
5255 } else {
5256 objc2_app_kit::NSTableViewRowActionStyle::Regular
5257 };
5258 let perform = sw.perform.clone();
5259 let table = tv.retain();
5262 let handler = block2::RcBlock::new(
5263 move |_action: std::ptr::NonNull<
5264 objc2_app_kit::NSTableViewRowAction,
5265 >,
5266 row: isize| {
5267 ffi_guard::contain((), || {
5268 perform(row as usize, day_edge, i);
5269 unsafe { table.setRowActionsVisible(false) };
5272 })
5273 },
5274 );
5275 let action =
5276 objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
5277 style,
5278 &NSString::from_str(&a.label),
5279 &handler,
5280 );
5281 if let Some(t) = a.tint {
5282 unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
5283 }
5284 if let Some(sym) = a.symbol {
5288 let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
5289 &NSString::from_str(day_spec::sf_symbol_name(sym)),
5290 None,
5291 );
5292 if let Some(img) = img {
5293 unsafe { action.setImage(Some(&img)) };
5294 }
5295 }
5296 action
5297 })
5298 .collect();
5299 NSArray::from_retained_slice(&actions)
5300 })
5301 }
5302 }
5303);
5304
5305impl DayListData {
5306 fn new(
5307 mtm: MainThreadMarker,
5308 node: NodeId,
5309 selectable: bool,
5310 multi: bool,
5311 automatic: bool,
5312 sections: bool,
5313 ) -> Retained<Self> {
5314 let this = Self::alloc(mtm).set_ivars(ListIvars {
5315 node,
5316 source: RefCell::new(None),
5317 selectable: std::cell::Cell::new(selectable),
5318 multi: std::cell::Cell::new(multi),
5319 suppress: std::cell::Cell::new(false),
5320 tokens: RefCell::new(Vec::new()),
5321 automatic,
5322 sections,
5323 header_estimate: std::cell::Cell::new(28.0),
5324 heights: RefCell::new(std::collections::HashMap::new()),
5325 cell_tokens: RefCell::new(std::collections::HashMap::new()),
5326 estimate: std::cell::Cell::new(44.0),
5327 heights_pending: std::cell::Cell::new(false),
5328 });
5329 unsafe { msg_send![super(this), init] }
5330 }
5331
5332 fn note_row_height(
5336 &self,
5337 table: &NSTableView,
5338 source: &ListSource,
5339 row: isize,
5340 cell: RawHandle,
5341 header: bool,
5342 ) {
5343 let height = (source.cell_height)(cell);
5344 if height <= 0.0 || row < 0 {
5345 return;
5346 }
5347 let token = (source.token_at)(row as usize);
5348 self.ivars()
5349 .cell_tokens
5350 .borrow_mut()
5351 .insert(cell as usize, token);
5352 self.ivars().heights.borrow_mut().insert(token, height);
5353 if header {
5354 self.ivars().header_estimate.set(height);
5355 } else {
5356 self.ivars().estimate.set(height);
5357 }
5358 let drawn = unsafe { table.rectOfRow(row) }.size.height;
5359 if (drawn - height).abs() > 0.5 {
5360 self.post_row_heights(table);
5361 }
5362 }
5363
5364 fn is_header(&self, row: isize) -> bool {
5366 row >= 0
5367 && self
5368 .ivars()
5369 .source
5370 .borrow()
5371 .as_ref()
5372 .and_then(|s| s.is_header.clone())
5373 .is_some_and(|is_header| is_header(row as usize))
5374 }
5375
5376 fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
5379 let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
5380 if let Some(token) = token {
5381 self.ivars().heights.borrow_mut().insert(token, height);
5382 self.post_row_heights(table);
5383 }
5384 }
5385
5386 fn post_row_heights(&self, table: &NSTableView) {
5390 if self.ivars().heights_pending.replace(true) {
5391 return;
5392 }
5393 let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
5396 return;
5397 };
5398 let this = Retained::into_raw(this) as usize;
5399 let table = Retained::into_raw(table.retain()) as usize;
5400 <AppKit as Platform>::post(Box::new(move || {
5401 let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5403 let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
5404 let (Some(this), Some(table)) = (this, table) else {
5405 return;
5406 };
5407 this.ivars().heights_pending.set(false);
5408 ffi_guard::contain((), || this.apply_row_heights(&table));
5409 }));
5410 }
5411
5412 fn apply_row_heights(&self, table: &NSTableView) {
5413 let Some(source) = self.ivars().source.borrow().clone() else {
5414 return;
5415 };
5416 let count = unsafe { table.numberOfRows() }.max(0) as usize;
5417 let shown = unsafe { table.rowsInRect(table.visibleRect()) };
5418 let first = shown.location.saturating_sub(8);
5420 let last = (shown.location + shown.length + 8)
5421 .min(count)
5422 .min((source.len)());
5423 let changed = objc2_foundation::NSMutableIndexSet::new();
5424 {
5425 let heights = self.ivars().heights.borrow();
5426 for row in first..last {
5427 if let Some(&height) = heights.get(&(source.token_at)(row)) {
5428 let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
5429 if (drawn - height).abs() > 0.5 {
5430 unsafe { changed.addIndex(row) };
5431 }
5432 }
5433 }
5434 }
5435 if changed.count() == 0 {
5436 return;
5437 }
5438 NSAnimationContext::beginGrouping();
5440 NSAnimationContext::currentContext().setDuration(0.0);
5441 unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
5442 NSAnimationContext::endGrouping();
5443 }
5444
5445 fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
5457 let source = self.ivars().source.borrow();
5458 let source = source.as_ref()?;
5459 let n = (source.len)();
5460 let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
5461 let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
5462 if old.len() != n || n == 0 || old == new {
5463 return None;
5464 }
5465 let (mut so, mut sn) = (old.clone(), new.clone());
5466 so.sort_unstable();
5467 sn.sort_unstable();
5468 if so != sn {
5469 return None;
5470 }
5471 for i in 0..n {
5472 if old[i] != new[i]
5473 && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
5474 {
5475 return None;
5476 }
5477 }
5478 let mut work = old;
5479 let mut moves = Vec::new();
5480 for i in 0..n {
5481 if work[i] == new[i] {
5482 continue;
5483 }
5484 let j = (i + 1..n).find(|&j| work[j] == new[i])?;
5485 let t = work.remove(j);
5486 work.insert(i, t);
5487 moves.push((j, i));
5488 }
5489 Some(moves)
5490 }
5491
5492 fn drag_context(
5496 &self,
5497 tv: &NSTableView,
5498 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5499 ) -> Option<(usize, usize)> {
5500 let src = unsafe { info.draggingSource() }?;
5501 if Retained::as_ptr(&src) as *const std::ffi::c_void
5502 != tv as *const NSTableView as *const std::ffi::c_void
5503 {
5504 return None;
5505 }
5506 let pb = unsafe { info.draggingPasteboard() };
5507 let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5508 .to_string()
5509 .parse::<usize>()
5510 .ok()?;
5511 let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5512 (from < len).then_some((from, len))
5513 }
5514
5515 fn can_move(&self, from: usize, to: usize) -> i64 {
5517 self.ivars()
5518 .source
5519 .borrow()
5520 .as_ref()
5521 .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5522 .unwrap_or(-1)
5523 }
5524}
5525
5526const DAY_ROW_CELL: &str = "day.cell";
5528const DAY_HEADER_CELL: &str = "day.header";
5529
5530const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5532
5533fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5536 let to = if ins > from { ins - 1 } else { ins };
5537 to.min(len.saturating_sub(1))
5538}
5539
5540fn target_to_insertion(from: usize, to: usize) -> usize {
5542 if to > from { to + 1 } else { to }
5543}
5544
5545type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5547
5548fn list_entry(key: usize) -> Option<ListEntry> {
5555 LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5556}
5557
5558struct TreeIvars {
5563 node: NodeId,
5564 source: RefCell<Option<TreeSource>>,
5566 selectable: std::cell::Cell<bool>,
5567 suppress: std::cell::Cell<bool>,
5569 items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5573}
5574
5575define_class!(
5576 #[unsafe(super(NSObject))]
5577 #[thread_kind = MainThreadOnly]
5578 #[name = "DayTreeData"]
5579 #[ivars = TreeIvars]
5580 struct DayTreeData;
5581
5582 unsafe impl NSObjectProtocol for DayTreeData {}
5583
5584 unsafe impl NSOutlineViewDataSource for DayTreeData {
5585 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5586 fn number_of_children(
5587 &self,
5588 _ov: &objc2_app_kit::NSOutlineView,
5589 item: Option<&objc2::runtime::AnyObject>,
5590 ) -> isize {
5591 ffi_guard::contain(0, || {
5595 let parent = item.and_then(Self::token_of_item);
5596 if item.is_some() && parent.is_none() {
5597 return 0; }
5599 self.ivars()
5600 .source
5601 .borrow()
5602 .as_ref()
5603 .map(|s| (s.children_len)(parent) as isize)
5604 .unwrap_or(0)
5605 })
5606 }
5607
5608 #[unsafe(method_id(outlineView:child:ofItem:))]
5609 fn child_of_item(
5610 &self,
5611 _ov: &objc2_app_kit::NSOutlineView,
5612 index: isize,
5613 item: Option<&objc2::runtime::AnyObject>,
5614 ) -> Retained<objc2::runtime::AnyObject> {
5615 let token = ffi_guard::contain(0, || {
5619 let parent = item.and_then(Self::token_of_item);
5620 self.ivars()
5621 .source
5622 .borrow()
5623 .as_ref()
5624 .map(|s| (s.child_token)(parent, index.max(0) as usize))
5625 .unwrap_or(0)
5626 });
5627 let ns = self.intern(token);
5628 unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5629 }
5630
5631 #[unsafe(method(outlineView:isItemExpandable:))]
5632 fn is_expandable(
5633 &self,
5634 _ov: &objc2_app_kit::NSOutlineView,
5635 item: &objc2::runtime::AnyObject,
5636 ) -> bool {
5637 ffi_guard::contain(false, || {
5638 let Some(token) = Self::token_of_item(item) else {
5639 return false;
5640 };
5641 self.ivars()
5642 .source
5643 .borrow()
5644 .as_ref()
5645 .map(|s| (s.expandable)(token))
5646 .unwrap_or(false)
5647 })
5648 }
5649
5650 #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5656 fn pasteboard_writer_for_item(
5657 &self,
5658 _ov: &objc2_app_kit::NSOutlineView,
5659 item: &objc2::runtime::AnyObject,
5660 ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5661 let make = || {
5662 let movable = self
5663 .ivars()
5664 .source
5665 .borrow()
5666 .as_ref()
5667 .is_some_and(|s| s.moves.is_some());
5668 let token = Self::token_of_item(item)?;
5669 if !movable {
5670 return None;
5671 }
5672 let pbitem = objc2_app_kit::NSPasteboardItem::new();
5673 unsafe {
5674 pbitem.setString_forType(
5675 &NSString::from_str(&token.to_string()),
5676 &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5677 );
5678 }
5679 Some(ProtocolObject::from_retained(pbitem))
5680 };
5681 ffi_guard::contain(None, make)
5682 }
5683
5684 #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5685 fn validate_drop(
5686 &self,
5687 ov: &objc2_app_kit::NSOutlineView,
5688 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5689 item: Option<&objc2::runtime::AnyObject>,
5690 child_index: isize,
5691 ) -> objc2_app_kit::NSDragOperation {
5692 ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5693 match self.drop_proposal(ov, info, item, child_index) {
5694 Some((token, parent, index)) if self.can_move(token, parent, index) => {
5695 objc2_app_kit::NSDragOperation::Move
5696 }
5697 _ => objc2_app_kit::NSDragOperation::None,
5698 }
5699 })
5700 }
5701
5702 #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5703 fn accept_drop(
5704 &self,
5705 ov: &objc2_app_kit::NSOutlineView,
5706 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5707 item: Option<&objc2::runtime::AnyObject>,
5708 child_index: isize,
5709 ) -> bool {
5710 let drop = || {
5711 let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5712 else {
5713 return false;
5714 };
5715 if !self.can_move(token, parent, index) {
5716 return false;
5717 }
5718 let mv = self
5721 .ivars()
5722 .source
5723 .borrow()
5724 .as_ref()
5725 .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5726 let Some(mv) = mv else { return false };
5727 mv(token, parent, index);
5728 true
5729 };
5730 ffi_guard::contain(false, drop)
5731 }
5732 }
5733
5734 unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5735
5736 unsafe impl NSOutlineViewDelegate for DayTreeData {
5737 #[unsafe(method(outlineView:isGroupItem:))]
5738 fn is_group_item(
5739 &self,
5740 _ov: &objc2_app_kit::NSOutlineView,
5741 item: &objc2::runtime::AnyObject,
5742 ) -> bool {
5743 Self::token_of_item(item).is_some_and(|t| {
5744 self.ivars()
5745 .source
5746 .borrow()
5747 .as_ref()
5748 .is_some_and(|s| (s.section_header)(t))
5749 })
5750 }
5751 #[unsafe(method(outlineView:shouldSelectItem:))]
5752 fn should_select_item(
5753 &self,
5754 _ov: &objc2_app_kit::NSOutlineView,
5755 item: &objc2::runtime::AnyObject,
5756 ) -> bool {
5757 Self::token_of_item(item).is_some_and(|t| {
5758 self.ivars()
5759 .source
5760 .borrow()
5761 .as_ref()
5762 .is_some_and(|s| !(s.section_header)(t))
5763 })
5764 }
5765
5766 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5767 fn view_for_item(
5768 &self,
5769 ov: &objc2_app_kit::NSOutlineView,
5770 _col: Option<&NSTableColumn>,
5771 item: &objc2::runtime::AnyObject,
5772 ) -> Option<Retained<NSView>> {
5773 ffi_guard::contain(None, || {
5775 let mtm = self.mtm();
5776 let token = Self::token_of_item(item)?;
5777 let ident = NSString::from_str("day.tree.cell");
5778 let cell: Retained<NSView> =
5782 unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5783 let v: Retained<NSView> =
5784 Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5785 unsafe { v.setIdentifier(Some(&ident)) };
5786 v
5787 });
5788 if let Some(source) = self.ivars().source.borrow().as_ref() {
5789 let raw = Retained::as_ptr(&cell) as RawHandle;
5790 if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5791 unsafe {
5792 cell.setTextField(None);
5793 }
5794 }
5795 (source.bind_row)(token, raw);
5796 if (source.section_header)(token) {
5799 fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5800 for child in unsafe { view.subviews() }.iter() {
5801 if let Ok(label) = child.clone().downcast::<NSTextField>() {
5802 return Some(label);
5803 }
5804 if let Some(label) = label_in(&child) {
5805 return Some(label);
5806 }
5807 }
5808 None
5809 }
5810 if let Some(label) = label_in(&cell) {
5811 let cell = cell.downcast_ref::<DayTreeCell>()?;
5812 unsafe {
5813 cell.setTextField(Some(&label));
5814 }
5815 }
5816 }
5817 }
5818 Some(cell)
5819 })
5820 }
5821
5822 #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5823 fn type_select_string(
5824 &self,
5825 _ov: &objc2_app_kit::NSOutlineView,
5826 _col: Option<&NSTableColumn>,
5827 item: &objc2::runtime::AnyObject,
5828 ) -> Option<Retained<NSString>> {
5829 ffi_guard::contain(None, || {
5830 let token = Self::token_of_item(item)?;
5831 let text = self
5832 .ivars()
5833 .source
5834 .borrow()
5835 .as_ref()
5836 .map(|s| (s.type_select_text)(token))
5837 .unwrap_or_default();
5838 (!text.is_empty()).then(|| NSString::from_str(&text))
5840 })
5841 }
5842
5843 #[unsafe(method_id(outlineView:rowViewForItem:))]
5844 fn row_view_for_item(
5845 &self,
5846 ov: &objc2_app_kit::NSOutlineView,
5847 _item: &objc2::runtime::AnyObject,
5848 ) -> Retained<objc2_app_kit::NSTableRowView> {
5849 if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5850 unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5852 } else {
5853 let rv: Retained<DayTreeRowView> =
5855 unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5856 Retained::into_super(rv)
5857 }
5858 }
5859
5860 #[unsafe(method(outlineViewSelectionDidChange:))]
5861 fn selection_did_change(&self, notification: &NSNotification) {
5862 ffi_guard::contain((), || {
5863 if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5864 return;
5865 }
5866 let Some(obj) = (unsafe { notification.object() }) else {
5867 return;
5868 };
5869 let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5870 return;
5871 };
5872 let idx = unsafe { ov.selectedRowIndexes() };
5874 let mut tokens = Vec::with_capacity(idx.count());
5875 let mut i = idx.firstIndex();
5876 while i != objc2_foundation::NSNotFound as usize {
5877 if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5878 && let Some(tok) = Self::token_of_item(&item)
5879 {
5880 tokens.push(tok);
5881 }
5882 i = unsafe { idx.indexGreaterThanIndex(i) };
5883 }
5884 emit(self.ivars().node, Event::TreeSelection(tokens));
5885 })
5886 }
5887
5888 #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5889 fn did_remove_row_view(
5890 &self,
5891 ov: &objc2_app_kit::NSOutlineView,
5892 row_view: &objc2_app_kit::NSTableRowView,
5893 _row: isize,
5894 ) {
5895 ffi_guard::contain((), || {
5901 let mut cell_ptr: Option<usize> = None;
5902 for sub in row_view.subviews().iter() {
5903 let is_cell = sub
5904 .identifier()
5905 .map(|i| i.to_string() == "day.tree.cell")
5906 .unwrap_or(false);
5907 if is_cell {
5908 cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5909 }
5910 }
5911 let Some(cell) = cell_ptr else { return };
5912 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5913 return;
5914 };
5915 let key = Retained::as_ptr(&scroll) as usize;
5916 let retained =
5920 unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5921 as usize;
5922 <AppKit as Platform>::post(Box::new(move || {
5923 let cell_view: Retained<NSView> =
5926 match unsafe { Retained::from_raw(retained as *mut NSView) } {
5927 Some(v) => v,
5928 None => return,
5929 };
5930 let recycle = tree_entry(key).and_then(|(_, data)| {
5931 data.ivars()
5932 .source
5933 .borrow()
5934 .as_ref()
5935 .map(|s| s.recycle.clone())
5936 });
5937 let Some(recycle) = recycle else { return };
5938 if cell_view.window().is_some() {
5939 return; }
5941 recycle(cell as RawHandle);
5942 }));
5943 })
5944 }
5945
5946 #[unsafe(method(outlineViewItemDidExpand:))]
5947 fn item_did_expand(&self, notification: &NSNotification) {
5948 self.report_disclosure(notification, true);
5949 }
5950
5951 #[unsafe(method(outlineViewItemDidCollapse:))]
5952 fn item_did_collapse(&self, notification: &NSNotification) {
5953 self.report_disclosure(notification, false);
5954 }
5955 }
5956);
5957
5958impl DayTreeData {
5959 fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5960 let this = Self::alloc(mtm).set_ivars(TreeIvars {
5961 node,
5962 source: RefCell::new(None),
5963 selectable: std::cell::Cell::new(selectable),
5964 suppress: std::cell::Cell::new(false),
5965 items: RefCell::new(HashMap::new()),
5966 });
5967 unsafe { msg_send![super(this), init] }
5968 }
5969
5970 fn intern(&self, token: u64) -> Retained<NSNumber> {
5972 self.ivars()
5973 .items
5974 .borrow_mut()
5975 .entry(token)
5976 .or_insert_with(|| NSNumber::new_u64(token))
5977 .clone()
5978 }
5979
5980 fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5981 item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5982 }
5983
5984 fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5987 ffi_guard::contain((), || {
5988 if self.ivars().suppress.get() {
5989 return;
5990 }
5991 let token = unsafe { notification.userInfo() }
5992 .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5993 .and_then(|item| Self::token_of_item(&item));
5994 if let Some(token) = token {
5995 emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5996 }
5997 })
5998 }
5999
6000 fn drop_proposal(
6004 &self,
6005 ov: &objc2_app_kit::NSOutlineView,
6006 info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6007 item: Option<&objc2::runtime::AnyObject>,
6008 child_index: isize,
6009 ) -> Option<(u64, Option<u64>, Option<usize>)> {
6010 let src = unsafe { info.draggingSource() }?;
6011 if Retained::as_ptr(&src) as *const std::ffi::c_void
6012 != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
6013 {
6014 return None;
6015 }
6016 let pb = unsafe { info.draggingPasteboard() };
6017 let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
6018 .to_string()
6019 .parse::<u64>()
6020 .ok()?;
6021 let parent = match item {
6022 Some(i) => Some(Self::token_of_item(i)?), None => None,
6024 };
6025 let index = (child_index >= 0).then_some(child_index as usize);
6026 Some((token, parent, index))
6027 }
6028
6029 fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
6031 self.ivars()
6032 .source
6033 .borrow()
6034 .as_ref()
6035 .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
6036 .map(|v| v == MoveVerdict::Allow)
6037 .unwrap_or(false)
6038 }
6039}
6040
6041define_class!(
6047 #[unsafe(super(objc2_app_kit::NSOutlineView))]
6048 #[thread_kind = MainThreadOnly]
6049 #[name = "DayOutlineView"]
6050 struct DayOutlineView;
6051
6052 impl DayOutlineView {
6053 #[unsafe(method(layout))]
6054 fn layout(&self) {
6055 sync_tree_width(self);
6056 let _: () = unsafe { msg_send![super(self), layout] };
6057 }
6058
6059 #[unsafe(method_id(menuForEvent:))]
6062 fn menu_for_event(
6063 &self,
6064 event: &objc2_app_kit::NSEvent,
6065 ) -> Option<Retained<NSMenu>> {
6066 ffi_guard::contain(None, || {
6067 let scroll = unsafe { self.enclosingScrollView() }?;
6068 let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
6069 let row_menu = data
6070 .ivars()
6071 .source
6072 .borrow()
6073 .as_ref()
6074 .and_then(|s| s.row_menu.clone())?;
6075 let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6076 let row = unsafe { self.rowAtPoint(p) };
6077 if row < 0 {
6078 return None;
6079 }
6080 let token =
6081 unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
6082 let items = row_menu(token);
6083 if items.is_empty() {
6084 return None;
6085 }
6086 Some(build_ns_menu(self.mtm(), "", &items))
6087 })
6088 }
6089 }
6090);
6091
6092define_class!(
6099 #[unsafe(super(objc2_app_kit::NSTableRowView))]
6100 #[thread_kind = MainThreadOnly]
6101 #[name = "DayTreeRowView"]
6102 struct DayTreeRowView;
6103
6104 impl DayTreeRowView {
6105 #[unsafe(method(drawSelectionInRect:))]
6106 fn draw_selection_in_rect(&self, _dirty: NSRect) {
6107 if !unsafe { self.isSelected() } {
6108 return;
6109 }
6110 let color = if unsafe { self.isEmphasized() } {
6111 unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
6112 } else {
6113 unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
6114 };
6115 let b = self.bounds();
6116 let pill = NSRect::new(
6117 NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
6118 NSSize::new(
6119 (b.size.width - 10.0).max(0.0),
6120 (b.size.height - 2.0).max(0.0),
6121 ),
6122 );
6123 unsafe {
6124 color.setFill();
6125 objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
6126 pill, 5.0, 5.0,
6127 )
6128 .fill();
6129 }
6130 }
6131 }
6132);
6133
6134define_class!(
6138 #[unsafe(super(objc2_app_kit::NSTableCellView))]
6139 #[thread_kind = MainThreadOnly]
6140 #[name = "DayTreeCell"]
6141 struct DayTreeCell;
6142
6143 impl DayTreeCell {
6144 #[unsafe(method(isFlipped))]
6145 fn is_flipped(&self) -> bool {
6146 true
6147 }
6148
6149 #[unsafe(method(layout))]
6150 fn layout(&self) {
6151 let _: () = unsafe { msg_send![super(self), layout] };
6152 ffi_guard::contain((), || {
6153 let width = self.bounds().size.width;
6154 if width <= 0.0 {
6155 return;
6156 }
6157 let mut cur = unsafe { self.superview() };
6161 let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
6162 while let Some(v) = cur {
6163 cur = unsafe { v.superview() };
6164 if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
6165 outline = Some(ov);
6166 break;
6167 }
6168 }
6169 let Some(ov) = outline else { return };
6170 let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
6171 return;
6172 };
6173 let f = tree_entry(Retained::as_ptr(&scroll) as usize)
6174 .and_then(|(_, data)| {
6175 data.ivars()
6176 .source
6177 .borrow()
6178 .as_ref()
6179 .map(|s| s.layout_cell_size.clone())
6180 });
6181 if let Some(f) = f {
6182 f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
6183 }
6184 })
6185 }
6186 }
6187);
6188
6189impl DayTreeCell {
6190 fn new(mtm: MainThreadMarker) -> Retained<Self> {
6191 unsafe { msg_send![Self::alloc(mtm), init] }
6192 }
6193}
6194
6195const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
6197
6198type TreeEntry = (
6200 Retained<objc2_app_kit::NSOutlineView>,
6201 Retained<DayTreeData>,
6202);
6203
6204fn tree_entry(key: usize) -> Option<TreeEntry> {
6207 TREE_STATE.with(|m| m.borrow().get(&key).cloned())
6208}
6209
6210fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
6214 let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
6215 return;
6216 };
6217 let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
6218 let f = outline.frame();
6219 if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
6220 unsafe {
6221 outline.setFrameSize(NSSize::new(clip_w, f.size.height));
6222 outline.sizeLastColumnToFit();
6223 }
6224 }
6225}
6226
6227fn post_realize_visible_tree_rows(key: usize) {
6230 <AppKit as Platform>::post(Box::new(move || {
6231 if let Some((outline, _)) = tree_entry(key) {
6232 let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
6233 for row in range.location..range.location + range.length {
6234 let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
6235 }
6236 }
6237 day_core::pump_events();
6238 }));
6239}
6240
6241type NavMenuEntry = (
6243 Retained<objc2_app_kit::NSOutlineView>,
6244 Retained<DayNavMenuData>,
6245);
6246
6247fn ns_rect(r: day_spec::Rect) -> NSRect {
6248 NSRect::new(
6249 NSPoint::new(r.origin.x, r.origin.y),
6250 NSSize::new(r.size.width, r.size.height),
6251 )
6252}
6253
6254fn draw_op(op: &DrawOp) {
6255 unsafe {
6256 match op {
6257 DrawOp::Stamp(st) => {
6263 let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
6264 for p in &st.at {
6265 if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
6266 unsafe { batch.appendBezierPath(©) };
6267 }
6268 }
6269 let color = match &st.paint {
6270 day_spec::Paint::Solid(c) => *c,
6271 _ => day_spec::Color::WHITE,
6274 };
6275 match &st.stroke {
6276 None => {
6277 nscolor(color).setFill();
6278 unsafe { batch.fill() };
6279 }
6280 Some(style) => {
6281 nscolor(color).setStroke();
6282 apply_stroke_style(&batch, style);
6283 unsafe { batch.stroke() };
6284 }
6285 }
6286 }
6287 DrawOp::Fill(shape, paint) => match paint {
6288 day_spec::Paint::Solid(color) => {
6289 nscolor(*color).setFill();
6290 if let Some(p) = bezier(shape) {
6291 p.fill();
6292 }
6293 }
6294 day_spec::Paint::Linear(g) => {
6295 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6298 let b = shape.bounds();
6299 let (s, e) = (g.start.resolve(b), g.end.resolve(b));
6300 NSGraphicsContext::saveGraphicsState_class();
6301 p.addClip();
6302 grad.drawFromPoint_toPoint_options(
6303 NSPoint::new(s.x, s.y),
6304 NSPoint::new(e.x, e.y),
6305 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6306 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6307 );
6308 NSGraphicsContext::restoreGraphicsState_class();
6309 }
6310 }
6311 day_spec::Paint::Radial(g) => {
6312 if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6315 let b = shape.bounds();
6316 NSGraphicsContext::saveGraphicsState_class();
6317 p.addClip();
6318 concat_unit_to_bounds(b);
6319 let c = NSPoint::new(g.center.x, g.center.y);
6320 grad.drawFromCenter_radius_toCenter_radius_options(
6321 c,
6322 0.0,
6323 c,
6324 g.radius,
6325 objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6326 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6327 );
6328 NSGraphicsContext::restoreGraphicsState_class();
6329 }
6330 }
6331 },
6332 DrawOp::Stroke(shape, paint, style) => {
6333 if let Some(p) = bezier(shape) {
6334 apply_stroke_style(&p, style);
6335 match paint {
6336 day_spec::Paint::Solid(color) => {
6337 nscolor(*color).setStroke();
6338 p.stroke();
6339 }
6340 _ => {
6346 let Some(ctx) = NSGraphicsContext::currentContext() else {
6347 return;
6348 };
6349 let cg = ctx.CGContext();
6350 NSGraphicsContext::saveGraphicsState_class();
6351 objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
6352 objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
6353 &cg,
6354 ));
6355 objc2_core_graphics::CGContext::clip(Some(&cg));
6356 draw_gradient_in(paint, shape.bounds());
6357 NSGraphicsContext::restoreGraphicsState_class();
6358 }
6359 }
6360 }
6361 }
6362 DrawOp::Clip(shape) => {
6363 if let Some(p) = bezier(shape) {
6365 p.addClip();
6366 }
6367 }
6368 DrawOp::Text {
6369 text,
6370 at,
6371 size,
6372 color,
6373 anchor,
6374 font,
6375 } => {
6376 let font = canvas_nsfont(*size, font);
6377 let attrs = canvas_text_attrs(&font, *color);
6378 let ns = NSString::from_str(text);
6379 let mut origin = NSPoint::new(at.x, at.y);
6380 if *anchor != day_spec::TextAnchor::LEADING {
6385 let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
6386 let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
6387 origin.x += dx;
6388 origin.y += dy;
6389 }
6390 let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
6391 }
6392 DrawOp::Image {
6396 image,
6397 rect,
6398 opacity,
6399 source,
6400 } => {
6401 let held = BITMAPS.with(|m| {
6402 m.borrow()
6403 .get(&image.0)
6404 .map(|b| (b.image.clone(), b.info.pixels))
6405 });
6406 if let Some((img, pixels)) = held {
6407 let region = match source {
6413 None => Some((NSRect::ZERO, *rect)),
6414 Some(src) => {
6415 day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
6416 let sz = img.size();
6417 let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
6418 let from = NSRect::new(
6419 NSPoint::new(
6420 src.origin.x * rx,
6421 (pixels.height - src.origin.y - src.size.height) * ry,
6422 ),
6423 NSSize::new(src.size.width * rx, src.size.height * ry),
6424 );
6425 (from, dest)
6426 })
6427 }
6428 };
6429 if let Some((from, dest)) = region {
6430 let dest = NSRect::new(
6431 NSPoint::new(dest.origin.x, dest.origin.y),
6432 NSSize::new(dest.size.width, dest.size.height),
6433 );
6434 img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
6438 dest,
6439 from,
6440 objc2_app_kit::NSCompositingOperation::SourceOver,
6441 *opacity,
6442 true,
6443 None,
6444 );
6445 }
6446 }
6447 }
6448 DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
6449 DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
6450 DrawOp::Concat(m) => {
6451 let t = NSAffineTransform::new();
6452 t.setTransformStruct(NSAffineTransformStruct {
6453 m11: m.a,
6454 m12: m.b,
6455 m21: m.c,
6456 m22: m.d,
6457 tX: m.tx,
6458 tY: m.ty,
6459 });
6460 t.concat();
6461 }
6462 }
6463 }
6464}
6465
6466fn nsgradient(
6468 stops: &[(f64, day_spec::Color)],
6469) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
6470 if stops.is_empty() {
6471 return None;
6472 }
6473 let colors = objc2_foundation::NSArray::from_retained_slice(
6474 &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
6475 );
6476 let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
6477 unsafe {
6478 objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
6479 objc2_app_kit::NSGradient::alloc(),
6480 &colors,
6481 locations.as_ptr(),
6482 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
6483 )
6484 }
6485}
6486
6487fn concat_unit_to_bounds(b: day_spec::Rect) {
6490 let t = NSAffineTransform::new();
6491 t.setTransformStruct(NSAffineTransformStruct {
6492 m11: b.size.width,
6493 m12: 0.0,
6494 m21: 0.0,
6495 m22: b.size.height,
6496 tX: b.origin.x,
6497 tY: b.origin.y,
6498 });
6499 unsafe { t.concat() };
6500}
6501
6502fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
6508 use day_spec::{LineCap, LineJoin};
6509 unsafe {
6510 p.setLineWidth(style.width);
6511 p.setLineCapStyle(match style.cap {
6512 LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
6513 LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
6514 LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
6515 });
6516 if style.is_plain() {
6517 return;
6518 }
6519 p.setLineJoinStyle(match style.join {
6520 LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
6521 LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
6522 LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
6523 });
6524 p.setMiterLimit(style.miter_limit);
6525 if !style.dash.is_empty() {
6526 let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
6527 p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
6528 }
6529 }
6530}
6531
6532fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6536 let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6537 | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6538 match paint {
6539 day_spec::Paint::Linear(g) => {
6540 if let Some(grad) = nsgradient(&g.stops) {
6541 let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6542 unsafe {
6543 grad.drawFromPoint_toPoint_options(
6544 NSPoint::new(s.x, s.y),
6545 NSPoint::new(e.x, e.y),
6546 opts,
6547 )
6548 };
6549 }
6550 }
6551 day_spec::Paint::Radial(g) => {
6552 if let Some(grad) = nsgradient(&g.stops) {
6553 NSGraphicsContext::saveGraphicsState_class();
6554 concat_unit_to_bounds(bounds);
6555 let c = NSPoint::new(g.center.x, g.center.y);
6556 unsafe {
6557 grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
6558 };
6559 NSGraphicsContext::restoreGraphicsState_class();
6560 }
6561 }
6562 day_spec::Paint::Solid(_) => {}
6563 }
6564}
6565
6566fn apply_button_content(
6567 btn: &NSButton,
6568 title: &str,
6569 icon: Option<&day_spec::Icon>,
6570 icon_only: bool,
6571) {
6572 let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6573 if let Some(image) = &image {
6574 let size = image.size();
6575 let longest = size.width.max(size.height);
6576 if longest > 0.0 {
6577 image.setSize(objc2_foundation::NSSize::new(
6578 size.width * 20.0 / longest,
6579 size.height * 20.0 / longest,
6580 ));
6581 }
6582 }
6583 let style = BUTTON_STYLES
6584 .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6585 .unwrap_or_default();
6586 BUTTON_IMAGES.with(|images| {
6587 images.remove(ptr_of(btn));
6588 if let Some(image) = &image {
6589 images.insert(ptr_of(btn), image.clone());
6590 }
6591 });
6592 set_button_title(btn, title, style);
6593 unsafe {
6596 btn.setImagePosition(if image.is_none() {
6597 objc2_app_kit::NSCellImagePosition::NoImage
6598 } else if icon_only {
6599 objc2_app_kit::NSCellImagePosition::ImageOnly
6600 } else {
6601 objc2_app_kit::NSCellImagePosition::ImageLeading
6602 });
6603 }
6604 set_button_image(btn, style);
6605 unsafe {
6606 if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6609 btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6610 }
6611 let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6612 btn.setToolTip(tooltip.as_deref());
6613 }
6614}
6615
6616fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6620 use day_spec::props::ButtonStyleSpec as S;
6621 let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6622 let image = image.map(|source| {
6623 let S::Tinted(fill) = style else {
6624 return source;
6625 };
6626 let size = source.size();
6627 let ink = nscolor(S::on_tint(fill));
6628 let draw = block2::RcBlock::new(move |rect: NSRect| {
6629 source.drawInRect_fromRect_operation_fraction(
6630 rect,
6631 NSRect::ZERO,
6632 objc2_app_kit::NSCompositingOperation::SourceOver,
6633 1.0,
6634 );
6635 unsafe {
6636 ink.setFill();
6637 objc2_app_kit::NSRectFillUsingOperation(
6638 rect,
6639 objc2_app_kit::NSCompositingOperation::SourceIn,
6640 );
6641 }
6642 objc2::runtime::Bool::YES
6643 });
6644 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6645 });
6646 unsafe {
6647 let position = btn.imagePosition();
6648 let image = image.map(|source| {
6653 if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6656 return source;
6657 }
6658 let size = source.size();
6659 let template = source.isTemplate();
6660 let padded = NSSize::new(size.width + 8.0, size.height);
6661 let draw = block2::RcBlock::new(move |_rect: NSRect| {
6662 source.drawInRect_fromRect_operation_fraction(
6663 NSRect::new(NSPoint::new(0.0, 0.0), size),
6664 NSRect::ZERO,
6665 objc2_app_kit::NSCompositingOperation::SourceOver,
6666 1.0,
6667 );
6668 objc2::runtime::Bool::YES
6669 });
6670 let out =
6671 objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6672 out.setTemplate(template);
6673 out
6674 });
6675 btn.setImage(image.as_deref());
6676 btn.setImagePosition(position);
6677 btn.setImageHugsTitle(true);
6678 }
6679}
6680
6681fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6687 BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6688 unsafe {
6689 if on {
6690 btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6691 }
6692 btn.setState(if on {
6693 NSControlStateValueOn
6694 } else {
6695 NSControlStateValueOff
6696 });
6697 }
6698}
6699
6700const TINT_CORNER_RADIUS: f64 = 6.0;
6703
6704fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6714 use day_spec::props::ButtonStyleSpec as S;
6715 let title = unsafe { btn.title() }.to_string();
6716 unsafe {
6717 btn.setKeyEquivalent(&NSString::from_str(""));
6719 btn.setBezelColor(None);
6720 btn.setBordered(!matches!(style, S::Plain));
6721 match style {
6722 S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6723 S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6724 S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6727 }
6728 btn.setWantsLayer(true);
6729 if let Some(layer) = btn.layer() {
6730 match style {
6731 S::Tinted(c) => {
6732 layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6733 layer.setCornerRadius(TINT_CORNER_RADIUS);
6734 }
6735 _ => layer.setBackgroundColor(None),
6736 }
6737 }
6738 }
6739 BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6740 let ink = match style {
6741 S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6742 _ => None,
6743 };
6744 unsafe {
6745 btn.setContentTintColor(ink.as_deref());
6746 }
6747 set_button_title(btn, &title, style);
6748 set_button_image(btn, style);
6749}
6750
6751fn set_button_title(
6761 btn: &objc2_app_kit::NSButton,
6762 title: &str,
6763 style: day_spec::props::ButtonStyleSpec,
6764) {
6765 use day_spec::props::ButtonStyleSpec as S;
6766 let position = unsafe { btn.imagePosition() };
6769 let S::Tinted(fill) = style else {
6770 unsafe {
6772 btn.setTitle(&NSString::from_str(title));
6773 btn.setImagePosition(position);
6774 }
6775 return;
6776 };
6777 unsafe {
6778 let col = nscolor(S::on_tint(fill));
6779 let font = btn
6780 .font()
6781 .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6782 let para = objc2_app_kit::NSMutableParagraphStyle::new();
6785 para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6786 let keys: [&NSString; 3] = [
6787 objc2_app_kit::NSFontAttributeName,
6788 objc2_app_kit::NSForegroundColorAttributeName,
6789 objc2_app_kit::NSParagraphStyleAttributeName,
6790 ];
6791 let objs: [&objc2::runtime::AnyObject; 3] = [
6792 font.as_ref() as &objc2::runtime::AnyObject,
6793 col.as_ref() as &objc2::runtime::AnyObject,
6794 para.as_ref() as &objc2::runtime::AnyObject,
6795 ];
6796 let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6797 let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6798 objc2_foundation::NSAttributedString::alloc(),
6799 &NSString::from_str(title),
6800 Some(&attrs),
6801 );
6802 btn.setAttributedTitle(&s);
6803 btn.setImagePosition(position);
6804 }
6805}
6806
6807define_class!(
6810 #[unsafe(super(objc2_app_kit::NSImageView))]
6811 #[thread_kind = MainThreadOnly]
6812 #[name = "DayFillImageView"]
6813 struct FillImageView;
6814
6815 impl FillImageView {
6816 #[unsafe(method(drawRect:))]
6817 fn draw_rect(&self, dirty: NSRect) {
6818 let bounds = self.bounds();
6819 let image = unsafe { self.image() };
6820 let Some(size) = image.map(|image| image.size()).filter(|size| {
6821 size.width > 0.0 && size.height > 0.0
6822 && bounds.size.width > 0.0 && bounds.size.height > 0.0
6823 }) else {
6824 let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6825 return;
6826 };
6827 let x = bounds.size.width / size.width;
6828 let y = bounds.size.height / size.height;
6829 let scale = x.max(y) / x.min(y);
6830 let cx = bounds.origin.x + bounds.size.width / 2.0;
6831 let cy = bounds.origin.y + bounds.size.height / 2.0;
6832 NSGraphicsContext::saveGraphicsState_class();
6833 objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6834 let transform = NSAffineTransform::transform();
6835 transform.translateXBy_yBy(cx, cy);
6836 transform.scaleBy(scale);
6837 transform.translateXBy_yBy(-cx, -cy);
6838 transform.concat();
6839 let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6840 NSGraphicsContext::restoreGraphicsState_class();
6841 }
6842
6843 #[unsafe(method(setFrameSize:))]
6844 fn set_frame_size(&self, size: NSSize) {
6845 let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6846 NSView::setNeedsDisplay(self, true);
6847 }
6848 }
6849);
6850
6851fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6852 use day_spec::Shape;
6853 use objc2_app_kit::NSBezierPath;
6854 unsafe {
6855 Some(match shape {
6856 Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6857 Shape::RoundedRect(r, rad) => {
6858 NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6859 }
6860 Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6861 Shape::Arc {
6862 rect,
6863 start_deg,
6864 sweep_deg,
6865 } => {
6866 let p = NSBezierPath::new();
6867 let center = NSPoint::new(
6868 rect.origin.x + rect.size.width / 2.0,
6869 rect.origin.y + rect.size.height / 2.0,
6870 );
6871 let radius = rect.size.width.min(rect.size.height) / 2.0;
6872 p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6874 center,
6875 radius,
6876 *start_deg,
6877 *start_deg + *sweep_deg,
6878 );
6879 p
6880 }
6881 Shape::Line(a, b) => {
6882 let p = NSBezierPath::new();
6883 p.moveToPoint(NSPoint::new(a.x, a.y));
6884 p.lineToPoint(NSPoint::new(b.x, b.y));
6885 p
6886 }
6887 Shape::Polygon(pts) => {
6888 if pts.len() < 2 {
6889 return None;
6890 }
6891 let p = NSBezierPath::new();
6892 p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6893 for pt in &pts[1..] {
6894 p.lineToPoint(NSPoint::new(pt.x, pt.y));
6895 }
6896 p.closePath();
6897 p
6898 }
6899 Shape::Path(path) => {
6900 use day_spec::PathSeg;
6901 if path.segs.is_empty() {
6902 return None;
6903 }
6904 let p = NSBezierPath::new();
6905 let mut cur = NSPoint::new(0.0, 0.0);
6909 for seg in &path.segs {
6910 match seg {
6911 PathSeg::Move(a) => {
6912 cur = NSPoint::new(a.x, a.y);
6913 p.moveToPoint(cur);
6914 }
6915 PathSeg::Line(a) => {
6916 cur = NSPoint::new(a.x, a.y);
6917 p.lineToPoint(cur);
6918 }
6919 PathSeg::Quad(c, a) => {
6920 let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6921 let c1 = NSPoint::new(
6922 cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6923 cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6924 );
6925 let c2 = NSPoint::new(
6926 end.x + 2.0 / 3.0 * (ctl.x - end.x),
6927 end.y + 2.0 / 3.0 * (ctl.y - end.y),
6928 );
6929 p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6930 cur = end;
6931 }
6932 PathSeg::Cubic(c1, c2, a) => {
6933 cur = NSPoint::new(a.x, a.y);
6934 p.curveToPoint_controlPoint1_controlPoint2(
6935 cur,
6936 NSPoint::new(c1.x, c1.y),
6937 NSPoint::new(c2.x, c2.y),
6938 );
6939 }
6940 PathSeg::Close => p.closePath(),
6941 }
6942 }
6943 p.setWindingRule(match path.rule {
6944 day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6945 day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6946 });
6947 p
6948 }
6949 })
6950 }
6951}
6952
6953struct UndoIvars {
6961 state: std::cell::RefCell<day_spec::UndoState>,
6962}
6963
6964define_class!(
6965 #[unsafe(super(objc2_foundation::NSUndoManager))]
6966 #[thread_kind = MainThreadOnly]
6967 #[name = "DayUndoManager"]
6968 #[ivars = UndoIvars]
6969 struct DayUndoManager;
6970
6971 impl DayUndoManager {
6975 #[unsafe(method(canUndo))]
6976 fn can_undo(&self) -> bool {
6977 self.ivars().state.borrow().can_undo
6978 }
6979
6980 #[unsafe(method(canRedo))]
6981 fn can_redo(&self) -> bool {
6982 self.ivars().state.borrow().can_redo
6983 }
6984
6985 #[unsafe(method(undo))]
6986 fn do_undo(&self) {
6987 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6988 }
6989
6990 #[unsafe(method(redo))]
6991 fn do_redo(&self) {
6992 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6993 }
6994
6995 #[unsafe(method_id(undoMenuItemTitle))]
6996 fn undo_menu_item_title(&self) -> Retained<NSString> {
6997 let label = self.ivars().state.borrow().undo_label.clone();
7000 unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7001 }
7002
7003 #[unsafe(method_id(redoMenuItemTitle))]
7004 fn redo_menu_item_title(&self) -> Retained<NSString> {
7005 let label = self.ivars().state.borrow().redo_label.clone();
7006 unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7007 }
7008 }
7009);
7010
7011fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
7012 UNDO_FRONT.with(|u| {
7013 u.borrow_mut()
7014 .get_or_insert_with(|| {
7015 let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
7016 state: std::cell::RefCell::new(day_spec::UndoState::default()),
7017 });
7018 unsafe { msg_send![super(this), init] }
7019 })
7020 .clone()
7021 })
7022}
7023
7024struct WinIvars {
7032 node: Option<NodeId>,
7033 group: Option<String>,
7036 last_state: Cell<i32>,
7039}
7040
7041define_class!(
7042 #[unsafe(super(NSObject))]
7043 #[thread_kind = MainThreadOnly]
7044 #[name = "DayWinDelegate"]
7045 #[ivars = WinIvars]
7046 struct DayWinDelegate;
7047
7048 unsafe impl NSObjectProtocol for DayWinDelegate {}
7049
7050 impl DayWinDelegate {
7054 #[unsafe(method(undo:))]
7058 fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7059 ffi_guard::contain((), || {
7060 if let Some(m) = self.acting_undo_manager() {
7061 unsafe { m.undo() };
7062 }
7063 });
7064 }
7065
7066 #[unsafe(method(redo:))]
7068 fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7069 ffi_guard::contain((), || {
7070 if let Some(m) = self.acting_undo_manager() {
7071 unsafe { m.redo() };
7072 }
7073 });
7074 }
7075
7076 #[unsafe(method(cut:))]
7077 fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7078 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
7079 }
7080
7081 #[unsafe(method(copy:))]
7082 fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7083 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
7084 }
7085
7086 #[unsafe(method(paste:))]
7087 fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7088 ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
7089 }
7090
7091 #[unsafe(method(selectAll:))]
7092 fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7093 ffi_guard::contain((), || {
7094 emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
7095 });
7096 }
7097
7098 #[unsafe(method(validateMenuItem:))]
7102 fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
7103 ffi_guard::contain(false, || {
7104 let state = EDIT_STATE.with(|s| s.get());
7105 match unsafe { item.action() } {
7106 Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
7109 Some(m) => {
7110 item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
7111 unsafe { m.canUndo() }
7112 }
7113 None => false,
7114 },
7115 Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
7116 Some(m) => {
7117 item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
7118 unsafe { m.canRedo() }
7119 }
7120 None => false,
7121 },
7122 Some(a) if a == sel!(selectAll:) => state.can_select_all,
7123 Some(a) if a == sel!(cut:) => state.can_cut,
7124 Some(a) if a == sel!(copy:) => state.can_copy,
7125 Some(a) if a == sel!(paste:) => {
7126 state.can_paste && {
7127 let pb = unsafe { NSPasteboard::generalPasteboard() };
7128 pb.types().is_some_and(|types| !types.is_empty())
7129 }
7130 }
7131 _ => true,
7132 }
7133 })
7134 }
7135 }
7136
7137 unsafe impl NSWindowDelegate for DayWinDelegate {
7138 #[unsafe(method(windowDidResize:))]
7139 fn window_did_resize(&self, notification: &NSNotification) {
7140 ffi_guard::contain((), || {
7141 if let Some(obj) = unsafe { notification.object() }
7142 && let Ok(win) = obj.downcast::<NSWindow>()
7143 && let Some(size) = pin_below_title_bar(&win)
7144 {
7145 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7146 emit(target, Event::WindowResized(size));
7147 }
7148 self.report_state_of(notification);
7150 })
7151 }
7152
7153 #[unsafe(method(windowShouldClose:))]
7154 fn window_should_close(&self, _window: &NSWindow) -> bool {
7155 ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
7156 }
7157
7158 #[unsafe(method(windowWillClose:))]
7159 fn window_will_close(&self, _notification: &NSNotification) {
7160 ffi_guard::contain((), || {
7161 match self.ivars().node {
7162 Some(node) => emit(node, Event::WindowClosed),
7165 None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
7170 None => {
7171 let app = NSApplication::sharedApplication(self.mtm());
7172 unsafe { app.terminate(None) };
7173 }
7174 }
7175 })
7176 }
7177
7178 #[unsafe(method_id(windowWillReturnUndoManager:))]
7179 fn window_will_return_undo_manager(
7180 &self,
7181 _window: &NSWindow,
7182 ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7183 ffi_guard::contain(None, || {
7187 UNDO_FRONT.with(|u| {
7188 u.borrow()
7189 .as_ref()
7190 .map(|m| Retained::into_super(m.clone()))
7191 })
7192 })
7193 }
7194
7195 #[unsafe(method(windowDidBecomeKey:))]
7196 fn window_did_become_key(&self, _notification: &NSNotification) {
7197 ffi_guard::contain((), || {
7198 if let Some(node) = self.ivars().node {
7199 emit(node, Event::WindowFocused(true));
7200 }
7201 })
7202 }
7203
7204 #[unsafe(method(windowDidResignKey:))]
7205 fn window_did_resign_key(&self, _notification: &NSNotification) {
7206 ffi_guard::contain((), || {
7207 if let Some(node) = self.ivars().node {
7208 emit(node, Event::WindowFocused(false));
7209 }
7210 })
7211 }
7212
7213 #[unsafe(method(windowDidMiniaturize:))]
7214 fn window_did_miniaturize(&self, notification: &NSNotification) {
7215 ffi_guard::contain((), || self.report_state_of(notification))
7216 }
7217
7218 #[unsafe(method(windowDidDeminiaturize:))]
7219 fn window_did_deminiaturize(&self, notification: &NSNotification) {
7220 ffi_guard::contain((), || self.report_state_of(notification))
7221 }
7222
7223 #[unsafe(method(windowDidEnterFullScreen:))]
7224 fn window_did_enter_full_screen(&self, notification: &NSNotification) {
7225 ffi_guard::contain((), || self.report_state_of(notification))
7226 }
7227
7228 #[unsafe(method(windowDidExitFullScreen:))]
7229 fn window_did_exit_full_screen(&self, notification: &NSNotification) {
7230 ffi_guard::contain((), || self.report_state_of(notification))
7231 }
7232 }
7233
7234 impl DayWinDelegate {
7238 #[unsafe(method(newWindowForTab:))]
7239 fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
7240 ffi_guard::contain((), || {
7241 let _ = match self.ivars().group.as_deref() {
7244 Some(group) => day_core::windows::open_new_window_for_group(group),
7245 None => day_core::windows::open_new_window(),
7246 };
7247 })
7248 }
7249 }
7250);
7251
7252impl DayWinDelegate {
7253 fn report_state_of(&self, notification: &NSNotification) {
7254 if let Some(obj) = unsafe { notification.object() }
7255 && let Ok(win) = obj.downcast::<NSWindow>()
7256 {
7257 self.report_state(&win);
7258 }
7259 }
7260}
7261
7262fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7265 match unsafe { event.keyCode() } {
7266 123 => Some("ArrowLeft"),
7267 124 => Some("ArrowRight"),
7268 125 => Some("ArrowDown"),
7269 126 => Some("ArrowUp"),
7270 _ => {
7278 let held = NSEventModifierFlags::Command
7279 | NSEventModifierFlags::Option
7280 | NSEventModifierFlags::Control;
7281 if event.modifierFlags().intersects(held) {
7282 return None;
7283 }
7284 let typed = event.characters()?.to_string();
7285 let mut chars = typed.chars();
7286 match (chars.next(), chars.next()) {
7287 (Some(c), None) => day_spec::KeyEvent::digit_name(c),
7288 _ => None,
7289 }
7290 }
7291 }
7292}
7293
7294fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7297 Some(match unsafe { event.keyCode() } {
7298 123 => "ArrowLeft",
7299 124 => "ArrowRight",
7300 125 => "ArrowDown",
7301 126 => "ArrowUp",
7302 36 | 76 => "Enter",
7303 48 => "Tab",
7304 53 => "Escape",
7305 51 => "Backspace",
7306 117 => "Delete",
7307 115 => "Home",
7308 119 => "End",
7309 116 => "PageUp",
7310 121 => "PageDown",
7311 114 => "Insert",
7312 122 => "F1",
7313 120 => "F2",
7314 99 => "F3",
7315 118 => "F4",
7316 96 => "F5",
7317 97 => "F6",
7318 98 => "F7",
7319 100 => "F8",
7320 101 => "F9",
7321 109 => "F10",
7322 103 => "F11",
7323 111 => "F12",
7324 _ => return None,
7325 })
7326}
7327
7328fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
7339 let ptr = (view as *const DayCanvas).cast::<NSView>() as usize;
7340 let flags = event.modifierFlags();
7341 let mods = key_modifiers(flags);
7342 if flags.contains(NSEventModifierFlags::Command) {
7343 return false;
7344 }
7345 let composing = MARKED.with(|t| t.contains(ptr));
7346 if !composing && let Some(named) = named_key(event) {
7347 emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
7348 return true;
7349 }
7350 let unmodified = unsafe { event.charactersIgnoringModifiers() }
7351 .map(|s| s.to_string())
7352 .unwrap_or_default();
7353 let typeable = !unmodified.is_empty()
7355 && !unmodified
7356 .chars()
7357 .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
7358 if !composing && flags.contains(NSEventModifierFlags::Control) {
7359 if typeable {
7360 emit(
7361 node,
7362 Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
7363 );
7364 }
7365 return true;
7366 }
7367 if !composing && !typeable {
7368 return true;
7369 }
7370 INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
7371 view.interpretKeyEvents(&NSArray::from_slice(&[event]));
7372 INTERPRETING.with(|i| *i.borrow_mut() = None);
7373 true
7374}
7375
7376fn text_of_input_string(string: &AnyObject) -> String {
7378 if let Some(s) = string.downcast_ref::<NSString>() {
7379 s.to_string()
7380 } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
7381 s.string().to_string()
7382 } else {
7383 String::new()
7384 }
7385}
7386
7387fn key_modifiers(f: NSEventModifierFlags) -> u8 {
7389 let mut modifiers = 0u8;
7390 if f.contains(NSEventModifierFlags::Shift) {
7391 modifiers |= day_spec::KeyEvent::SHIFT;
7392 }
7393 if f.contains(NSEventModifierFlags::Command) {
7394 modifiers |= day_spec::KeyEvent::PRIMARY;
7395 }
7396 if f.contains(NSEventModifierFlags::Option) {
7397 modifiers |= day_spec::KeyEvent::ALT;
7398 }
7399 if f.contains(NSEventModifierFlags::Control) {
7400 modifiers |= day_spec::KeyEvent::CONTROL;
7401 }
7402 modifiers
7403}
7404
7405impl DayWinDelegate {
7406 fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7411 let responder = NSApplication::sharedApplication(self.mtm())
7412 .keyWindow()
7413 .and_then(|w| w.firstResponder());
7414 responder
7415 .and_then(|r| unsafe { r.undoManager() })
7416 .or_else(|| {
7417 UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
7418 })
7419 }
7420}
7421
7422impl DayWinDelegate {
7423 fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
7424 let this = Self::alloc(mtm).set_ivars(WinIvars {
7425 node,
7426 group,
7427 last_state: Cell::new(day_spec::WindowState::Normal.code()),
7428 });
7429 unsafe { msg_send![super(this), init] }
7430 }
7431
7432 fn report_state(&self, window: &NSWindow) {
7436 let state = ns_window_state(window);
7437 if self.ivars().last_state.replace(state.code()) != state.code() {
7438 log::debug!("appkit: window state now {state:?}");
7439 let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7440 emit(target, Event::WindowStateChanged(state));
7441 }
7442 }
7443}
7444
7445fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
7448 if window.isMiniaturized() {
7449 day_spec::WindowState::Minimized
7450 } else if window
7451 .styleMask()
7452 .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
7453 {
7454 day_spec::WindowState::Fullscreen
7455 } else if window.isZoomed() {
7456 day_spec::WindowState::Maximized
7457 } else {
7458 day_spec::WindowState::Normal
7459 }
7460}
7461
7462fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
7465 use day_spec::WindowState as S;
7466 let current = ns_window_state(window);
7467 if current == state {
7468 return;
7469 }
7470 unsafe {
7471 match current {
7472 S::Minimized => window.deminiaturize(None),
7473 S::Fullscreen => {
7477 window.toggleFullScreen(None);
7478 return;
7479 }
7480 S::Maximized if state != S::Minimized => window.zoom(None),
7481 _ => {}
7482 }
7483 match state {
7484 S::Normal => {}
7485 S::Minimized => window.miniaturize(None),
7486 S::Maximized => {
7487 if !window.isZoomed() {
7488 window.zoom(None)
7489 }
7490 }
7491 S::Fullscreen => window.toggleFullScreen(None),
7492 }
7493 }
7494}
7495
7496#[distributed_slice]
7502pub static RENDERERS: [fn() -> Renderer<AppKit>];
7503
7504struct SecondaryWin {
7508 window: Retained<NSWindow>,
7509 #[allow(dead_code)] delegate: Retained<DayWinDelegate>,
7511 content: Handle,
7512}
7513
7514struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
7517impl Drop for MenuEscapeMonitor {
7518 fn drop(&mut self) {
7519 unsafe { NSEvent::removeMonitor(&self.0) };
7520 }
7521}
7522
7523pub struct AppKit {
7524 menu_escape_monitor: Option<MenuEscapeMonitor>,
7525 sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
7526 sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
7528
7529 mtm: MainThreadMarker,
7530 registry: Registry<AppKit>,
7531 window: Option<Retained<NSWindow>>,
7532 content: Option<Handle>,
7533 secondary: Vec<SecondaryWin>,
7534 app_name: String,
7535 cascade: Option<NSPoint>,
7540 cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7543}
7544
7545impl AppKit {
7546 fn swap_text_field(
7551 &mut self,
7552 h: &Handle,
7553 old: &NSTextField,
7554 node: NodeId,
7555 secure: bool,
7556 ) -> Retained<NSTextField> {
7557 let new = new_text_field(self.mtm, node, secure);
7558 let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7559 let window = h.window();
7562 let focused = window
7563 .as_deref()
7564 .is_some_and(|w| owns_first_responder(w, h));
7565 let selection = old.currentEditor().map(|e| e.selectedRange());
7566 unsafe {
7567 new.setStringValue(&old.stringValue());
7568 new.setPlaceholderString(old.placeholderString().as_deref());
7569 new.setEnabled(old.isEnabled());
7570 new.setFont(old.font().as_deref());
7571 new.setFrame(h.frame());
7572 new.setHidden(h.isHidden());
7573 new.setMenu(h.menu().as_deref());
7574 new.setToolTip(h.toolTip().as_deref());
7575 if h.wantsLayer() {
7577 new.setWantsLayer(true);
7578 new.setAlphaValue(h.alphaValue());
7579 let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7580 let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7581 if !from.is_null() && !to.is_null() {
7582 let t: CGAffineTransform = msg_send![from, affineTransform];
7583 let _: () = msg_send![to, setAffineTransform: t];
7584 }
7585 }
7586 if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7589 new.setAccessibilityIdentifier(Some(&id));
7590 }
7591 if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7592 new.setAccessibilityLabel(Some(&label));
7593 }
7594 if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7595 new.setAccessibilityHelp(Some(&help));
7596 }
7597 if !h.isAccessibilityElement() {
7598 new.setAccessibilityElement(false);
7599 }
7600 }
7601 for r in unsafe { h.gestureRecognizers() }.iter() {
7603 unsafe {
7604 h.removeGestureRecognizer(&r);
7605 new.addGestureRecognizer(&r);
7606 }
7607 }
7608 GESTURES.with(|m| {
7609 let mut m = m.borrow_mut();
7610 if let Some(targets) = m.remove(&old_key) {
7611 m.insert(new_key, targets);
7612 }
7613 });
7614 if let Some((owner, area)) = self.cursors.remove(&old_key) {
7615 unsafe {
7616 h.removeTrackingArea(&area);
7617 new.addTrackingArea(&area);
7618 }
7619 self.cursors.insert(new_key, (owner, area));
7620 }
7621 PAN_NODES.with(|t| rekey(t, old_key, new_key));
7622 HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7623 ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
7624 ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
7625 KEY_NODES.with(|t| rekey(t, old_key, new_key));
7626 FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7627 CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7628 transfer::moved(h, &new);
7629 unsafe { old.setDelegate(None) };
7632 TARGETS.with(|m| {
7633 m.borrow_mut().remove(&old_key);
7634 });
7635 if let Some(parent) = unsafe { h.superview() } {
7636 unsafe {
7637 parent.addSubview_positioned_relativeTo(
7638 &new,
7639 objc2_app_kit::NSWindowOrderingMode::Above,
7640 Some(h),
7641 );
7642 h.removeFromSuperview();
7643 }
7644 }
7645 if focused && let Some(window) = window {
7646 FIELD_SWAP.with(|s| s.set(true));
7647 let taken = window.makeFirstResponder(Some(&new));
7648 FIELD_SWAP.with(|s| s.set(false));
7649 if taken && let Some(editor) = new.currentEditor() {
7652 let len = unsafe { new.stringValue() }.length();
7653 let range = selection
7654 .filter(|r| r.location.saturating_add(r.length) <= len)
7655 .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7656 editor.setSelectedRange(range);
7657 }
7658 }
7659 day_spec::sidetable::sweep(old_key);
7661 new
7662 }
7663
7664 pub fn new() -> Self {
7665 let mtm =
7666 MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7667 let mut registry = Registry::default();
7668 for f in RENDERERS {
7669 registry.register(f());
7670 }
7671 AppKit {
7672 menu_escape_monitor: None,
7673 mtm,
7674 registry,
7675 window: None,
7676 sharing: None,
7677 sharing_delegate: None,
7678 content: None,
7679 secondary: Vec::new(),
7680 app_name: "Day".into(),
7681 cascade: None,
7682 cursors: HashMap::new(),
7683 }
7684 }
7685
7686 pub fn mtm(&self) -> MainThreadMarker {
7688 self.mtm
7689 }
7690
7691 fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
7700 if content.window().is_none_or(|w| w.isVisible()) {
7701 return None;
7702 }
7703 let main = NSApplication::sharedApplication(self.mtm).mainWindow();
7704 let anchor = main
7705 .filter(|m| {
7706 self.secondary
7707 .iter()
7708 .any(|w| std::ptr::eq(&*w.window, &**m))
7709 })
7710 .or_else(|| {
7711 self.secondary
7712 .iter()
7713 .find(|w| w.window.isVisible())
7714 .map(|w| w.window.clone())
7715 })?;
7716 let shown = anchor
7717 .tabGroup()
7718 .and_then(|g| g.selectedWindow())
7719 .unwrap_or(anchor);
7720 self.secondary
7721 .iter()
7722 .find(|w| std::ptr::eq(&*w.window, &*shown) && w.window.isVisible())
7723 .map(|w| w.content.clone())
7724 }
7725
7726 fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7727 if let Some(w) = self
7728 .secondary
7729 .iter()
7730 .find(|w| ptr_of(&w.content) == ptr_of(host))
7731 {
7732 return Some(w.window.clone());
7733 }
7734 self.content
7735 .as_ref()
7736 .filter(|c| ptr_of(c) == ptr_of(host))
7737 .and(self.window.clone())
7738 }
7739
7740 fn make_window(
7746 &self,
7747 options: &WindowOptions,
7748 prefs_style: bool,
7749 node: Option<NodeId>,
7750 ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7751 let mtm = self.mtm;
7752 let (title, size, min_size, tabbing) = (
7753 options.title.as_str(),
7754 options.size,
7755 options.min_size,
7756 &options.tabbing,
7757 );
7758 let content_rect =
7759 NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7760 let style = window_chrome::style_mask(options, prefs_style);
7762 let window = window_chrome::alloc_window(
7763 mtm,
7764 content_rect,
7765 style,
7766 options.chrome == day_spec::WindowChrome::Frameless,
7767 );
7768 unsafe { window.setReleasedWhenClosed(false) };
7769 window.setTitle(&NSString::from_str(title));
7770 if let Some(min) = min_size {
7771 unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7772 }
7773 if let Some(max) = options.max_size {
7774 unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7775 }
7776 use day_spec::WindowTabbing as T;
7777 use objc2_app_kit::NSWindowTabbingMode as M;
7778 let group = match tabbing {
7779 T::Group(g) | T::Preferred(g) => Some(g.clone()),
7780 T::Automatic | T::Disallowed => None,
7781 };
7782 match tabbing {
7783 _ if prefs_style => window.setTabbingMode(M::Disallowed),
7784 T::Disallowed => window.setTabbingMode(M::Disallowed),
7785 T::Automatic => unsafe {
7789 window.setTabbingIdentifier(&NSString::from_str("day.normal"))
7790 },
7791 T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7792 T::Preferred(g) => {
7793 unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7794 window.setTabbingMode(M::Preferred);
7795 }
7796 }
7797 if group.is_some() {
7798 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7801 }
7802 let delegate = DayWinDelegate::new(mtm, node, group);
7803 window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7804 let content = view_of(DayFlipped::new(mtm));
7805 window.setContentView(Some(&content));
7806 window_chrome::apply(&window, &content, options);
7807 window.setAutorecalculatesKeyViewLoop(true);
7816 (window, delegate, content)
7817 }
7818}
7819
7820impl Default for AppKit {
7821 fn default() -> Self {
7822 Self::new()
7823 }
7824}
7825
7826fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7827 Retained::from(x.as_ref())
7828}
7829
7830fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7831 unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7832}
7833
7834fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7837 use objc2_app_kit::*;
7838 unsafe {
7839 Some(match f {
7840 Font::LargeTitle => NSFontTextStyleLargeTitle,
7841 Font::Title => NSFontTextStyleTitle1,
7842 Font::Title2 => NSFontTextStyleTitle2,
7843 Font::Title3 => NSFontTextStyleTitle3,
7844 Font::Headline => NSFontTextStyleHeadline,
7845 Font::Subheadline => NSFontTextStyleSubheadline,
7846 Font::Body => NSFontTextStyleBody,
7847 Font::Callout => NSFontTextStyleCallout,
7848 Font::Footnote => NSFontTextStyleFootnote,
7849 Font::Caption => NSFontTextStyleCaption1,
7850 Font::Caption2 => NSFontTextStyleCaption2,
7851 Font::System(_) | Font::Custom(..) => return None,
7852 })
7853 }
7854}
7855
7856fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7857 use day_spec::FontWeight as W;
7858 use objc2_app_kit::*;
7859 unsafe {
7860 match w {
7861 W::UltraLight => NSFontWeightUltraLight,
7862 W::Thin => NSFontWeightThin,
7863 W::Light => NSFontWeightLight,
7864 W::Regular => NSFontWeightRegular,
7865 W::Medium => NSFontWeightMedium,
7866 W::Semibold => NSFontWeightSemibold,
7867 W::Bold => NSFontWeightBold,
7868 W::Heavy => NSFontWeightHeavy,
7869 W::Black => NSFontWeightBlack,
7870 }
7871 }
7872}
7873
7874fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7877 use day_spec::FontWeight as W;
7878 match w {
7879 W::UltraLight => 2,
7880 W::Thin => 3,
7881 W::Light => 4,
7882 W::Regular => 5,
7883 W::Medium => 6,
7884 W::Semibold => 8,
7885 W::Bold => 9,
7886 W::Heavy => 10,
7887 W::Black => 12,
7888 }
7889}
7890
7891fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7896 use objc2_app_kit::*;
7897 let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7898 let prepared = OFFSCREEN_FONTS.with(|t| {
7901 t.borrow()
7902 .iter()
7903 .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
7904 .map(|(_, f)| f.clone())
7905 });
7906 if let Some(f) = prepared {
7907 return f;
7908 }
7909 let Some(mtm) = objc2::MainThreadMarker::new() else {
7910 return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7914 };
7915 let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7916 let mut traits = NSFontTraitMask::empty();
7917 if weight >= day_spec::FontWeight::Semibold {
7918 traits |= NSFontTraitMask::BoldFontMask;
7919 }
7920 if font.italic {
7921 traits |= NSFontTraitMask::ItalicFontMask;
7922 }
7923 let Some(family) = font.family.as_deref() else {
7924 let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7925 return if font.italic {
7926 unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7927 } else {
7928 base
7929 };
7930 };
7931 let ns_family = NSString::from_str(family);
7932 if let Some(f) = unsafe {
7933 manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7934 } {
7935 return f;
7936 }
7937 if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7938 return if traits.is_empty() {
7939 f
7940 } else {
7941 unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7942 };
7943 }
7944 log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7945 unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7946}
7947
7948fn canvas_text_attrs(
7951 font: &NSFont,
7952 color: day_spec::Color,
7953) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7954 let col = nscolor(color);
7955 let keys: [&NSString; 2] = unsafe {
7957 [
7958 objc2_app_kit::NSFontAttributeName,
7959 objc2_app_kit::NSForegroundColorAttributeName,
7960 ]
7961 };
7962 let objs: [&objc2::runtime::AnyObject; 2] = [
7963 font as &objc2::runtime::AnyObject,
7964 col.as_ref() as &objc2::runtime::AnyObject,
7965 ];
7966 objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7967}
7968
7969fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7972 use objc2_app_kit::*;
7973 let base: Retained<NSFont> = match spec.style {
7974 Font::System(pt) => {
7975 let w = spec
7976 .weight
7977 .map(ns_weight)
7978 .unwrap_or(unsafe { NSFontWeightRegular });
7979 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7980 }
7981 Font::Custom(name, pt) => {
7985 match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7986 Some(f) => {
7987 if spec
7988 .weight
7989 .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7990 {
7991 let mtm = objc2::MainThreadMarker::new()
7992 .expect("labels realize on the main thread");
7993 unsafe {
7994 NSFontManager::sharedFontManager(mtm)
7995 .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7996 }
7997 } else {
7998 f
7999 }
8000 }
8001 None => {
8002 log::warn!(
8003 "unknown font family {name:?} — falling back to the system font \
8004 (is the file in the project's fonts/ directory?)"
8005 );
8006 let w = spec
8007 .weight
8008 .map(ns_weight)
8009 .unwrap_or(unsafe { NSFontWeightRegular });
8010 unsafe { NSFont::systemFontOfSize_weight(pt, w) }
8011 }
8012 }
8013 }
8014 style => {
8015 let ts = ns_text_style(style).expect("semantic style");
8018 let opts = objc2_foundation::NSDictionary::new();
8019 let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
8020 match spec.weight {
8021 Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
8023 None => f,
8024 }
8025 }
8026 };
8027 let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
8032 let w = spec
8033 .weight
8034 .map(ns_weight)
8035 .unwrap_or(unsafe { NSFontWeightRegular });
8036 unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
8037 } else {
8038 base
8039 };
8040 let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
8044 let w = spec
8045 .weight
8046 .map(ns_weight)
8047 .unwrap_or(unsafe { NSFontWeightRegular });
8048 unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
8049 } else {
8050 base
8051 };
8052 let base = if spec.scale != 1.0 {
8056 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8057 let pts = spec.resolved_points(base.pointSize());
8058 unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
8059 } else {
8060 base
8061 };
8062 if spec.italic {
8063 let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8064 unsafe {
8065 NSFontManager::sharedFontManager(mtm)
8066 .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
8067 }
8068 } else {
8069 base
8070 }
8071}
8072
8073fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
8083 use objc2_foundation::{NSMutableAttributedString, NSRange};
8084 unsafe {
8085 let cur = tf.attributedStringValue();
8086 let m = NSMutableAttributedString::initWithAttributedString(
8087 NSMutableAttributedString::alloc(),
8088 &cur,
8089 );
8090 let style = objc2_app_kit::NSMutableParagraphStyle::new();
8091 style.setAlignment(align);
8092 style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
8095 m.addAttribute_value_range(
8096 objc2_app_kit::NSParagraphStyleAttributeName,
8097 &style,
8098 NSRange::new(0, cur.length()),
8099 );
8100 tf.setAttributedStringValue(&m);
8101 }
8102}
8103
8104fn attributed_label(
8105 text: &str,
8106 base_font: &NSFont,
8107 color: Option<day_spec::Color>,
8108 role: day_spec::props::TextRole,
8109 runs: &[day_spec::TextRun],
8110) -> Retained<objc2_foundation::NSAttributedString> {
8111 use objc2_foundation::{NSMutableAttributedString, NSRange};
8112 let ns = NSString::from_str(text);
8113 let s = unsafe {
8114 NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
8115 };
8116 let whole = NSRange::new(0, ns.length());
8117 unsafe {
8118 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
8119 let fg = color.map(nscolor).unwrap_or_else(|| match role {
8127 day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
8128 day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
8129 });
8130 s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
8131 }
8132 for r in runs {
8133 let Some(range) = utf16_range(text, &r.range) else {
8134 continue;
8135 };
8136 unsafe {
8137 s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
8138 if let Some(c) = r.color {
8139 s.addAttribute_value_range(
8140 objc2_app_kit::NSForegroundColorAttributeName,
8141 &nscolor(c),
8142 range,
8143 );
8144 }
8145 if let Some(c) = r.background {
8146 s.addAttribute_value_range(
8147 objc2_app_kit::NSBackgroundColorAttributeName,
8148 &nscolor(c),
8149 range,
8150 );
8151 }
8152 if r.underline.is_on() {
8153 let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
8154 s.addAttribute_value_range(
8155 objc2_app_kit::NSUnderlineStyleAttributeName,
8156 &style,
8157 range,
8158 );
8159 }
8160 if r.strikethrough {
8161 let one = objc2_foundation::NSNumber::new_i64(1);
8162 s.addAttribute_value_range(
8163 objc2_app_kit::NSStrikethroughStyleAttributeName,
8164 &one,
8165 range,
8166 );
8167 }
8168 if let Some(url) = r.link.as_deref() {
8169 let value = NSString::from_str(url);
8172 s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
8173 }
8174 }
8175 }
8176 s.into_super()
8177}
8178
8179fn ns_underline(u: day_spec::Underline) -> i64 {
8183 use day_spec::Underline as U;
8184 match u {
8185 U::None => 0,
8186 U::Single => 0x01,
8187 U::Double => 0x09,
8188 U::Dotted => 0x01 | 0x0100,
8189 U::Wavy => 0x01 | 0x0400,
8190 }
8191}
8192
8193fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
8195 let start = text.get(..r.start)?.encode_utf16().count();
8196 let len = text.get(r.clone())?.encode_utf16().count();
8197 Some(objc2_foundation::NSRange::new(start, len))
8198}
8199
8200fn register_bundled_fonts() {
8205 #[link(name = "CoreText", kind = "framework")]
8207 unsafe extern "C" {
8208 fn CTFontManagerRegisterFontsForURL(
8209 font_url: *const std::ffi::c_void,
8210 scope: u32, error: *mut *const std::ffi::c_void,
8212 ) -> bool;
8213 }
8214 for path in day_spec::fonts::bundled_fonts() {
8215 let url = unsafe {
8216 objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
8217 };
8218 let ok = unsafe {
8219 CTFontManagerRegisterFontsForURL(
8220 Retained::as_ptr(&url) as *const std::ffi::c_void,
8221 1,
8222 std::ptr::null_mut(),
8223 )
8224 };
8225 if !ok {
8226 log::warn!("could not register bundled font {}", path.display());
8227 }
8228 }
8229}
8230
8231fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
8234 match a {
8235 day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
8236 day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
8237 day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
8238 }
8239}
8240
8241fn configure_label_cell(tf: &NSTextField) {
8242 if let Some(cell) = unsafe { tf.cell() } {
8243 unsafe {
8244 cell.setWraps(true);
8245 cell.setUsesSingleLineMode(false);
8246 cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
8247 }
8248 }
8249}
8250
8251fn content_of(parent: &Handle) -> Retained<NSView> {
8253 if let Some(sv) = parent.downcast_ref::<NSScrollView>()
8254 && let Some(doc) = unsafe { sv.documentView() }
8255 {
8256 return doc;
8257 }
8258 parent.clone()
8259}
8260
8261fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
8267 let Some(a) = anim else {
8268 body();
8269 return;
8270 };
8271 let (dur, timing) = appkit_timing(a);
8272 unsafe {
8273 NSAnimationContext::beginGrouping();
8274 let ctx = NSAnimationContext::currentContext();
8275 ctx.setDuration(dur);
8276 ctx.setTimingFunction(Some(&timing));
8277 ctx.setAllowsImplicitAnimation(true);
8278 body();
8279 NSAnimationContext::endGrouping();
8280 }
8281}
8282
8283fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
8286 unsafe {
8287 let named = |n| {
8288 (
8289 a.duration_secs().max(0.01),
8290 CAMediaTimingFunction::functionWithName(n),
8291 )
8292 };
8293 match a.curve {
8294 Curve::Linear => named(kCAMediaTimingFunctionLinear),
8295 Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
8296 Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
8297 Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
8298 Curve::Spring { damping, .. } => {
8299 let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
8301 (
8302 a.duration_secs().max(0.05),
8303 CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
8304 )
8305 }
8306 }
8307 }
8308}
8309
8310fn warn_missing_renderer(kind: PieceKind) {
8315 day_spec::placeholder::report(kind, "appkit");
8316}
8317
8318pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
8322 view_of(unsafe {
8323 NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
8324 })
8325}
8326
8327impl Toolkit for AppKit {
8328 fn ui_idle(&mut self) -> bool {
8331 toolbar::chrome_settled()
8332 }
8333
8334 type Handle = Handle;
8335
8336 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
8337 use day_spec::SystemColor;
8338 let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
8339 let block = block2::StackBlock::new(|| {
8340 let color = match role {
8341 SystemColor::Accent => NSColor::controlAccentColor(),
8342 SystemColor::Text => NSColor::labelColor(),
8343 SystemColor::SecondaryText => NSColor::secondaryLabelColor(),
8344 SystemColor::Background => NSColor::windowBackgroundColor(),
8345 SystemColor::Surface => NSColor::controlBackgroundColor(),
8346 };
8347 if let Some(rgb) =
8348 color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())
8349 {
8350 result.set(day_spec::Color::rgba(
8351 rgb.redComponent(),
8352 rgb.greenComponent(),
8353 rgb.blueComponent(),
8354 rgb.alphaComponent(),
8355 ));
8356 }
8357 });
8358 NSApplication::sharedApplication(self.mtm())
8359 .effectiveAppearance()
8360 .performAsCurrentDrawingAppearance(&block);
8361 result.get()
8362 }
8363
8364 fn dark_mode(&mut self) -> bool {
8365 let app = NSApplication::sharedApplication(self.mtm());
8368 app.effectiveAppearance()
8369 .name()
8370 .to_string()
8371 .contains("Dark")
8372 }
8373
8374 fn reduce_motion(&mut self) -> bool {
8377 objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
8378 }
8379
8380 fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
8384 use day_spec::AppBadge;
8385 let label = match badge {
8386 AppBadge::None => None,
8387 AppBadge::Count(0) => None,
8389 AppBadge::Count(n) => Some(n.to_string()),
8390 AppBadge::Text(t) if t.is_empty() => None,
8391 AppBadge::Text(t) => Some(t.clone()),
8392 AppBadge::Dot => Some("\u{2022}".to_string()),
8394 };
8395 let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
8396 let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
8397 unsafe { tile.setBadgeLabel(ns.as_deref()) };
8398 tile.display();
8399 }
8400
8401 fn set_appearance(&mut self, dark: Option<bool>) {
8402 let app = NSApplication::sharedApplication(self.mtm());
8403 let appearance = dark.and_then(|d| {
8404 objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
8405 if d {
8406 objc2_app_kit::NSAppearanceNameDarkAqua
8407 } else {
8408 objc2_app_kit::NSAppearanceNameAqua
8409 }
8410 })
8411 });
8412 unsafe { app.setAppearance(appearance.as_deref()) };
8414 }
8415
8416 fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
8417 controls::refresh_gesture::attach(handle, host);
8418 }
8419
8420 fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
8421 unsafe {
8422 handle.setHidden(!visible);
8423 }
8424 }
8425
8426 fn capability(&self, cap: Cap) -> Support {
8427 match cap {
8428 Cap::ShareActions => Support::Native,
8430 Cap::SearchField => Support::Native,
8431 Cap::ComboBox => Support::Native,
8432 Cap::Stepper => Support::Native,
8433 Cap::DateTimePicker => Support::Native,
8434 Cap::ColorPicker => Support::Native,
8435 Cap::PullRefresh => Support::Emulated,
8436 Cap::Pager => Support::Emulated,
8437 Cap::PullRefreshGesture => Support::Emulated,
8438 Cap::Cursor => Support::Native,
8442 Cap::FontList => Support::Native,
8444 Cap::ListItem => Support::Native,
8446 Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
8450 Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
8453 Cap::Announce => Support::Native,
8456 Cap::ReduceMotion => Support::Native,
8459 Cap::Snapshot
8460 | Cap::NativeSymbols
8461 | Cap::NavTabs
8470 | Cap::NavSplit
8471 | Cap::NavRepresent
8475 | Cap::NavContentList
8478 | Cap::Dialogs
8479 | Cap::FileDialogs
8480 | Cap::FolderDialog
8482 | Cap::Animation
8483 | Cap::TextEditable
8485 | Cap::TextSelectable
8486 | Cap::TextSpellCheck
8487 | Cap::NavReorder | Cap::ListReorder
8490 | Cap::ListRecycling
8493 | Cap::ListSwipeActions
8496 | Cap::ListSections
8498 | Cap::Tree
8501 | Cap::TreeSections
8502 | Cap::TreeMove
8503 | Cap::MultiWindow
8505 | Cap::WindowStates
8508 | Cap::WindowFullscreen
8509 | Cap::ContentProtection
8511 | Cap::WindowTabbing
8514 | Cap::DockMenu
8516 | Cap::FramelessWindow
8520 | Cap::OverlayTitleBar
8521 | Cap::TransparentWindow
8522 | Cap::WindowMaterial
8523 | Cap::DragRegion
8525 | Cap::StatusItem
8528 | Cap::AppProgress
8529 | Cap::DockVisibility
8530 | Cap::WindowGeometry
8533 | Cap::WindowPosition
8534 | Cap::WindowLevel
8535 | Cap::WindowAppearance
8536 | Cap::RequestAttention
8537 | Cap::Monitors
8538 | Cap::DynamicShortcuts
8540 | Cap::Toolbar
8542 | Cap::ToolbarSearch
8544 | Cap::AppMenu
8545 | Cap::AppBadgeCount
8548 | Cap::AppBadgeText
8549 | Cap::UndoBridge
8552 | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
8553 | Cap::AppBadgeDot
8554 | Cap::Appearance
8555 | Cap::BaselineAlignment
8557 | Cap::Inspector
8560 | Cap::Split
8562 | Cap::TextRuns
8563 | Cap::TextLinks => Support::Native,
8564 Cap::Cover => Support::Emulated,
8567 Cap::CoverSheet => Support::Native,
8569 _ => Support::Unsupported,
8570 }
8571 }
8572
8573 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
8574 let mtm = self.mtm;
8575 match Builtin::from_key(kind) {
8576 Some(Builtin::Container) => {
8577 let v = DayFlipped::new(mtm);
8578 if let Some(p) = props.downcast_ref::<ContainerProps>() {
8579 if p.role == Some(day_spec::SurfaceRole::SectionCard) {
8580 v.set_section_card(p.corner_radius);
8581 } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
8582 v.set_surface(p.background, p.corner_radius, p.clips);
8583 }
8584 }
8585 view_of(v)
8586 }
8587 Some(Builtin::Scroll) => {
8588 let horizontal = props
8589 .downcast_ref::<day_spec::props::ScrollProps>()
8590 .map(|p| p.horizontal)
8591 .unwrap_or(false);
8592 let sv = unsafe { NSScrollView::new(mtm) };
8593 unsafe {
8594 sv.setHasVerticalScroller(!horizontal);
8595 sv.setHasHorizontalScroller(horizontal);
8596 sv.setDrawsBackground(false);
8597 sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8603 }
8604 let doc = DayFlipped::new(mtm);
8605 unsafe { sv.setDocumentView(Some(doc.as_ref())) };
8606 view_of(sv)
8607 }
8608 Some(Builtin::Label) => {
8609 let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
8614 return placeholder_view(mtm, kind);
8615 };
8616 let tf = DayLabel::new(mtm, id, &p.text);
8617 configure_label_cell(&tf);
8618 if !p.wraps || p.max_lines > 0 {
8619 unsafe {
8620 tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8621 if !p.wraps || p.max_lines == 1 {
8622 tf.setUsesSingleLineMode(true);
8623 tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8624 }
8625 }
8626 }
8627 unsafe { tf.setFont(Some(&nsfont(p.font))) };
8628 match (p.color, p.role) {
8632 (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8633 (None, day_spec::props::TextRole::Secondary) => unsafe {
8634 tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
8635 },
8636 (None, day_spec::props::TextRole::Primary) => {}
8637 }
8638 if !p.runs.is_empty() {
8639 let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8640 unsafe { tf.setAttributedStringValue(&s) };
8641 }
8642 tf.ivars().has_runs.set(!p.runs.is_empty());
8643 tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8644 if p.align != day_spec::props::TextAlign::Leading {
8649 unsafe { tf.setAlignment(nstextalign(p.align)) };
8650 if !p.runs.is_empty() {
8651 set_paragraph_alignment(&tf, nstextalign(p.align));
8652 }
8653 }
8654 view_of(Retained::into_super(tf))
8655 }
8656 Some(Builtin::Button) => {
8657 let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8658 return placeholder_view(mtm, kind);
8659 };
8660 let target = DayTarget::new(mtm, id);
8661 let btn = unsafe {
8662 NSButton::buttonWithTitle_target_action(
8663 &NSString::from_str(&p.title),
8664 Some(&*target),
8665 Some(sel!(action:)),
8666 mtm,
8667 )
8668 };
8669 apply_button_style(&btn, p.style);
8670 if p.icon.is_some() {
8671 apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8672 }
8673 unsafe { btn.setEnabled(p.enabled) };
8674 set_button_selected(&btn, p.selected);
8675 let view = view_of(btn);
8676 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8677 view
8678 }
8679 Some(Builtin::Toggle) => {
8680 let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8681 return placeholder_view(mtm, kind);
8682 };
8683 let target = DayTarget::new(mtm, id);
8684 let sw = unsafe { NSSwitch::new(mtm) };
8685 unsafe {
8686 sw.setState(if p.on { 1 } else { 0 });
8687 sw.setEnabled(p.enabled);
8688 sw.setTarget(Some(&*target));
8689 sw.setAction(Some(sel!(action:)));
8690 }
8691 let view = view_of(sw);
8692 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8693 view
8694 }
8695 Some(Builtin::Slider) => {
8696 let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8697 return placeholder_view(mtm, kind);
8698 };
8699 let target = DayTarget::new(mtm, id);
8700 let sl = unsafe {
8701 NSSlider::sliderWithValue_minValue_maxValue_target_action(
8702 p.value,
8703 p.min,
8704 p.max,
8705 Some(&*target),
8706 Some(sel!(action:)),
8707 mtm,
8708 )
8709 };
8710 unsafe { sl.setContinuous(true) };
8711 let view = view_of(sl);
8712 TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8713 view
8714 }
8715 Some(Builtin::Picker) => picker::realize_any(self, props, id),
8716 Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8717 Some(Builtin::TextField) => {
8718 let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8719 return placeholder_view(mtm, kind);
8720 };
8721 let tf = new_text_field(mtm, id, false);
8722 unsafe {
8723 tf.setStringValue(&NSString::from_str(&p.text));
8724 tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8725 }
8726 view_of(tf)
8727 }
8728 Some(Builtin::Divider) => {
8729 let b = unsafe { NSBox::new(mtm) };
8730 unsafe { b.setBoxType(NSBoxType::Separator) };
8731 view_of(b)
8732 }
8733 Some(Builtin::Progress) => {
8734 let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8735 return placeholder_view(mtm, kind);
8736 };
8737 if p.value.is_none() {
8738 return crate::controls::spinner::make(self, p, id);
8739 }
8740 let pi = unsafe { NSProgressIndicator::new(mtm) };
8741 unsafe {
8742 match p.value {
8743 Some(v) => {
8744 pi.setStyle(NSProgressIndicatorStyle::Bar);
8745 pi.setIndeterminate(false);
8746 pi.setMinValue(0.0);
8747 pi.setMaxValue(1.0);
8748 pi.setDoubleValue(v);
8749 }
8750 None => {
8751 pi.setStyle(NSProgressIndicatorStyle::Spinning);
8752 pi.setIndeterminate(true);
8753 pi.startAnimation(None);
8754 }
8755 }
8756 }
8757 view_of(pi)
8758 }
8759 Some(Builtin::Canvas) => {
8760 let canvas = DayCanvas::new(mtm);
8761 KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8762 view_of(canvas)
8763 }
8764 Some(Builtin::Inspector) => {
8765 let (visible, width, leading) = props
8766 .downcast_ref::<InspectorProps>()
8767 .map(|p| {
8768 (
8769 p.visible,
8770 p.width,
8771 p.edge == day_spec::props::PaneEdge::Leading,
8772 )
8773 })
8774 .unwrap_or((false, 280.0, false));
8775 let content_wrap = view_of(DayFlipped::new(mtm));
8776 let panel_flipped = DayFlipped::new(mtm);
8777 panel_flipped.set_pane_backdrop();
8781 let panel_wrap = view_of(panel_flipped);
8782 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8783 let _ = unsafe { split_vc.view() };
8786 let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8787 let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8788 unsafe {
8789 content_vc.setView(&content_wrap);
8790 panel_vc.setView(&panel_wrap);
8791 }
8792 let content_item = unsafe {
8793 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8794 };
8795 let panel_item = unsafe {
8800 if leading {
8801 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8802 } else {
8803 objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8804 }
8805 };
8806 unsafe {
8807 panel_item.setCanCollapse(false);
8811 panel_item.setCollapsed(!visible);
8812 panel_item.setMinimumThickness(width);
8813 panel_item.setMaximumThickness(width);
8814 panel_item.setAllowsFullHeightLayout(true);
8815 if leading {
8816 split_vc.addSplitViewItem(&panel_item);
8817 split_vc.addSplitViewItem(&content_item);
8818 } else {
8819 split_vc.addSplitViewItem(&content_item);
8820 split_vc.addSplitViewItem(&panel_item);
8821 }
8822 }
8823 let split = unsafe { split_vc.splitView() };
8824 unsafe {
8825 split.setVertical(true);
8826 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8827 split.setTranslatesAutoresizingMaskIntoConstraints(true);
8831 }
8832 let view = view_of(split);
8833 INSPECTOR_STATE.with(|m| {
8834 m.borrow_mut().insert(
8835 ptr_of(&view),
8836 InspectorState {
8837 content_wrap,
8838 panel_wrap,
8839 _split_vc: split_vc,
8840 panel_item,
8841 },
8842 )
8843 });
8844 view
8845 }
8846 Some(Builtin::InspectorPane) => {
8847 let pane = view_of(DayNavPage::new(mtm, id));
8851 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8852 let panel = props
8853 .downcast_ref::<InspectorPaneProps>()
8854 .map(|p| p.panel)
8855 .unwrap_or(false);
8856 INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8857 pane
8858 }
8859 Some(Builtin::Split) => {
8860 let (axis, fraction, min_pane) = props
8861 .downcast_ref::<SplitProps>()
8862 .map(|p| (p.axis, p.fraction, p.min_pane))
8863 .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8864 let wrap = view_of(DayFlipped::new(mtm));
8865 let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8866 let first_wrap = view_of(DayFlipped::new(mtm));
8867 let second_wrap = view_of(DayFlipped::new(mtm));
8868 unsafe {
8869 split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8871 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8872 split.addArrangedSubview(&first_wrap);
8873 split.addArrangedSubview(&second_wrap);
8874 split.setFrame(wrap.bounds());
8875 split.setAutoresizingMask(
8876 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8877 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8878 );
8879 wrap.addSubview(&split);
8880 }
8881 let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8882 split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8883 SPLIT_STATE.with(|m| {
8884 m.borrow_mut().insert(
8885 ptr_of(&wrap),
8886 SplitState {
8887 split,
8888 first_wrap,
8889 second_wrap,
8890 delegate,
8891 },
8892 )
8893 });
8894 wrap
8895 }
8896 Some(Builtin::SplitPane) => {
8897 let pane = view_of(DayNavPage::new(mtm, id));
8900 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8901 let second = props
8902 .downcast_ref::<SplitPaneProps>()
8903 .map(|p| p.second)
8904 .unwrap_or(false);
8905 SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8906 pane
8907 }
8908 Some(Builtin::Nav) => {
8909 let presentation = props
8910 .downcast_ref::<NavProps>()
8911 .map(|p| p.presentation)
8912 .unwrap_or(NavPresentation::Split);
8913 let is_split = presentation.is_split();
8914 let sidebar_wrap = view_of(DayFlipped::new(mtm));
8923 let detail_wrap = view_of(DayFlipped::new(mtm));
8924 let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8925 let _ = unsafe { split_vc.view() };
8931 let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8934 let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8935 unsafe {
8936 sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8937 detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8938 }
8939 let sidebar_item = unsafe {
8940 objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8941 };
8942 let detail_item = unsafe {
8943 objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8944 };
8945 let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8951 let list_visible = props
8957 .downcast_ref::<NavProps>()
8958 .is_none_or(|p| p.list_visible);
8959 let (list_wrap, list_item) = match list_width {
8960 Some(w) => {
8961 let wrap = view_of(DayFlipped::new(mtm));
8962 let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8963 unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8964 let item = unsafe {
8965 objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8966 };
8967 unsafe {
8968 item.setCanCollapse(true);
8969 item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8970 item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8971 item.setCollapsed(!list_visible);
8972 }
8973 (Some(wrap), Some(item))
8974 }
8975 None => (None, None),
8976 };
8977 unsafe {
8978 sidebar_item.setCanCollapse(is_split);
8981 sidebar_item.setCollapsed(!is_split);
8982 if is_split {
8983 sidebar_item.setAllowsFullHeightLayout(true);
8987 sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8988 sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8989 } else {
8990 sidebar_item.setMinimumThickness(0.0);
8991 sidebar_item.setMaximumThickness(0.0);
8992 }
8993 split_vc.addSplitViewItem(&sidebar_item);
8994 if let Some(item) = list_item.as_ref() {
8995 split_vc.addSplitViewItem(item);
8996 }
8997 split_vc.addSplitViewItem(&detail_item);
8998 }
8999 let split = unsafe { split_vc.splitView() };
9000 unsafe {
9007 let after = split.nextResponder();
9008 split.setNextResponder(Some(&split_vc));
9009 let own_view = split_vc.view();
9019 let vc_resp: *const objc2_app_kit::NSResponder = {
9020 let r: &objc2_app_kit::NSResponder = &split_vc;
9021 r
9022 };
9023 let view_resp: *const objc2_app_kit::NSResponder = {
9024 let r: &objc2_app_kit::NSResponder = &own_view;
9025 r
9026 };
9027 let upstream = after.filter(|a| {
9028 let p: *const objc2_app_kit::NSResponder = &**a;
9029 p != vc_resp && p != view_resp
9030 });
9031 split_vc.setNextResponder(upstream.as_deref());
9032 }
9033 unsafe {
9034 split.setVertical(true);
9035 split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
9036 split.setTranslatesAutoresizingMaskIntoConstraints(true);
9044 }
9045 let root_title = props
9046 .downcast_ref::<NavProps>()
9047 .map(|p| p.title.clone())
9048 .unwrap_or_default();
9049 let header = if presentation == NavPresentation::Stack {
9052 Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
9053 } else {
9054 None
9055 };
9056 let tabs = (presentation == NavPresentation::Tabs).then(|| {
9059 let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
9060 let documents = props
9061 .downcast_ref::<NavProps>()
9062 .is_some_and(|p| p.documents.is_some());
9063 let (inset, inset_top) = if documents {
9069 (0.0, 0.0)
9070 } else {
9071 (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
9072 };
9073 let b = detail_wrap.bounds();
9074 let frame = NSRect::new(
9075 NSPoint::new(inset, inset_top),
9076 NSSize::new(
9077 (b.size.width - 2.0 * inset).max(0.0),
9078 (b.size.height - inset_top - inset).max(0.0),
9079 ),
9080 );
9081 unsafe {
9082 tv.setTabViewType(if documents {
9083 objc2_app_kit::NSTabViewType::NoTabsNoBorder
9084 } else {
9085 objc2_app_kit::NSTabViewType::TopTabsBezelBorder
9086 });
9087 tv.setFrame(frame);
9088 tv.setAutoresizingMask(
9089 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9090 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9091 );
9092 detail_wrap.addSubview(&tv);
9093 }
9094 TabHost {
9095 view: tv,
9096 target: None,
9097 }
9098 });
9099 let view = view_of(split);
9100 NAV_STATE.with(|m| {
9101 m.borrow_mut().insert(
9102 ptr_of(&view),
9103 NavState {
9104 sidebar_wrap,
9105 detail_wrap,
9106 _split_vc: split_vc,
9107 sidebar_item,
9108 list_wrap,
9109 list_item,
9110 pages: Vec::new(),
9111 list_page: None,
9112 sidebar_page: None,
9113 list_width,
9114 list_visible,
9115 list_positioned: false,
9116 positioned: false,
9117 presentation,
9118 selected: 0,
9119 tabs,
9120 header,
9121 root_title,
9122 node: id,
9123 title_strip: 0.0,
9124 },
9125 )
9126 });
9127 view
9128 }
9129 Some(Builtin::NavPage) => {
9130 let page = view_of(DayNavPage::new(mtm, id));
9131 NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
9132 if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
9133 PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
9134 }
9135 page
9136 }
9137 Some(Builtin::Cover) => {
9141 let page = DayNavPage::new(mtm, id);
9142 let cover_props = props.downcast_ref::<CoverProps>();
9143 page.ivars()
9146 .sheet
9147 .set(cover_props.is_some_and(|p| p.sheet || p.half));
9148 page.ivars().half.set(cover_props.is_some_and(|p| p.half));
9149 page.ivars().large.set(cover_props.is_some_and(|p| p.large));
9150 unsafe { page.setHidden(true) };
9151 view_of(page)
9152 }
9153 Some(Builtin::NavMenu) => {
9154 let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
9155 return placeholder_view(mtm, kind);
9156 };
9157 let data = DayNavMenuData::new(
9158 mtm,
9159 id,
9160 &p.items,
9161 &p.icons,
9162 &p.badges,
9163 &p.badge_icons,
9164 &p.badge_tints,
9165 &p.sections,
9166 &p.tints,
9167 &p.menus,
9168 );
9169 *data.ivars().movable.borrow_mut() = p.movable.clone();
9170 data.ivars().regroup.set(p.regroup);
9171 *data.ivars().sorted.borrow_mut() = p.sorted.clone();
9172 let outline: Retained<objc2_app_kit::NSOutlineView> = {
9174 let o: Retained<DayNavOutlineView> =
9175 unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
9176 NAV_OUTLINE_MENUS
9177 .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
9178 unsafe { msg_send![&*o, self] }
9179 };
9180 let col = unsafe {
9181 objc2_app_kit::NSTableColumn::initWithIdentifier(
9182 objc2_app_kit::NSTableColumn::alloc(mtm),
9183 &NSString::from_str("item"),
9184 )
9185 };
9186 unsafe {
9187 outline.addTableColumn(&col);
9188 outline.setOutlineTableColumn(Some(&col));
9189 outline.setHeaderView(None);
9190 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9203 outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
9208 outline.setFloatsGroupRows(true);
9211 outline.setIndentationPerLevel(0.0);
9212 outline.registerForDraggedTypes(
9215 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9216 DAY_NAV_PASTEBOARD_TYPE,
9217 )]),
9218 );
9219 outline.setDraggingSourceOperationMask_forLocal(
9220 objc2_app_kit::NSDragOperation::Move,
9221 true,
9222 );
9223 outline.setDraggingSourceOperationMask_forLocal(
9224 objc2_app_kit::NSDragOperation::None,
9225 false,
9226 );
9227 outline.setDraggingDestinationFeedbackStyle(
9228 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9229 );
9230 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9231 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9232 outline.reloadData();
9233 }
9234 let scroll = unsafe { NSScrollView::new(mtm) };
9235 unsafe {
9236 scroll.setDrawsBackground(false);
9237 scroll.setHasVerticalScroller(true);
9238 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9242 scroll.setHasHorizontalScroller(false);
9244 outline.setAutoresizingMask(
9245 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9246 );
9247 outline.setColumnAutoresizingStyle(
9248 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9249 );
9250 scroll.setDocumentView(Some(&outline));
9251 }
9252 let view = view_of(scroll);
9253 if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
9256 data.ivars().suppress.set(true);
9257 unsafe {
9258 outline.selectRowIndexes_byExtendingSelection(
9259 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9260 false,
9261 )
9262 };
9263 data.ivars().suppress.set(false);
9264 }
9265 NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9266 view
9267 }
9268 Some(Builtin::List) => {
9269 let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
9270 return placeholder_view(mtm, kind);
9271 };
9272 let table: Retained<DayListView> =
9274 unsafe { msg_send![DayListView::alloc(mtm), init] };
9275 let table = Retained::into_super(table);
9276 if p.inset_grouped {
9277 unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
9280 }
9281 let col = unsafe {
9282 NSTableColumn::initWithIdentifier(
9283 NSTableColumn::alloc(mtm),
9284 &NSString::from_str("day.list.col"),
9285 )
9286 };
9287 let data = DayListData::new(
9288 mtm,
9289 id,
9290 p.selectable,
9291 p.multi_select,
9292 p.row_height == RowHeight::Automatic,
9293 p.sections,
9294 );
9295 unsafe {
9296 if p.multi_select {
9297 table.setAllowsMultipleSelection(true);
9298 }
9299 table.addTableColumn(&col);
9300 table.setHeaderView(None);
9301 table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
9310 table.setIntercellSpacing(NSSize::new(0.0, 0.0));
9314 if p.separators == Some(true) {
9318 table.setGridStyleMask(
9319 objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
9320 );
9321 table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
9322 }
9323 table.setColumnAutoresizingStyle(
9324 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9325 );
9326 table.setFloatsGroupRows(p.sections);
9329 match p.row_height {
9330 RowHeight::Uniform(h) => table.setRowHeight(h),
9331 RowHeight::Automatic => table.setRowHeight(44.0),
9332 }
9333 if !p.selectable {
9334 table.setSelectionHighlightStyle(
9335 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9336 );
9337 }
9338 table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9342 table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9343 table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9344 table.setTarget(Some(&*data));
9345 if p.activatable {
9346 table.setDoubleAction(Some(sel!(doubleClickRow:)));
9347 }
9348 if p.reorderable {
9349 table.registerForDraggedTypes(
9353 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9354 DAY_ROW_PASTEBOARD_TYPE,
9355 )]),
9356 );
9357 table.setDraggingSourceOperationMask_forLocal(
9358 objc2_app_kit::NSDragOperation::Move,
9359 true,
9360 );
9361 table.setDraggingSourceOperationMask_forLocal(
9362 objc2_app_kit::NSDragOperation::None,
9363 false,
9364 );
9365 table.setDraggingDestinationFeedbackStyle(
9366 objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9367 );
9368 }
9369 }
9370 let scroll = unsafe { NSScrollView::new(mtm) };
9371 unsafe {
9372 scroll.setDrawsBackground(false);
9373 scroll.setHasVerticalScroller(true);
9374 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9378 scroll.setDocumentView(Some(&table));
9379 let clip = scroll.contentView();
9380 clip.setPostsBoundsChangedNotifications(true);
9381 objc2_foundation::NSNotificationCenter::defaultCenter()
9382 .addObserver_selector_name_object(
9383 &data,
9384 sel!(listViewportChanged:),
9385 Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
9386 Some(&clip),
9387 );
9388 }
9389 let view = view_of(scroll);
9390 LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
9391 view
9392 }
9393 Some(Builtin::Tree) => {
9394 let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
9395 return placeholder_view(mtm, kind);
9396 };
9397 let outline: Retained<objc2_app_kit::NSOutlineView> = {
9399 let o: Retained<DayOutlineView> =
9400 unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
9401 unsafe { msg_send![&*o, self] }
9402 };
9403 let col = unsafe {
9404 NSTableColumn::initWithIdentifier(
9405 NSTableColumn::alloc(mtm),
9406 &NSString::from_str("day.tree.col"),
9407 )
9408 };
9409 let data = DayTreeData::new(mtm, id, p.selectable);
9410 unsafe {
9411 if p.multi_select {
9412 outline.setAllowsMultipleSelection(true);
9413 }
9414 outline.addTableColumn(&col);
9415 outline.setOutlineTableColumn(Some(&col));
9416 outline.setHeaderView(None);
9417 if p.section_headers {
9418 outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9421 outline.setFloatsGroupRows(true);
9422 } else {
9423 outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
9426 outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
9427 }
9428 outline.setColumnAutoresizingStyle(
9429 objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9430 );
9431 outline.setAutoresizesOutlineColumn(true);
9432 if let Some(indent) = p.indent {
9433 outline.setIndentationPerLevel(indent);
9434 }
9435 match p.row_height {
9436 RowHeight::Uniform(h) => outline.setRowHeight(h),
9437 RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
9438 RowHeight::Automatic => {}
9439 }
9440 if !p.selectable {
9441 outline.setSelectionHighlightStyle(
9442 objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9443 );
9444 }
9445 outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9446 outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9447 outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9448 if p.movable {
9449 outline.registerForDraggedTypes(
9454 &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9455 DAY_TREE_PASTEBOARD_TYPE,
9456 )]),
9457 );
9458 outline.setDraggingSourceOperationMask_forLocal(
9459 objc2_app_kit::NSDragOperation::Move,
9460 true,
9461 );
9462 outline.setDraggingSourceOperationMask_forLocal(
9463 objc2_app_kit::NSDragOperation::None,
9464 false,
9465 );
9466 }
9467 }
9468 let scroll = unsafe { NSScrollView::new(mtm) };
9469 unsafe {
9470 scroll.setDrawsBackground(false);
9471 scroll.setHasVerticalScroller(true);
9472 scroll.setHasHorizontalScroller(false);
9473 scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9474 outline.setAutoresizingMask(
9475 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9476 );
9477 scroll.setDocumentView(Some(&outline));
9478 }
9479 let view = view_of(scroll);
9480 TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9481 view
9482 }
9483 Some(Builtin::Image) => {
9484 let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
9485 return placeholder_view(mtm, kind);
9486 };
9487 let iv: Retained<objc2_app_kit::NSImageView> =
9488 if p.content_mode == ContentMode::Fill {
9489 let view: Retained<FillImageView> =
9490 unsafe { msg_send![FillImageView::alloc(mtm), init] };
9491 Retained::from(
9492 <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
9493 )
9494 } else {
9495 unsafe { objc2_app_kit::NSImageView::new(mtm) }
9496 };
9497 let scaling = match p.content_mode {
9500 ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
9501 _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
9502 };
9503 unsafe { iv.setImageScaling(scaling) };
9504 if let Some(img) = appkit_image_for(&p.source) {
9505 if p.tint.is_some() || p.template {
9510 unsafe { img.setTemplate(true) };
9511 }
9512 unsafe { iv.setImage(Some(&img)) };
9513 }
9514 if let Some(t) = p.tint {
9515 unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
9516 }
9517 IMAGE_MODES.with(|t| {
9518 t.insert(
9519 ptr_of(&iv),
9520 ImageMode {
9521 template: p.template,
9522 tinted: p.tint.is_some(),
9523 },
9524 )
9525 });
9526 view_of(iv)
9527 }
9528 Some(Builtin::ListItem) => {
9529 let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
9530 else {
9531 return placeholder_view(mtm, kind);
9532 };
9533 make_list_item(p, mtm)
9534 }
9535 Some(Builtin::ListCell) | None => {
9538 if let Some(make) = self.registry.get(kind).map(|r| r.make) {
9539 return make(self, props, id);
9540 }
9541 warn_missing_renderer(kind);
9545 placeholder_view(mtm, kind)
9546 }
9547 }
9548 }
9549
9550 fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
9551 match kind {
9552 kinds::LIST_ITEM => {
9553 let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
9554 return;
9555 };
9556 let props = LIST_ITEMS.with(|m| {
9557 let mut m = m.borrow_mut();
9558 let props = m.get_mut(&ptr_of(h))?;
9559 use day_spec::props::ListItemPatch as P;
9560 match p {
9561 P::Title(t) => props.title = t.clone(),
9562 P::Subtitle(t) => props.subtitle = t.clone(),
9563 P::Detail(t) => props.detail = t.clone(),
9564 P::Icon(i) => props.icon = i.clone(),
9565 P::IconTint(c) => props.icon_tint = *c,
9566 P::Checked(on) => props.checked = *on,
9567 }
9568 Some(props.clone())
9569 });
9570 if let Some(props) = props {
9571 dress_list_item(h, &props, self.mtm());
9572 }
9573 }
9574 kinds::IMAGE => {
9575 if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
9576 match p {
9577 day_spec::props::ImagePatch::Tint(c) => {
9578 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9582 let key = ptr_of(&iv);
9583 let template = IMAGE_MODES
9584 .with(|t| {
9585 t.with(key, |m| {
9586 m.tinted = c.is_some();
9587 m.renders_template()
9588 })
9589 })
9590 .unwrap_or(c.is_some());
9591 if let Some(img) = unsafe { iv.image() } {
9592 unsafe { img.setTemplate(template) };
9593 }
9594 unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
9595 }
9596 }
9597 day_spec::props::ImagePatch::Source(source) => {
9601 if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9602 if let Some(img) = appkit_image_for(source) {
9608 let template = IMAGE_MODES
9609 .with(|t| t.get(ptr_of(&iv)))
9610 .is_some_and(|m| m.renders_template());
9611 unsafe {
9612 img.setTemplate(template);
9613 iv.setImage(Some(&img));
9614 }
9615 }
9616 }
9617 }
9618 }
9619 }
9620 }
9621 kinds::CONTAINER => {
9622 if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
9623 patch.downcast_ref::<ContainerPatch>(),
9624 h.clone().downcast::<DayFlipped>(),
9625 ) {
9626 v.set_surface(*c, 0.0, false);
9634 }
9635 }
9636 kinds::LABEL => {
9637 if let (Some(p), Ok(tf)) = (
9638 patch.downcast_ref::<LabelPatch>(),
9639 h.clone().downcast::<NSTextField>(),
9640 ) {
9641 match p {
9642 LabelPatch::Text(t) => {
9643 unsafe { tf.setStringValue(&NSString::from_str(t)) };
9644 if let Some(label) = h.downcast_ref::<DayLabel>() {
9645 label.ivars().has_runs.set(false);
9646 label.set_links(false);
9647 }
9648 }
9649 LabelPatch::Color(c) => unsafe {
9650 tf.setTextColor(c.map(nscolor).as_deref())
9651 },
9652 LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9653 LabelPatch::Runs(text, runs) => {
9654 let base = unsafe { tf.font() };
9658 let s = match base.as_deref() {
9659 Some(f) => {
9660 attributed_label(text, f, None, Default::default(), runs)
9661 }
9662 None => attributed_label(
9663 text,
9664 &nsfont(day_spec::FontSpec::default()),
9665 None,
9666 Default::default(),
9667 runs,
9668 ),
9669 };
9670 unsafe { tf.setAttributedStringValue(&s) };
9671 set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9674 if let Some(label) = h.downcast_ref::<DayLabel>() {
9675 label.ivars().has_runs.set(!runs.is_empty());
9676 label.set_links(runs.iter().any(|r| r.link.is_some()));
9677 }
9678 }
9679 }
9680 }
9681 }
9682 kinds::BUTTON => {
9683 if let (Some(p), Ok(btn)) = (
9684 patch.downcast_ref::<ButtonPatch>(),
9685 h.clone().downcast::<NSButton>(),
9686 ) {
9687 match p {
9688 ButtonPatch::Content(c) => {
9689 apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
9690 }
9691 ButtonPatch::Title(t) => {
9692 let style = BUTTON_STYLES
9693 .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9694 .unwrap_or_default();
9695 set_button_title(&btn, t, style);
9696 }
9697 ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9698 ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9699 ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9700 }
9701 }
9702 }
9703 kinds::TOGGLE => {
9704 if let (Some(p), Ok(sw)) = (
9705 patch.downcast_ref::<TogglePatch>(),
9706 h.clone().downcast::<NSSwitch>(),
9707 ) {
9708 match p {
9709 TogglePatch::On(on) => {
9710 let want = if *on { 1 } else { 0 };
9711 if unsafe { sw.state() } != want {
9712 unsafe { sw.setState(want) };
9713 }
9714 }
9715 TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9716 }
9717 }
9718 }
9719 kinds::SLIDER => {
9720 if let (Some(p), Ok(sl)) = (
9721 patch.downcast_ref::<SliderPatch>(),
9722 h.clone().downcast::<NSSlider>(),
9723 ) {
9724 match p {
9725 SliderPatch::Value(v) => {
9726 if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9727 unsafe { sl.setDoubleValue(*v) };
9728 }
9729 }
9730 SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9731 }
9732 }
9733 }
9734 kinds::PROGRESS => {
9735 if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9736 {
9737 crate::controls::spinner::update(self, h, p);
9738 return;
9739 }
9740
9741 if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9742 patch.downcast_ref::<ProgressPatch>(),
9743 h.clone().downcast::<NSProgressIndicator>(),
9744 ) {
9745 unsafe {
9746 match v {
9747 Some(val) => {
9748 if pi.isIndeterminate() {
9749 pi.stopAnimation(None);
9750 pi.setIndeterminate(false);
9751 pi.setStyle(NSProgressIndicatorStyle::Bar);
9752 pi.setMinValue(0.0);
9753 pi.setMaxValue(1.0);
9754 }
9755 if (pi.doubleValue() - val).abs() > 0.0001 {
9756 pi.setDoubleValue(*val);
9757 }
9758 }
9759 None => {
9760 pi.setIndeterminate(true);
9761 pi.setStyle(NSProgressIndicatorStyle::Spinning);
9762 pi.startAnimation(None);
9763 }
9764 }
9765 }
9766 }
9767 }
9768 kinds::NAV_MENU => {
9769 if let Some(NavMenuPatch::Items {
9770 items,
9771 icons,
9772 badges,
9773 badge_icons,
9774 badge_tints,
9775 sections,
9776 tints,
9777 menus,
9778 movable,
9779 sorted,
9780 selected,
9781 rows_changed,
9782 ..
9783 }) = patch.downcast_ref::<NavMenuPatch>()
9784 {
9785 NAV_MENUS.with(|m| {
9786 let m = m.borrow();
9787 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9788 return;
9789 };
9790 *data.ivars().movable.borrow_mut() = movable.clone();
9791 *data.ivars().sorted.borrow_mut() = sorted.clone();
9792 data.set_items(
9793 items,
9794 icons,
9795 badges,
9796 badge_icons,
9797 badge_tints,
9798 sections,
9799 tints,
9800 menus,
9801 );
9802 data.ivars().suppress.set(true);
9803 if let Some(rows) = rows_changed {
9806 let set = objc2_foundation::NSMutableIndexSet::new();
9807 for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9808 unsafe { set.addIndex(row) };
9809 }
9810 unsafe {
9811 outline.reloadDataForRowIndexes_columnIndexes(
9812 &set,
9813 &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9814 )
9815 };
9816 data.ivars().suppress.set(false);
9817 return;
9818 }
9819 unsafe {
9820 outline.reloadData();
9821 match selected.and_then(|i| data.row_of_item(i)) {
9822 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9823 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9824 false,
9825 ),
9826 None => outline.deselectAll(None),
9827 }
9828 }
9829 data.ivars().suppress.set(false);
9830 });
9831 adopt_menu_for_tabs(self.mtm(), h);
9833 } else if let Some(NavMenuPatch::IconProgress(progress)) =
9834 patch.downcast_ref::<NavMenuPatch>()
9835 {
9836 NAV_MENUS.with(|menus| {
9837 let menus = menus.borrow();
9838 let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9839 return;
9840 };
9841 let previous = data.ivars().icon_progress.replace(progress.clone());
9842 for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9843 let Some(index) = item else {
9844 continue;
9845 };
9846 let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9847 if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9848 continue;
9849 }
9850 if let Some(view) = unsafe {
9851 outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9852 } && let Some(cell) =
9853 view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9854 && let Some(icon) = unsafe { cell.imageView() }
9855 {
9856 nav_progress::update(&icon, value);
9857 }
9858 }
9859 });
9860 } else if let Some(NavMenuPatch::Selected(sel)) =
9861 patch.downcast_ref::<NavMenuPatch>()
9862 {
9863 NAV_MENUS.with(|m| {
9864 let m = m.borrow();
9865 let Some((outline, data)) = m.get(&ptr_of(h)) else {
9866 return;
9867 };
9868 data.ivars().suppress.set(true);
9869 unsafe {
9870 match sel.and_then(|i| data.row_of_item(i)) {
9871 Some(row) => outline.selectRowIndexes_byExtendingSelection(
9872 &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9873 false,
9874 ),
9875 None => outline.deselectAll(None),
9876 }
9877 }
9878 data.ivars().suppress.set(false);
9879 });
9880 }
9881 }
9882 kinds::INSPECTOR => {
9883 if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9884 INSPECTOR_STATE.with(|m| {
9885 if let Some(state) = m.borrow().get(&ptr_of(h)) {
9886 state.panel_item.setCollapsed(!*v);
9889 }
9890 });
9891 }
9892 }
9893 kinds::SPLIT => {
9894 if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9895 SPLIT_STATE.with(|m| {
9896 let m = m.borrow();
9897 let Some(state) = m.get(&ptr_of(h)) else {
9898 return;
9899 };
9900 let iv = state.delegate.ivars();
9901 match p {
9902 SplitPatch::Fraction(f) => {
9903 iv.share.set(f.clamp(0.0, 1.0));
9904 if iv.positioned.get() {
9905 split_place(&state.split, iv);
9906 }
9907 }
9908 SplitPatch::Axis(axis) => unsafe {
9909 state
9910 .split
9911 .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9912 state.split.adjustSubviews();
9913 if iv.positioned.get() {
9914 split_place(&state.split, iv);
9915 }
9916 },
9917 }
9918 });
9919 }
9920 }
9921 kinds::NAV => {
9922 if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9923 nav_present(self.mtm(), h, *next);
9924 return;
9925 }
9926 if let Some(p) = patch.downcast_ref::<NavPatch>() {
9927 NAV_STATE.with(|m| {
9928 let mut m = m.borrow_mut();
9929 let Some(state) = m.get_mut(&ptr_of(h)) else {
9930 return;
9931 };
9932 match p {
9933 NavPatch::Pushed { title, .. } => {
9934 let last = state.pages.len().saturating_sub(1);
9936 state.selected = last;
9937 for (i, page) in state.pages.iter().enumerate() {
9938 page.setHidden(i != last);
9939 }
9940 if let Some(hdr) = state.header.as_mut() {
9941 hdr.titles.push(title.clone());
9942 sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9943 }
9944 }
9945 NavPatch::Popped => {
9946 let n = state.pages.len();
9949 if let Some(top) = state.pages.last() {
9950 top.setHidden(true);
9951 }
9952 if n >= 2 {
9953 state.pages[n - 2].setHidden(false);
9954 }
9955 state.selected = n.saturating_sub(2);
9956 if let Some(hdr) = state.header.as_mut() {
9957 if hdr.titles.len() > 1 {
9958 hdr.titles.pop();
9959 }
9960 let after: Vec<Retained<NSView>> = state
9963 .pages
9964 .iter()
9965 .take(n.saturating_sub(1))
9966 .cloned()
9967 .collect();
9968 sync_nav_header(hdr, &state.detail_wrap, &after);
9969 }
9970 }
9971 NavPatch::Title(t) => {
9972 if let Some(hdr) = state.header.as_mut() {
9973 if let Some(last) = hdr.titles.last_mut() {
9974 *last = t.clone();
9975 }
9976 unsafe {
9977 hdr.title.setStringValue(&NSString::from_str(t));
9978 }
9979 }
9980 }
9981 NavPatch::GuardTop(_) => {}
9985 NavPatch::Reorder(order) => {
9986 let old = state.pages.clone();
9987 state.pages =
9988 order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9989 if let Some(tabs) = &state.tabs {
9990 TAB_PICK_SUPPRESS.with(|s| s.set(true));
9991 unsafe {
9992 let items = tabs.view.tabViewItems();
9993 for item in items.iter() {
9994 tabs.view.removeTabViewItem(&item);
9995 }
9996 for i in order {
9997 if let Some(item) = items.iter().nth(*i) {
9998 tabs.view.addTabViewItem(&item);
9999 }
10000 }
10001 }
10002 TAB_PICK_SUPPRESS.with(|s| s.set(false));
10003 }
10004 }
10005 NavPatch::Presentation(_) => {}
10007 NavPatch::Select(i) => {
10011 state.selected = *i;
10012 match state.tabs.as_ref() {
10013 Some(tabs) => {
10015 let n = unsafe { tabs.view.numberOfTabViewItems() };
10016 if (*i as isize) < n {
10017 TAB_PICK_SUPPRESS.with(|s| s.set(true));
10018 unsafe {
10019 tabs.view.selectTabViewItemAtIndex(*i as isize)
10020 };
10021 TAB_PICK_SUPPRESS.with(|s| s.set(false));
10022 }
10023 }
10024 None => {
10025 for (n, page) in state.pages.iter().enumerate() {
10026 page.setHidden(n != *i);
10027 }
10028 }
10029 }
10030 }
10031 NavPatch::ListVisible(v) => {
10037 state.list_visible = *v;
10038 if let Some(item) = state.list_item.as_ref() {
10039 item.setCollapsed(!*v);
10040 let split = unsafe { state._split_vc.splitView() };
10041 unsafe { split.layoutSubtreeIfNeeded() };
10042 if let Some(w) = take_list_placement(state) {
10047 unsafe {
10048 split.setPosition_ofDividerAtIndex(
10049 day_spec::NAV_SIDEBAR_WIDTH + w,
10050 1,
10051 );
10052 }
10053 }
10054 if *v
10061 && let Some(wrap) = state.list_wrap.as_ref()
10062 && let Some(page) = state.list_page.as_ref()
10063 {
10064 unsafe {
10065 wrap.layoutSubtreeIfNeeded();
10066 page.setFrame(wrap.bounds());
10067 }
10068 }
10069 }
10070 }
10071 NavPatch::ListInStack(_) => {}
10075 }
10076 });
10077 }
10078 }
10079 kinds::COVER => {
10085 if let (Some(p), Ok(page)) = (
10086 patch.downcast_ref::<CoverPatch>(),
10087 h.clone().downcast::<DayNavPage>(),
10088 ) {
10089 let node = page.ivars().node;
10090 match p {
10091 CoverPatch::Present { background, .. } => {
10092 if page.ivars().sheet.get() {
10093 if let Some(parent) =
10094 primary_content().and_then(|v| unsafe { v.window() })
10095 {
10096 let bounds = parent.frame().size;
10097 let max = if page.ivars().large.get() {
10098 day_spec::props::LARGE_SHEET_MAX
10099 } else {
10100 day_spec::props::SHEET_MAX
10101 };
10102 let height = if page.ivars().half.get() {
10103 (bounds.height * 0.5).clamp(160.0, max.height)
10104 } else {
10105 (bounds.height - 80.0).clamp(300.0, max.height)
10106 };
10107 let size = NSSize::new(
10108 (bounds.width - 40.0).clamp(320.0, max.width),
10109 height,
10110 );
10111 let window = unsafe {
10112 NSWindow::initWithContentRect_styleMask_backing_defer(
10113 NSWindow::alloc(MainThreadMarker::new().unwrap()),
10114 NSRect::new(NSPoint::new(0.0, 0.0), size),
10115 NSWindowStyleMask::Titled,
10116 NSBackingStoreType::Buffered,
10117 false,
10118 )
10119 };
10120 unsafe {
10121 window.setReleasedWhenClosed(false);
10122 page.removeFromSuperview();
10123 page.setHidden(false);
10124 page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
10125 window.setContentView(Some(&page));
10126 }
10127 let key = ptr_of(h);
10128 SHEET_NODES.with(|t| {
10129 t.insert(Retained::as_ptr(&window) as usize, node)
10130 });
10131 install_sheet_escape_monitor();
10132 COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
10133 dispatch2::DispatchQueue::main().exec_async(move || {
10134 ffi_guard::contain((), || {
10135 let window =
10136 COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
10137 if let (Some(window), Some(parent)) = (
10138 window,
10139 primary_content()
10140 .and_then(|v| unsafe { v.window() }),
10141 ) {
10142 unsafe {
10143 parent.beginSheet_completionHandler(
10144 &window, None,
10145 );
10146 }
10147 }
10148 });
10149 });
10150 emit(
10151 node,
10152 Event::FrameChanged(Size::new(size.width, size.height)),
10153 );
10154 }
10155 return;
10156 }
10157 unsafe {
10161 page.setWantsLayer(true);
10162 if let Some(layer) = page.layer() {
10163 let color = match background {
10164 Some(bg) => nscolor(*bg),
10165 None => NSColor::windowBackgroundColor(),
10166 };
10167 layer.setBackgroundColor(Some(&color.CGColor()));
10168 }
10169 }
10170 if let Some(content) = primary_content() {
10173 if let Some(window) = unsafe { content.window() } {
10174 toolbar::cover_presented(ptr_of(h), &window);
10175 }
10176 let top = title_bar_inset(&content);
10181 let full = content.frame().size;
10182 page.ivars().top_inset.set(top);
10183 unsafe {
10184 page.removeFromSuperview();
10185 content.addSubview(&page);
10186 page.setFrame(NSRect::new(
10187 NSPoint::new(0.0, -top),
10188 NSSize::new(full.width, full.height),
10189 ));
10190 page.setBoundsOrigin(NSPoint::new(0.0, -top));
10191 page.setAutoresizingMask(
10192 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10193 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10194 );
10195 page.setHidden(false);
10196 }
10197 emit(
10198 node,
10199 Event::FrameChanged(Size::new(
10200 full.width,
10201 (full.height - top).max(0.0),
10202 )),
10203 );
10204 }
10205 }
10206 CoverPatch::DismissDisabled(_) => {}
10207 CoverPatch::Dismiss => {
10208 COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
10209 toolbar::cover_dismissed(ptr_of(h));
10210 unsafe {
10211 page.setHidden(true);
10212 page.removeFromSuperview();
10213 }
10214 emit(node, Event::CoverHidden);
10215 }
10216 }
10217 }
10218 }
10219 kinds::PICKER => picker::update_any(self, h, patch),
10220 kinds::TEXT_AREA => textarea::update_any(self, h, patch),
10221 kinds::TEXT_FIELD => {
10222 if let (Some(p), Ok(tf)) = (
10223 patch.downcast_ref::<TextFieldPatch>(),
10224 h.clone().downcast::<NSTextField>(),
10225 ) {
10226 match p {
10227 TextFieldPatch::Text { text, from_native } => {
10228 if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
10230 unsafe { tf.setStringValue(&NSString::from_str(text)) };
10231 }
10232 }
10233 TextFieldPatch::Placeholder(t) => unsafe {
10234 tf.setPlaceholderString(Some(&NSString::from_str(t)))
10235 },
10236 TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
10237 TextFieldPatch::Select(sel) => {
10241 if let Some(editor) = tf.currentEditor() {
10242 let (start, end) = sel.utf16(&editor.string().to_string());
10243 editor.setSelectedRange(objc2_foundation::NSRange::new(
10244 start,
10245 end - start,
10246 ));
10247 }
10248 }
10249 }
10250 }
10251 }
10252 kinds::LIST => match patch.downcast_ref::<ListPatch>() {
10253 Some(ListPatch::Splice(deltas)) => {
10254 if let Some((table, data)) = list_entry(ptr_of(h)) {
10260 use objc2_app_kit::NSTableViewAnimationOptions;
10261 for d in deltas {
10262 unsafe {
10263 table.beginUpdates();
10264 match d {
10265 day_spec::props::RowDelta::Insert(i) => table
10266 .insertRowsAtIndexes_withAnimation(
10267 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10268 NSTableViewAnimationOptions::SlideDown,
10269 ),
10270 day_spec::props::RowDelta::Remove(i) => table
10271 .removeRowsAtIndexes_withAnimation(
10272 &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10273 NSTableViewAnimationOptions::SlideUp,
10274 ),
10275 day_spec::props::RowDelta::Move(from, to) => {
10276 table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
10277 }
10278 }
10279 table.endUpdates();
10280 }
10281 }
10282 if let Some(source) = data.ivars().source.borrow().as_ref() {
10286 let n = (source.len)();
10287 *data.ivars().tokens.borrow_mut() =
10288 (0..n).map(|i| (source.token_at)(i)).collect();
10289 }
10290 }
10291 post_realize_visible_rows(ptr_of(h));
10292 }
10293 Some(ListPatch::Reload) => {
10294 if let Some((table, data)) = list_entry(ptr_of(h)) {
10295 let selected = unsafe { table.selectedRowIndexes() };
10299 let tokens: Vec<u64> = data
10300 .ivars()
10301 .tokens
10302 .borrow()
10303 .iter()
10304 .enumerate()
10305 .filter(|(row, _)| selected.containsIndex(*row))
10306 .map(|(_, token)| *token)
10307 .collect();
10308 data.ivars().suppress.set(true);
10309 if let Some(moves) = data.permutation_moves(&table) {
10316 unsafe {
10317 table.beginUpdates();
10318 for (from, to) in moves {
10319 table.moveRowAtIndex_toIndex(from as isize, to as isize);
10320 }
10321 table.endUpdates();
10322 }
10323 } else {
10324 unsafe { table.reloadData() };
10325 }
10326 let restored = objc2_foundation::NSMutableIndexSet::new();
10327 for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
10328 if tokens.contains(token) {
10329 restored.addIndex(row);
10330 }
10331 }
10332 unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
10333 data.ivars().suppress.set(false);
10334 }
10335 post_realize_visible_rows(ptr_of(h));
10341 }
10342 Some(ListPatch::ScrollToRow(row)) => {
10343 let (key, row) = (ptr_of(h), *row);
10346 <AppKit as Platform>::post(Box::new(move || {
10347 if let Some((table, _)) = list_entry(key) {
10348 let rows = unsafe { table.numberOfRows() };
10349 if rows > 0 {
10350 unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
10351 }
10352 }
10353 }));
10354 post_realize_visible_rows(ptr_of(h));
10355 }
10356 Some(ListPatch::ScrollToEnd) => {
10357 let key = ptr_of(h);
10362 <AppKit as Platform>::post(Box::new(move || {
10363 if let Some((table, _)) = list_entry(key) {
10364 let rows = unsafe { table.numberOfRows() };
10365 if rows > 0 {
10366 unsafe { table.scrollRowToVisible(rows - 1) };
10367 }
10368 }
10369 }));
10370 post_realize_visible_rows(ptr_of(h));
10372 }
10373 Some(ListPatch::Selected(rows)) => {
10374 if let Some((table, data)) = list_entry(ptr_of(h)) {
10377 data.ivars().suppress.set(true);
10378 unsafe {
10379 if rows.is_empty() {
10380 table.deselectAll(None);
10381 } else {
10382 let set = objc2_foundation::NSMutableIndexSet::new();
10383 let count = table.numberOfRows().max(0) as usize;
10384 for r in rows.iter().copied().filter(|r| *r < count) {
10385 set.addIndex(r);
10386 }
10387 table.selectRowIndexes_byExtendingSelection(&set, false);
10388 }
10389 }
10390 data.ivars().suppress.set(false);
10391 }
10392 }
10393 Some(ListPatch::RowSizeInvalidated { cell, height }) => {
10394 if let Some((table, data)) = list_entry(ptr_of(h)) {
10395 data.row_resized(&table, *cell, *height);
10396 }
10397 }
10398 Some(ListPatch::Editing(_)) | None => {}
10401 },
10402 kinds::TREE => match patch.downcast_ref::<TreePatch>() {
10403 Some(TreePatch::Reload) => {
10404 if let Some((outline, _)) = tree_entry(ptr_of(h)) {
10409 unsafe { outline.reloadData() };
10410 }
10411 post_realize_visible_tree_rows(ptr_of(h));
10412 }
10413 Some(TreePatch::Expand(token, on)) => {
10414 let (key, token, on) = (ptr_of(h), *token, *on);
10419 <AppKit as Platform>::post(Box::new(move || {
10420 if let Some((outline, data)) = tree_entry(key) {
10421 let item = data.intern(token);
10422 data.ivars().suppress.set(true);
10425 unsafe {
10426 if on {
10427 outline.expandItem(Some(&item));
10428 } else {
10429 outline.collapseItem(Some(&item));
10430 }
10431 }
10432 data.ivars().suppress.set(false);
10433 }
10434 day_core::pump_events();
10435 }));
10436 post_realize_visible_tree_rows(ptr_of(h));
10437 }
10438 Some(TreePatch::Selected(tokens)) => {
10439 if let Some((outline, data)) = tree_entry(ptr_of(h)) {
10440 data.ivars().suppress.set(true);
10441 unsafe {
10442 if tokens.is_empty() {
10443 outline.deselectAll(None);
10444 } else {
10445 let set = objc2_foundation::NSMutableIndexSet::new();
10446 for t in tokens {
10447 let row = outline.rowForItem(Some(&data.intern(*t)));
10450 if row >= 0 {
10451 set.addIndex(row as usize);
10452 }
10453 }
10454 outline.selectRowIndexes_byExtendingSelection(&set, false);
10455 }
10456 }
10457 data.ivars().suppress.set(false);
10458 }
10459 }
10460 Some(TreePatch::Reveal(token)) => {
10461 let (key, token) = (ptr_of(h), *token);
10464 <AppKit as Platform>::post(Box::new(move || {
10465 if let Some((outline, data)) = tree_entry(key) {
10466 let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
10467 if row >= 0 {
10468 unsafe { outline.scrollRowToVisible(row) };
10469 }
10470 }
10471 }));
10472 post_realize_visible_tree_rows(ptr_of(h));
10473 }
10474 None => {}
10475 },
10476 _ => {
10477 if let Some(update) = self.registry.get(kind).map(|r| r.update) {
10478 update(self, h, patch);
10479 }
10480 }
10481 }
10482 }
10483
10484 fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
10486 let f = self.registry.get(kind).and_then(|r| r.release);
10489 if let Some(f) = f {
10490 f(self, h);
10491 }
10492 }
10493 fn release(&mut self, h: Handle) {
10494 LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
10495 self.secondary.retain(|w| {
10499 if ptr_of(&w.content) == ptr_of(&h) {
10500 w.window.close();
10501 day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
10505 false
10506 } else {
10507 true
10508 }
10509 });
10510 TARGETS.with(|m| {
10511 m.borrow_mut().remove(&ptr_of(&h));
10512 });
10513 LIST_STATE.with(|m| {
10514 m.borrow_mut().remove(&ptr_of(&h));
10515 });
10516 TREE_STATE.with(|m| {
10517 m.borrow_mut().remove(&ptr_of(&h));
10518 });
10519 GESTURES.with(|m| {
10520 m.borrow_mut().remove(&ptr_of(&h));
10521 });
10522 NAV_STATE.with(|m| {
10523 if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
10524 unsafe {
10532 nav._split_vc.setNextResponder(None);
10533 let split = nav._split_vc.splitView();
10534 if split.nextResponder().is_some_and(|r| {
10535 core::ptr::eq::<objc2::runtime::AnyObject>(
10536 r.as_ref(),
10537 nav._split_vc.as_ref(),
10538 )
10539 }) {
10540 split.setNextResponder(None);
10541 }
10542 }
10543 }
10544 });
10545 NAV_PAGES.with(|set| {
10546 set.borrow_mut().remove(&ptr_of(&h));
10547 });
10548 SPLIT_STATE.with(|m| {
10549 if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
10550 state.split.setDelegate(None);
10551 }
10552 });
10553 INSPECTOR_STATE.with(|m| {
10554 if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
10555 unsafe {
10558 insp._split_vc.setNextResponder(None);
10559 let split = insp._split_vc.splitView();
10560 if split.nextResponder().is_some_and(|r| {
10561 core::ptr::eq::<objc2::runtime::AnyObject>(
10562 r.as_ref(),
10563 insp._split_vc.as_ref(),
10564 )
10565 }) {
10566 split.setNextResponder(None);
10567 }
10568 }
10569 }
10570 });
10571 NAV_MENUS.with(|m| {
10572 if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
10573 day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
10578 }
10579 });
10580 day_spec::sidetable::sweep(ptr_of(&h));
10586 unsafe { h.removeFromSuperview() };
10587 }
10588
10589 fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
10590 if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
10594 unsafe { content_of(parent).addSubview(child) };
10595 adopt_menu_for_tabs(self.mtm(), child);
10596 return;
10597 }
10598 let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
10601 let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
10602 let handled = NAV_STATE.with(|m| {
10603 let mut m = m.borrow_mut();
10604 let Some(state) = m.get_mut(&ptr_of(parent)) else {
10605 return false;
10606 };
10607 if page_pane == Some(day_spec::props::Pane::List)
10610 && let Some(wrap) = state.list_wrap.as_ref()
10611 {
10612 state.list_page = Some(child.clone());
10613 unsafe {
10614 child.setFrame(wrap.bounds());
10615 child.setAutoresizingMask(
10616 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10617 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10618 );
10619 wrap.addSubview(child);
10620 }
10621 return true;
10622 }
10623 if is_sidebar_page {
10624 state.sidebar_page = Some(child.clone());
10625 }
10626 let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
10632 if !to_pane && let Some(tabs) = state.tabs.as_ref() {
10637 state.pages.push(child.clone());
10638 let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
10639 unsafe {
10640 child.setAutoresizingMask(
10641 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10642 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10643 );
10644 item.setView(Some(child));
10645 tabs.view.addTabViewItem(&item);
10646 }
10647 if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10648 sync_tab_labels(tabs, &titles, state.selected);
10649 }
10650 return true;
10651 }
10652 let (wrap, frame) = if to_pane {
10653 (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10654 } else {
10655 state.pages.push(child.clone());
10656 let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10657 (
10658 &state.detail_wrap,
10659 nav_page_frame(&state.detail_wrap, visible),
10660 )
10661 };
10662 unsafe {
10663 child.setFrame(frame);
10664 child.setAutoresizingMask(
10665 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10666 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10667 );
10668 wrap.addSubview(child);
10669 }
10670 true
10671 });
10672 if handled {
10673 return;
10674 }
10675 let split_pane = SPLIT_STATE.with(|m| {
10678 let m = m.borrow();
10679 let Some(state) = m.get(&ptr_of(parent)) else {
10680 return false;
10681 };
10682 let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10683 let wrap = if second {
10684 &state.second_wrap
10685 } else {
10686 &state.first_wrap
10687 };
10688 unsafe {
10689 child.setFrame(wrap.bounds());
10690 child.setAutoresizingMask(
10691 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10692 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10693 );
10694 wrap.addSubview(child);
10695 }
10696 true
10697 });
10698 if split_pane {
10699 return;
10700 }
10701 let inspected = INSPECTOR_STATE.with(|m| {
10704 let m = m.borrow();
10705 let Some(state) = m.get(&ptr_of(parent)) else {
10706 return false;
10707 };
10708 let panel = INSPECTOR_PANES
10709 .with(|t| t.get(ptr_of(child)))
10710 .unwrap_or(false);
10711 let wrap = if panel {
10712 &state.panel_wrap
10713 } else {
10714 &state.content_wrap
10715 };
10716 unsafe {
10717 child.setFrame(wrap.bounds());
10718 child.setAutoresizingMask(
10719 objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10720 | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10721 );
10722 wrap.addSubview(child);
10723 }
10724 true
10725 });
10726 if !inspected {
10727 unsafe { content_of(parent).addSubview(child) };
10730 }
10731 }
10732
10733 fn remove(&mut self, parent: &Handle, child: &Handle) {
10734 PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10735 let mtm = self.mtm();
10736 NAV_STATE.with(|m| {
10737 if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10738 if let Some(tabs) = state.tabs.as_ref() {
10740 unsafe {
10741 let n = tabs.view.numberOfTabViewItems();
10742 for i in 0..n {
10743 let item = tabs.view.tabViewItemAtIndex(i);
10744 if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10745 tabs.view.removeTabViewItem(&item);
10746 break;
10747 }
10748 }
10749 }
10750 }
10751 state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10752 if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10753 state.sidebar_page = None;
10754 }
10755 }
10756 });
10757 unsafe { child.removeFromSuperview() };
10758 }
10759
10760 fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10761 unsafe { content_of(parent).addSubview(child) };
10762 }
10763
10764 fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10765 match kind {
10766 kinds::LABEL => {
10767 if let Some(tf) = h.downcast_ref::<NSTextField>() {
10768 let w = p.width.unwrap_or(1.0e6);
10769 let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10771 let mut height = s.height.ceil();
10772 if tf.maximumNumberOfLines() == 1 {
10775 thread_local! {
10776 static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10777 }
10778 if let Some(font) = unsafe { tf.font() } {
10779 height = height.min(
10780 METRICS
10781 .with(|metrics| metrics.defaultLineHeightForFont(&font))
10782 .ceil(),
10783 );
10784 }
10785 }
10786 return Size::new(s.width.ceil().min(w), height);
10787 }
10788 Size::ZERO
10789 }
10790 kinds::BUTTON | kinds::TOGGLE => {
10791 let s = unsafe { h.fittingSize() };
10792 Size::new(s.width.ceil(), s.height.ceil())
10793 }
10794 kinds::SLIDER => {
10795 let s = unsafe { h.fittingSize() };
10796 Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10797 }
10798 kinds::PICKER => picker::measure_any(self, h, p),
10799 kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10800 kinds::TEXT_FIELD => {
10801 let s = unsafe { h.fittingSize() };
10802 Size::new(
10803 p.width.unwrap_or(s.width.max(160.0)),
10804 s.height.max(22.0).ceil(),
10805 )
10806 }
10807 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10808 kinds::LIST_ITEM => {
10811 let s = h.fittingSize();
10812 Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10813 }
10814 kinds::PROGRESS => {
10815 let indeterminate = h
10817 .clone()
10818 .downcast::<NSProgressIndicator>()
10819 .map(|pi| unsafe { pi.isIndeterminate() })
10820 .unwrap_or(false);
10821 if indeterminate {
10822 let large = h
10823 .downcast_ref::<NSProgressIndicator>()
10824 .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10825 let side = if large { 32.0 } else { 20.0 };
10826 Size::new(side, side)
10827 } else {
10828 Size::new(p.width.unwrap_or(180.0), 20.0)
10829 }
10830 }
10831 kinds::NAV_MENU => {
10832 let rows = NAV_MENUS.with(|m| {
10833 m.borrow()
10834 .get(&ptr_of(h))
10835 .map(|(_, d)| d.ivars().items.borrow().len())
10836 .unwrap_or(0)
10837 });
10838 Size::new(
10839 p.width.unwrap_or(220.0),
10840 p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10841 )
10842 }
10843 kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10845 _ => {
10846 if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10847 measure(self, h, p)
10848 } else {
10849 let s = unsafe { h.fittingSize() };
10850 Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10851 }
10852 }
10853 }
10854 }
10855
10856 fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10857 unsafe {
10858 h.setWantsLayer(true);
10859 }
10860 let v = h.clone();
10861 with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10862 }
10863
10864 fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10865 TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10868 let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10869 let v = h.clone();
10870 with_appkit_anim(anim, move || {
10871 if let Some(base) = base {
10872 apply_geometry(&v, base, t);
10873 }
10874 });
10875 }
10876
10877 fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10878 if let Some(label) = h.downcast_ref::<DayLabel>() {
10879 label.ivars().selectable.set(selectable);
10880 label.set_links(label.ivars().has_links.get());
10881 } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10882 unsafe { tf.setSelectable(selectable) };
10883 }
10884 None
10885 }
10886
10887 fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10888 let node = text_field_node(h)?;
10889 let old = h.downcast_ref::<NSTextField>()?;
10890 let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10893 .then(|| self.swap_text_field(h, old, node, traits.secure));
10894 let tf = swapped.as_deref().unwrap_or(old);
10895 unsafe {
10896 tf.setEditable(!traits.read_only);
10899 tf.setSelectable(true);
10900 }
10901 let content_type = match traits.purpose {
10905 InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10906 InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10907 InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10908 InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10909 InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10910 InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10911 InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10912 InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10913 InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10914 };
10915 unsafe {
10916 tf.setContentType(content_type);
10917 tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10920 }
10921 swapped.map(view_of)
10924 }
10925
10926 fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10927 let key = Retained::as_ptr(h) as usize;
10928 if cursor == Cursor::Default {
10929 if let Some((owner, area)) = self.cursors.remove(&key) {
10931 unsafe { h.removeTrackingArea(&area) };
10932 if owner.ivars().hiding.replace(false) {
10933 NSCursor::unhide();
10934 }
10935 }
10936 return;
10937 }
10938 let hidden = cursor == Cursor::None;
10939 let shape = if hidden { None } else { ns_cursor(&cursor) };
10940 let mtm = self.mtm;
10941 let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10942 let owner = DayCursorOwner::new(mtm);
10943 let opts = NSTrackingAreaOptions::CursorUpdate
10946 | NSTrackingAreaOptions::MouseEnteredAndExited
10947 | NSTrackingAreaOptions::ActiveInKeyWindow
10948 | NSTrackingAreaOptions::InVisibleRect;
10949 let any: &objc2::runtime::AnyObject = &owner;
10950 let area = unsafe {
10951 NSTrackingArea::initWithRect_options_owner_userInfo(
10952 NSTrackingArea::alloc(),
10953 NSRect::ZERO,
10954 opts,
10955 Some(any),
10956 None,
10957 )
10958 };
10959 unsafe { h.addTrackingArea(&area) };
10960 (owner, area)
10961 });
10962 let changed = {
10963 let iv = owner.ivars();
10964 let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10965 (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10966 (None, None) => true,
10967 _ => false,
10968 };
10969 *iv.cursor.borrow_mut() = shape;
10970 let was_hidden = iv.hidden.replace(hidden);
10971 !same || was_hidden != hidden
10972 };
10973 if changed && let Some(w) = h.window() {
10976 unsafe { w.invalidateCursorRectsForView(h) };
10977 }
10978 }
10979
10980 fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10994 if !day_spec::kind_has_baseline(kind) {
10995 return None;
10996 }
10997 let current = unsafe { h.frame() };
11000 if (current.size.height - size.height).abs() > 0.5 {
11001 unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
11002 }
11003 let insets = unsafe { h.alignmentRectInsets() };
11004 let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
11005 let font = h
11006 .downcast_ref::<NSControl>()
11007 .and_then(|c| unsafe { c.font() });
11008 let offset = match font {
11009 Some(_) if kind == kinds::TEXT_AREA => reported,
11012 Some(f) => {
11013 let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
11014 let line = ascender - descender;
11015 let align_h = (size.height - insets.top - insets.bottom).max(0.0);
11016 insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
11017 }
11018 None => reported,
11019 };
11020 (offset > 0.0 && offset < size.height).then_some(offset)
11022 }
11023
11024 fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
11025 if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
11027 return;
11028 }
11029 let r = NSRect::new(
11032 NSPoint::new(frame.origin.x, frame.origin.y),
11033 NSSize::new(frame.size.width, frame.size.height),
11034 );
11035 if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
11040 let strip = unsafe { split.superview() }
11044 .and_then(|sup| {
11045 let content = unsafe { sup.window() }?.contentView()?;
11046 let mut ancestor = Some(sup.clone());
11050 while let Some(view) = ancestor {
11051 if std::ptr::eq(&*view, &*content) {
11052 break;
11053 }
11054 if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
11055 return None; }
11057 ancestor = unsafe { view.superview() };
11058 }
11059 let point = unsafe {
11060 sup.convertPoint_toView(
11061 NSPoint::new(frame.origin.x, frame.origin.y),
11062 Some(&content),
11063 )
11064 };
11065 (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
11066 })
11067 .unwrap_or(0.0);
11068 let r = NSRect::new(
11069 NSPoint::new(r.origin.x, r.origin.y - strip),
11070 NSSize::new(r.size.width, r.size.height + strip),
11071 );
11072 let wraps = NAV_STATE.with(|m| {
11073 m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
11074 (s.title_strip != strip).then(|| {
11075 s.title_strip = strip;
11076 let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
11077 w.extend(s.list_wrap.clone());
11078 w
11079 })
11080 })
11081 });
11082 let first = NAV_STATE.with(|m| {
11083 m.borrow_mut()
11084 .get_mut(&ptr_of(h))
11085 .map(|s| {
11086 if !s.presentation.is_split() {
11087 return (false, None);
11088 }
11089 let sidebar = !std::mem::replace(&mut s.positioned, true);
11090 (sidebar, take_list_placement(s))
11095 })
11096 .unwrap_or((false, None))
11097 });
11098 unsafe {
11099 split.setFrame(r);
11100 split.layoutSubtreeIfNeeded();
11101 }
11102 for wrap in wraps.iter().flatten() {
11105 place_below_strip(wrap, strip);
11106 }
11107 unsafe {
11108 if first.0 {
11109 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
11110 }
11111 if let Some(w) = first.1 {
11116 split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
11117 }
11118 }
11119 } else {
11120 BASE_FRAMES.with(|m| {
11121 m.insert(
11122 ptr_of(h),
11123 [
11124 frame.origin.x,
11125 frame.origin.y,
11126 frame.size.width,
11127 frame.size.height,
11128 ],
11129 )
11130 });
11131 match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
11133 Some(t) => apply_geometry(
11134 h,
11135 [
11136 frame.origin.x,
11137 frame.origin.y,
11138 frame.size.width,
11139 frame.size.height,
11140 ],
11141 t,
11142 ),
11143 None => unsafe { h.setFrame(r) },
11144 }
11145 }
11146 }
11147
11148 fn set_scroll_content(&mut self, h: &Handle, content: Size) {
11149 if let Some(sv) = h.downcast_ref::<NSScrollView>()
11150 && let Some(doc) = unsafe { sv.documentView() }
11151 {
11152 unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
11153 }
11154 }
11155
11156 fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
11158 day_spec::RowMetrics {
11159 insets: day_spec::Insets {
11160 top: 4.0,
11161 leading: 8.0,
11162 bottom: 4.0,
11163 trailing: 8.0,
11164 },
11165 min_height: 28.0,
11166 }
11167 }
11168
11169 fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
11170 if let Some(sv) = h.downcast_ref::<NSScrollView>()
11171 && let Some(doc) = unsafe { sv.documentView() }
11172 {
11173 unsafe {
11174 doc.scrollRectToVisible(NSRect::new(
11175 NSPoint::new(target.origin.x, target.origin.y),
11176 NSSize::new(target.size.width, target.size.height),
11177 ))
11178 };
11179 }
11180 }
11181
11182 fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
11183 let Some(window) = h.window() else { return };
11184 let list = list_entry(ptr_of(h));
11186 let responder: &NSResponder = match &list {
11187 Some((table, _)) => table,
11188 None => h,
11189 };
11190 let responder_ptr = responder as *const NSResponder as usize;
11191 if focused {
11192 window.makeFirstResponder(Some(responder));
11193 return;
11194 }
11195 let owns = window
11198 .firstResponder()
11199 .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
11200 || owns_first_responder(&window, h);
11201 if owns {
11202 window.makeFirstResponder(None);
11203 }
11204 }
11205
11206 fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
11207 if focusable {
11210 FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
11211 } else {
11212 FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
11213 }
11214 }
11215
11216 fn set_event_sink(&mut self, sink: EventSink) {
11217 SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
11218 }
11219
11220 fn set_edit_state(&mut self, state: &day_spec::EditState) {
11221 EDIT_STATE.with(|s| s.set(*state));
11222 }
11223
11224 fn modifiers(&mut self) -> day_spec::Modifiers {
11225 let f = NSEvent::modifierFlags_class();
11226 day_spec::Modifiers {
11227 shift: f.contains(NSEventModifierFlags::Shift),
11228 primary: f.contains(NSEventModifierFlags::Command),
11229 alt: f.contains(NSEventModifierFlags::Option),
11230 }
11231 }
11232
11233 fn set_undo_state(&mut self, state: &day_spec::UndoState) {
11234 let front = undo_front(self.mtm);
11235 *front.ivars().state.borrow_mut() = state.clone();
11236 }
11237
11238 fn attach_list(&mut self, host: &Handle, source: ListSource) {
11239 let key = ptr_of(host);
11240 if let Some((table, data)) = list_entry(key) {
11241 data.ivars().source.replace(Some(source));
11242 unsafe { table.reloadData() };
11244 }
11245 post_realize_visible_rows(key);
11250 }
11251
11252 fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
11253 let key = ptr_of(host);
11254 if let Some((outline, data)) = tree_entry(key) {
11255 data.ivars().source.replace(Some(source));
11256 unsafe { outline.reloadData() };
11258 }
11259 <AppKit as Platform>::post(Box::new(move || {
11262 if let Some((outline, _)) = tree_entry(key) {
11263 unsafe { outline.layoutSubtreeIfNeeded() };
11264 }
11265 }));
11266 }
11267
11268 fn adopt(&mut self, raw: RawHandle) -> Handle {
11269 let ptr = raw as *mut NSView;
11273 unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
11274 }
11275
11276 fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
11277 self.edit_toolbar(h, ops)
11278 }
11279
11280 fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
11281 self.patch_toolbar(h, patch);
11282 }
11283
11284 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
11285 let mtm = self.mtm;
11286 if self.menu_escape_monitor.is_none() {
11287 let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
11288 ffi_guard::contain(event.as_ptr(), || {
11289 let event_ref = unsafe { event.as_ref() };
11290 let app = NSApplication::sharedApplication(mtm);
11291 if app.modalWindow().is_none()
11294 && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
11295 && unsafe { event_ref.charactersIgnoringModifiers() }
11296 .is_some_and(|s| s.to_string() == "\u{1b}")
11297 && app
11298 .mainMenu()
11299 .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
11300 {
11301 std::ptr::null_mut()
11302 } else {
11303 event.as_ptr()
11304 }
11305 })
11306 });
11307 self.menu_escape_monitor = unsafe {
11308 NSEvent::addLocalMonitorForEventsMatchingMask_handler(
11309 objc2_app_kit::NSEventMask::KeyDown,
11310 &block,
11311 )
11312 }
11313 .map(MenuEscapeMonitor);
11314 }
11315 let app = NSApplication::sharedApplication(mtm);
11316 let menubar = NSMenu::new(mtm);
11317 let mut items = items.to_vec();
11320 let about = extract_app_role(&mut items, day_spec::MenuRole::About);
11321 let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
11322 let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
11323 let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
11324 let services =
11325 install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
11326 let items =
11331 day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
11332 let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
11333 for item in &items {
11335 match item {
11336 day_spec::MenuItem::Submenu { label, items, role } => {
11337 let sub = build_ns_menu(mtm, label, items);
11338 let it = NSMenuItem::new(mtm);
11339 if *role == Some(day_spec::MenuBarRole::Help)
11343 || *label == day_localization::t(day_localization::key::day_help)
11344 {
11345 help_menu = Some((label.clone(), sub));
11346 continue;
11347 }
11348 it.setTitle(&NSString::from_str(label));
11349 it.setSubmenu(Some(&sub));
11350 menubar.addItem(&it);
11351 }
11352 other => {
11353 let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
11355 let it = NSMenuItem::new(mtm);
11356 it.setSubmenu(Some(&sub));
11357 menubar.addItem(&it);
11358 }
11359 }
11360 }
11361 if !model_has_role(&items, day_spec::MenuRole::Minimize) {
11364 install_windows_menu(mtm, &app, &menubar);
11365 }
11366 if let Some((label, help)) = help_menu {
11367 let it = NSMenuItem::new(mtm);
11368 it.setTitle(&NSString::from_str(&label));
11369 it.setSubmenu(Some(&help));
11370 menubar.addItem(&it);
11371 unsafe { app.setHelpMenu(Some(&help)) };
11374 }
11375 app.setMainMenu(Some(&menubar));
11376 unsafe { app.setServicesMenu(Some(&services)) };
11377 }
11378
11379 fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
11380 let Some(view) = h.downcast_ref::<NSView>() else {
11381 return;
11382 };
11383 if items.is_empty() {
11384 unsafe { view.setMenu(None) };
11385 return;
11386 }
11387 let menu = build_ns_menu(self.mtm, "", items);
11388 unsafe { view.setMenu(Some(&menu)) };
11394 fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
11395 for sub in v.subviews() {
11396 unsafe { sub.setMenu(Some(menu)) };
11397 apply_to_subviews(&sub, menu);
11398 }
11399 }
11400 apply_to_subviews(view, &menu);
11401 }
11402
11403 fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
11404 transfer::source(h, source);
11405 }
11406 fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
11407 transfer::target(h, target);
11408 }
11409 fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11410 CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
11413 }
11414
11415 fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11416 let Some(btn) = h.downcast_ref::<NSButton>() else {
11417 return;
11418 };
11419 unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
11423 BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
11424 }
11425
11426 fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
11427 let key = ptr_of(h);
11428 if kind == day_spec::GestureKind::Pan {
11432 PAN_NODES.with(|t| t.insert(key, node));
11433 install_container_pan_monitor();
11434 return;
11435 }
11436 if kind == day_spec::GestureKind::Rotate {
11440 ROTATE_NODES.with(|t| t.insert(key, node));
11441 return;
11442 }
11443 if kind == day_spec::GestureKind::Hover {
11447 let first = HOVER_NODES.with(|t| t.get(key)).is_none();
11451 HOVER_NODES.with(|t| t.insert(key, node));
11452 if first {
11453 install_tracking_area(h);
11454 }
11455 return;
11456 }
11457 let already = GESTURES.with(|m| {
11459 m.borrow()
11460 .get(&key)
11461 .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
11462 });
11463 if already {
11464 return;
11465 }
11466 let mtm = self.mtm;
11467 let target = DayGesture::new(mtm, node, kind);
11468 let recognizer: Retained<NSGestureRecognizer> = unsafe {
11469 match kind {
11470 day_spec::GestureKind::Drag => {
11471 Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
11472 NSPanGestureRecognizer::alloc(mtm),
11473 Some(&target),
11474 Some(sel!(fire:)),
11475 ))
11476 }
11477 day_spec::GestureKind::Pinch => Retained::into_super(
11478 objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
11479 objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
11480 Some(&target),
11481 Some(sel!(fire:)),
11482 ),
11483 ),
11484 _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
11485 NSClickGestureRecognizer::alloc(mtm),
11486 Some(&target),
11487 Some(sel!(fire:)),
11488 )),
11489 }
11490 };
11491 unsafe { h.addGestureRecognizer(&recognizer) };
11492 GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
11493 }
11494
11495 fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
11496 unsafe {
11497 if let Some(id) = &a11y.identifier {
11498 h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
11499 }
11500 if let Some(label) = &a11y.label {
11501 h.setAccessibilityLabel(Some(&NSString::from_str(label)));
11502 APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
11503 } else {
11504 APP_LABELED.with(|t| t.remove(ptr_of(h)));
11505 }
11506 if let Some(hint) = &a11y.hint {
11507 h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
11508 }
11509 if let Some(value) = &a11y.value {
11510 let ns = NSString::from_str(value);
11511 h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
11512 }
11513 if let Some(role) = ns_role(a11y.role) {
11516 h.setAccessibilityRole(Some(role));
11517 }
11518 if a11y.role == day_spec::Role::Tab {
11519 h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
11520 }
11521 if let Some(on) = a11y.selected {
11522 h.setAccessibilitySelected(on);
11523 }
11524 if a11y.hidden {
11530 h.setAccessibilityElement(false);
11531 h.setAccessibilityChildren(Some(&NSArray::new()));
11532 }
11533 }
11534 }
11535
11536 fn announce(&mut self, text: &str, urgent: bool) {
11540 use objc2_app_kit::{
11541 NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
11542 NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
11543 NSAccessibilityPriorityLevel,
11544 };
11545 let app = NSApplication::sharedApplication(self.mtm());
11546 let window = primary_content().and_then(|content| content.window());
11547 let element: &objc2::runtime::AnyObject = match &window {
11548 Some(window) => window,
11549 None => &app,
11550 };
11551 let priority = if urgent {
11553 NSAccessibilityPriorityLevel::High
11554 } else {
11555 NSAccessibilityPriorityLevel::Medium
11556 };
11557 let announcement = NSString::from_str(text);
11558 let priority = NSNumber::new_isize(priority.0);
11559 let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
11560 unsafe {
11563 let user_info = NSDictionary::from_slices::<NSString>(
11564 &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
11565 &values,
11566 );
11567 NSAccessibilityPostNotificationWithUserInfo(
11568 element,
11569 NSAccessibilityAnnouncementRequestedNotification,
11570 Some(&user_info),
11571 );
11572 }
11573 }
11574
11575 fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
11576 unsafe {
11577 let role = h
11578 .accessibilityRole()
11579 .map(|r| day_role_from_ns(&r.to_string()))
11580 .unwrap_or(day_spec::Role::None);
11581 let picker = picker::read_native(h);
11584 day_spec::NativeSnapshot {
11585 found: true,
11586 role,
11587 label: h.accessibilityLabel().map(|s| s.to_string()),
11588 value: h
11589 .accessibilityValue()
11590 .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
11591 identifier: h
11592 .accessibilityIdentifier()
11593 .map(|s| s.to_string())
11594 .filter(|s| !s.is_empty()),
11595 text: match &picker {
11596 Some((text, _)) => text.clone(),
11597 None => native_text(h),
11598 },
11599 number: native_number(h),
11600 checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
11601 match sw.state() {
11602 s if s == NSControlStateValueOn => Some(true),
11603 s if s == NSControlStateValueOff => Some(false),
11604 _ => None,
11606 }
11607 } else if let Some(btn) = h.downcast_ref::<NSButton>() {
11608 BUTTON_SELECTED
11611 .with(|m| m.borrow().contains_key(&ptr_of(h)))
11612 .then(|| btn.state() == NSControlStateValueOn)
11613 } else {
11614 None
11615 },
11616 enabled: match (&picker, h.downcast_ref::<NSControl>()) {
11619 (Some((_, on)), _) => *on,
11620 (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
11621 (None, Some(c)) => Some(c.isEnabled()),
11622 (None, None) => None,
11623 },
11624 visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
11626 frame: native_frame(h),
11627 }
11628 }
11629 }
11630
11631 fn request_frame(
11632 &mut self,
11633 host: &Handle,
11634 cb: day_spec::FrameCallback,
11635 ) -> day_spec::CancelFrame {
11636 frame::request(host, cb)
11637 }
11638
11639 fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
11640 OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
11641 unsafe { h.setNeedsDisplay(true) };
11642 }
11643 fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
11644 NAV_STATE.with(|m| {
11645 let m = m.borrow();
11646 let Some(st) = m.get(&ptr_of(host)) else {
11647 return false;
11648 };
11649 if !matches!(
11652 st.presentation,
11653 NavPresentation::Split | NavPresentation::Rail
11654 ) {
11655 return false;
11656 }
11657 let item = &st.sidebar_item;
11658 let collapsed = unsafe { item.isCollapsed() };
11664 unsafe { item.setCollapsed(!collapsed) };
11665 true
11666 })
11667 }
11668
11669 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11670 let content = self.content.as_ref().ok_or("no window content")?;
11671 match self.shown_document_content(content) {
11672 Some(shown) => snapshot_view(&shown),
11673 None => snapshot_view(content),
11674 }
11675 }
11676
11677 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11683 use objc2::AllocAnyThread as _;
11684 let data = NSData::with_bytes(bytes);
11685 let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11686 else {
11687 emit(
11688 WINDOW_NODE,
11689 Event::ImageDecoded {
11690 req,
11691 result: Err(day_spec::ImageError::Decode),
11692 },
11693 );
11694 return;
11695 };
11696 let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11697 let info = day_spec::BitmapInfo {
11698 pixels: Size::new(w, h),
11699 scale: 1.0,
11702 format: day_spec::ImageFormat::sniff(bytes),
11703 has_alpha: unsafe { rep.hasAlpha() },
11704 };
11705 let image = unsafe {
11709 objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11710 };
11711 unsafe { image.addRepresentation(&rep) };
11712 BITMAPS.with(|m| {
11713 m.borrow_mut().insert(
11714 id.0,
11715 AppKitBitmap {
11716 image,
11717 rep: Some(rep),
11718 info,
11719 },
11720 )
11721 });
11722 emit(
11723 WINDOW_NODE,
11724 Event::ImageDecoded {
11725 req,
11726 result: Ok(info),
11727 },
11728 );
11729 }
11730
11731 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11732 BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11733 }
11734
11735 fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11742 let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11743 let mut out = day_spec::ImageProperties::default();
11744 let size = unsafe { rep.size() };
11745 if size.width > 0.0 {
11746 let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11747 if (dpi - 72.0).abs() > 0.5 {
11750 out.dpi = Some(dpi);
11751 }
11752 }
11753 if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11757 let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11758 for key in keys.iter() {
11759 let value: Option<Retained<objc2::runtime::AnyObject>> =
11760 unsafe { msg_send![&*exif, objectForKey: &*key] };
11761 let Some(value) = value else { continue };
11762 let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11763 let (k, v) = (key.to_string(), text.to_string());
11764 match k.as_str() {
11765 "Orientation" => out.orientation = v.parse().ok(),
11766 "DateTimeOriginal" => out.created = Some(v.clone()),
11767 _ => {}
11768 }
11769 out.extra.push((k, v));
11772 }
11773 }
11774 Some(out)
11775 }
11776
11777 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11781 use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11782 vec![Png, Jpeg, Tiff, Bmp, Gif]
11783 }
11784
11785 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11786 let result = encode_bitmap(id, spec);
11787 emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11788 }
11789
11790 fn release_image(&mut self, id: day_spec::BitmapId) {
11791 release_bitmap(id);
11792 }
11793
11794 fn render_bitmap(
11804 &mut self,
11805 req: u64,
11806 id: day_spec::BitmapId,
11807 ops: &[DrawOp],
11808 size: Size,
11809 scale: f64,
11810 ) {
11811 let resources = Sendable(OffscreenResources::collect(ops));
11812 let ops = ops.to_vec();
11813 day_spec::offscreen::spawn(move || {
11814 let resources = resources;
11816 let painted = day_spec::ffi_guard::contain(
11817 Err(day_spec::ExportError::Failed(
11818 "the offscreen painter panicked".into(),
11819 )),
11820 || {
11821 let started = std::time::Instant::now();
11822 let painted = resources
11823 .0
11824 .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
11825 log::debug!(
11827 "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
11828 size.width * scale,
11829 size.height * scale,
11830 started.elapsed().as_secs_f64() * 1000.0,
11831 ops.len()
11832 );
11833 painted
11834 },
11835 );
11836 let painted = Sendable(painted);
11837 <AppKit as Platform>::post(Box::new(move || {
11838 let painted = painted;
11839 let result = painted.0.map(|cg_image| {
11840 let bitmap = bitmap_from_cgimage(&cg_image, scale);
11841 let info = bitmap.info;
11842 BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11843 info
11844 });
11845 emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11846 }));
11847 });
11848 }
11849
11850 fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11851 let result = render_pdf_bytes(pages, info);
11852 emit(WINDOW_NODE, Event::PdfRendered { req, result });
11853 }
11854
11855 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11859 use day_spec::FontWeight as W;
11860 let mtm =
11861 objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11862 let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11863 let mut out = Vec::new();
11864 for family in unsafe { manager.availableFontFamilies() }.iter() {
11865 let name = family.to_string();
11866 if name.starts_with('.') {
11867 continue;
11868 }
11869 let mut faces = Vec::new();
11870 if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11871 for member in members.iter() {
11872 if member.count() < 4 {
11873 continue;
11874 }
11875 let style = member
11876 .objectAtIndex(1)
11877 .downcast_ref::<NSString>()
11878 .map(|s| s.to_string())
11879 .unwrap_or_default();
11880 let weight = member
11881 .objectAtIndex(2)
11882 .downcast_ref::<objc2_foundation::NSNumber>()
11883 .map(|n| n.integerValue())
11884 .unwrap_or(5);
11885 let traits = member
11886 .objectAtIndex(3)
11887 .downcast_ref::<objc2_foundation::NSNumber>()
11888 .map(|n| n.integerValue())
11889 .unwrap_or(0);
11890 let weight = match weight {
11891 ..=2 => W::UltraLight,
11892 3 => W::Thin,
11893 4 => W::Light,
11894 5 => W::Regular,
11895 6 => W::Medium,
11896 7 | 8 => W::Semibold,
11897 9 => W::Bold,
11898 10 | 11 => W::Heavy,
11899 _ => W::Black,
11900 };
11901 let italic = traits & 0x1 != 0; faces.push(day_spec::FontFace {
11903 name: if style.is_empty() {
11904 day_spec::FontFace::synthesized_name(weight, italic)
11905 } else {
11906 style
11907 },
11908 weight,
11909 italic,
11910 });
11911 }
11912 }
11913 out.push(day_spec::FontFamilyInfo {
11914 family: name,
11915 faces,
11916 });
11917 }
11918 out
11919 }
11920
11921 fn measure_text(
11924 &mut self,
11925 text: &str,
11926 size: f64,
11927 font: &day_spec::CanvasFont,
11928 ) -> Option<day_spec::TextMetrics> {
11929 let nsfont = canvas_nsfont(size, font);
11930 let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11931 let ns = NSString::from_str(text);
11932 let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11933 let unbounded = NSSize::new(f64::MAX, f64::MAX);
11937 let ink: NSRect = unsafe {
11938 msg_send![
11939 &ns,
11940 boundingRectWithSize: unbounded,
11941 options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11942 attributes: &*attrs,
11943 ]
11944 };
11945 Some(day_spec::TextMetrics::from_baseline(
11946 sz.width,
11947 nsfont.ascender(),
11948 sz.height - nsfont.ascender(),
11949 nsfont.capHeight(),
11950 day_spec::Rect::new(
11951 ink.origin.x,
11952 -(ink.origin.y + ink.size.height),
11953 ink.size.width,
11954 ink.size.height,
11955 ),
11956 ))
11957 }
11958
11959 fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11960 let content = self.content.as_ref().ok_or("no window content")?;
11961 match self.shown_document_content(content) {
11962 Some(shown) => snapshot_view_chrome(&shown),
11963 None => snapshot_view_chrome(content),
11964 }
11965 }
11966
11967 fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11968 snapshot_view(host)
11969 }
11970
11971 fn open_window(
11972 &mut self,
11973 id: NodeId,
11974 options: &WindowOptions,
11975 kind: day_spec::WindowKind,
11976 ) -> day_spec::WindowOpenReply<Handle> {
11977 let prefs = kind.is_panel();
11978 let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11979 if prefs {
11980 window.center();
11983 unsafe { window.setExcludedFromWindowsMenu(true) };
11984 } else {
11985 let from = match self.cascade {
11993 Some(p) => p,
11994 None => self
11995 .window
11996 .as_ref()
11997 .map(|w| {
11998 let f = w.frame();
11999 let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
12000 unsafe { w.cascadeTopLeftFromPoint(top_left) }
12003 })
12004 .unwrap_or(NSPoint::new(0.0, 0.0)),
12005 };
12006 self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
12007 }
12008 window_chrome::place(&window, options.placement);
12009 if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
12014 center_on_screen_of(&window, self.window.as_deref());
12015 }
12016 let _ = pin_below_title_bar(&window);
12019 if !options.start_hidden {
12020 window.makeKeyAndOrderFront(None);
12021 }
12022 mark_tree_needs_display(&content);
12025 self.secondary.push(SecondaryWin {
12026 window,
12027 delegate,
12028 content: content.clone(),
12029 });
12030 day_spec::WindowOpenReply::Open(content)
12031 }
12032
12033 fn native_window_tabs(&self) -> bool {
12034 true
12035 }
12036 fn group_windows(&mut self, hosts: &[Handle]) {
12037 let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
12038 let Some(first) = windows.first() else {
12039 return;
12040 };
12041 unsafe {
12042 NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
12043 }
12044 for window in windows.iter().skip(1) {
12046 unsafe {
12047 first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
12048 }
12049 }
12050 if let Some(group) = first.tabGroup() {
12051 if !group.isTabBarVisible() {
12052 unsafe {
12053 first.toggleTabBar(None);
12054 }
12055 }
12056 for (i, window) in windows.iter().enumerate() {
12057 group.insertWindow_atIndex(window, i as isize);
12058 }
12059 }
12060 for window in &windows {
12063 if let Some(size) = pin_below_title_bar(window) {
12064 let node = window
12065 .delegate()
12066 .and_then(|d| d.downcast::<DayWinDelegate>().ok())
12067 .and_then(|d| d.ivars().node)
12068 .unwrap_or(WINDOW_NODE);
12069 emit(node, Event::WindowResized(size));
12070 }
12071 }
12072 }
12073 fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
12074 let Some(window) = self.ns_window_for(host) else {
12075 return Vec::new();
12076 };
12077 let windows = window.tabGroup().map(|g| g.windows());
12078 let Some(windows) = windows else {
12079 return Vec::new();
12080 };
12081 windows
12082 .iter()
12083 .filter_map(|window| {
12084 self.secondary
12085 .iter()
12086 .find(|w| std::ptr::eq(&*w.window, &*window))
12087 .and_then(|w| w.delegate.ivars().node)
12088 })
12089 .collect()
12090 }
12091
12092 fn close_window(&mut self, host: &Handle) {
12093 if let Some(w) = self
12096 .secondary
12097 .iter()
12098 .find(|w| ptr_of(&w.content) == ptr_of(host))
12099 {
12100 w.window.close();
12101 }
12102 }
12103
12104 fn focus_window(&mut self, host: &Handle) {
12105 if let Some(w) = self
12106 .secondary
12107 .iter()
12108 .find(|w| ptr_of(&w.content) == ptr_of(host))
12109 {
12110 w.window.makeKeyAndOrderFront(None);
12111 }
12112 }
12113
12114 fn fit_window(&mut self, host: &Handle, size: Size) {
12115 let Some(w) = self
12116 .secondary
12117 .iter()
12118 .find(|w| ptr_of(&w.content) == ptr_of(host))
12119 else {
12120 return;
12121 };
12122 unsafe {
12123 w.window
12127 .setContentSize(NSSize::new(size.width, size.height));
12128 let mask = w.window.styleMask();
12132 w.window
12133 .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
12134 w.window.center();
12135 }
12136 center_on_screen_of(&w.window, self.window.as_deref());
12137 }
12138
12139 fn set_window_title(&mut self, host: &Handle, title: &str) {
12140 if let Some(w) = self
12141 .secondary
12142 .iter()
12143 .find(|w| ptr_of(&w.content) == ptr_of(host))
12144 {
12145 w.window.setTitle(&NSString::from_str(title));
12146 return;
12147 }
12148 if self
12152 .content
12153 .as_ref()
12154 .is_some_and(|c| ptr_of(c) == ptr_of(host))
12155 && let Some(w) = self.window.as_ref()
12156 {
12157 w.setTitle(&NSString::from_str(title));
12158 }
12159 }
12160
12161 fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
12162 use day_spec::WindowChange as C;
12163 let Some(window) = self.ns_window_for(host) else {
12164 return;
12165 };
12166 match change {
12167 C::State(state) => set_ns_window_state(&window, *state),
12168 C::ContentProtected(on) => window.setSharingType(if *on {
12170 objc2_app_kit::NSWindowSharingType::None
12171 } else {
12172 objc2_app_kit::NSWindowSharingType::ReadOnly
12173 }),
12174 other => window_chrome::apply_property(&window, other),
12175 }
12176 }
12177
12178 fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
12179 self.ns_window_for(host)
12180 .map(|w| window_chrome::frame_of(&w))
12181 }
12182
12183 fn monitors(&self) -> Vec<day_spec::Monitor> {
12184 window_chrome::monitors(self.mtm)
12185 }
12186
12187 fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
12190
12191 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
12192 dock::set_app_items(self.mtm, items);
12193 }
12194
12195 fn set_drag_region(&mut self, h: &Handle, drag: bool) {
12196 window_chrome::set_drag_region(h, drag);
12197 }
12198
12199 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
12200 status_item::set_items(self.mtm, items);
12201 }
12202
12203 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
12204 status_item::set_progress(self.mtm, progress);
12205 }
12206
12207 fn set_dock_visible(&mut self, visible: bool) {
12208 status_item::set_dock_visible(self.mtm, visible);
12209 }
12210
12211 fn set_keep_running(&mut self, keep: bool) {
12212 status_item::set_keep_running(keep);
12213 }
12214
12215 fn quit_app(&mut self) {
12216 let app = NSApplication::sharedApplication(self.mtm);
12217 unsafe { app.terminate(None) };
12218 }
12219
12220 fn present(&mut self, req: u64, spec: &present::PresentSpec) {
12221 use present::PresentSpec;
12222 let mtm = self.mtm;
12223 let app = NSApplication::sharedApplication(mtm);
12227 let key = app.keyWindow().filter(|k| {
12228 let mut owner = k.clone();
12229 while let Some(parent) = owner.sheetParent() {
12230 owner = parent;
12231 }
12232 self.window
12233 .as_deref()
12234 .is_some_and(|w| std::ptr::eq(w, &*owner))
12235 || self
12236 .secondary
12237 .iter()
12238 .any(|s| std::ptr::eq(&*s.window, &*owner))
12239 });
12240 let Some(mut window) = key.or_else(|| self.window.clone()) else {
12241 emit(
12242 WINDOW_NODE,
12243 Event::PresentResult {
12244 req,
12245 result: present::PresentResult::Dismissed,
12246 },
12247 );
12248 return;
12249 };
12250 while let Some(sheet) = window.attachedSheet() {
12252 window = sheet;
12253 }
12254 match spec {
12256 PresentSpec::OpenFile {
12257 filters, multiple, ..
12258 } => {
12259 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12260 unsafe {
12261 panel.setCanChooseFiles(true);
12262 panel.setCanChooseDirectories(false);
12263 panel.setAllowsMultipleSelection(*multiple);
12264 panel.setMessage(Some(&NSString::from_str(spec.title())));
12265 }
12266 apply_allowed_file_types(&panel, filters);
12267 let p = panel.clone();
12268 let handler: block2::RcBlock<dyn Fn(isize)> =
12271 block2::RcBlock::new(move |resp: isize| {
12272 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12273 });
12274 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12275 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12276 return;
12277 }
12278 PresentSpec::OpenFolder { .. } => {
12280 let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12281 unsafe {
12282 panel.setCanChooseFiles(false);
12283 panel.setCanChooseDirectories(true);
12284 panel.setCanCreateDirectories(true);
12285 panel.setAllowsMultipleSelection(false);
12286 panel.setMessage(Some(&NSString::from_str(spec.title())));
12287 }
12288 let p = panel.clone();
12289 let handler: block2::RcBlock<dyn Fn(isize)> =
12290 block2::RcBlock::new(move |resp: isize| {
12291 ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12292 });
12293 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12294 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12295 return;
12296 }
12297 PresentSpec::SaveFile { suggested_name, .. } => {
12298 let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
12299 unsafe {
12300 panel.setMessage(Some(&NSString::from_str(spec.title())));
12301 panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
12302 }
12303 apply_allowed_file_types(&panel, spec.filters());
12304 let p = panel.clone();
12305 let handler: block2::RcBlock<dyn Fn(isize)> =
12306 block2::RcBlock::new(move |resp: isize| {
12307 ffi_guard::contain((), || emit_panel_result(req, resp, &p));
12309 });
12310 unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12311 PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
12312 return;
12313 }
12314 _ => {}
12315 }
12316 let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
12317 unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
12318 if let Some(msg) = spec.message() {
12319 unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
12320 }
12321 let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
12323 PresentSpec::Dialog { buttons, .. } => {
12324 if buttons
12325 .iter()
12326 .any(|b| b.role == present::ButtonRole::Destructive)
12327 {
12328 unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
12329 }
12330 for b in buttons {
12331 unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
12332 }
12333 block2::RcBlock::new(move |resp: isize| {
12334 ffi_guard::contain((), || {
12335 let idx = resp - 1000;
12337 emit(
12338 WINDOW_NODE,
12339 Event::PresentResult {
12340 req,
12341 result: present::PresentResult::Button(idx as i64),
12342 },
12343 );
12344 PRESENT_ALERTS.with(|m| {
12345 m.borrow_mut().remove(&req);
12346 });
12347 })
12348 })
12349 }
12350 PresentSpec::Prompt {
12351 placeholder,
12352 initial,
12353 ok,
12354 cancel,
12355 ..
12356 } => {
12357 let tf = unsafe { NSTextField::new(mtm) };
12358 unsafe {
12359 tf.setFrame(NSRect::new(
12360 NSPoint::new(0.0, 0.0),
12361 NSSize::new(260.0, 24.0),
12362 ));
12363 tf.setEditable(true);
12364 tf.setBezeled(true);
12365 tf.setStringValue(&NSString::from_str(initial));
12366 tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
12367 alert.setAccessoryView(Some(&tf));
12368 alert.addButtonWithTitle(&NSString::from_str(ok)); alert.addButtonWithTitle(&NSString::from_str(cancel)); }
12371 block2::RcBlock::new(move |resp: isize| {
12372 ffi_guard::contain((), || {
12373 let result = if resp == 1000 {
12374 present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
12375 } else {
12376 present::PresentResult::Dismissed
12377 };
12378 emit(WINDOW_NODE, Event::PresentResult { req, result });
12379 PRESENT_ALERTS.with(|m| {
12380 m.borrow_mut().remove(&req);
12381 });
12382 })
12383 })
12384 }
12385 PresentSpec::OpenFile { .. }
12387 | PresentSpec::OpenFolder { .. }
12388 | PresentSpec::SaveFile { .. } => unreachable!(),
12389 };
12390 unsafe {
12391 alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
12392 }
12393 PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
12394 }
12395
12396 fn dismiss(&mut self, req: u64) {
12397 let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
12400 if let Some(alert) = alert {
12401 let sheet = alert.window();
12402 if let Some(parent) = sheet.sheetParent() {
12403 unsafe { parent.endSheet(&sheet) };
12404 }
12405 }
12406 let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
12408 if let Some(panel) = panel
12409 && let Some(parent) = panel.sheetParent()
12410 {
12411 unsafe { parent.endSheet(&panel) };
12412 }
12413 }
12414
12415 fn application_handlers(
12416 &mut self,
12417 query: &day_spec::applications::HandlerQuery,
12418 ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
12419 {
12420 applications::handlers(query)
12421 }
12422
12423 fn open_url_with_application(
12424 &mut self,
12425 url: &str,
12426 application: &str,
12427 completion: day_spec::applications::OpenApplicationCompletion,
12428 ) {
12429 applications::open(url, application, completion);
12430 }
12431
12432 fn share_support(&self) -> day_spec::Support {
12433 day_spec::Support::Native
12434 }
12435 fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
12436 use objc2::{msg_send, runtime::AnyObject};
12437 use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
12438 let Some(mtm) = objc2::MainThreadMarker::new() else {
12439 return false;
12440 };
12441 let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
12442 return false;
12443 };
12444 let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
12445 let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
12446 return false;
12447 };
12448 unsafe {
12449 let items = NSArray::from_retained_slice(&[url]);
12450 let picker: objc2::rc::Allocated<AnyObject> =
12451 msg_send![objc2::class!(NSSharingServicePicker), alloc];
12452 let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
12453 let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
12454 actions: spec.actions.clone(),
12455 });
12456 let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
12457 let _: () = msg_send![&*picker, setDelegate: &*delegate];
12458 let (view, rect, edge) = match anchor {
12461 Some(view) => (view.clone(), view.bounds(), 1usize),
12462 None => {
12463 let bounds = window_view.bounds();
12464 let y = if window_view.isFlipped() {
12465 30.0
12466 } else {
12467 bounds.size.height - 30.0
12468 };
12469 let rect = NSRect::new(
12470 NSPoint::new(bounds.size.width - 30.0, y),
12471 NSSize::new(1.0, 1.0),
12472 );
12473 (window_view, rect, 3usize)
12474 }
12475 };
12476 let _: () =
12477 msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
12478 self.sharing = Some(picker);
12480 self.sharing_delegate = Some(delegate);
12481 }
12482 true
12483 }
12484 fn open_url(&mut self, url: &str) {
12485 let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
12488 if let Some(nsurl) = nsurl {
12489 unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
12490 }
12491 }
12492}
12493
12494#[allow(deprecated)]
12497fn apply_allowed_file_types(
12498 panel: &objc2_app_kit::NSSavePanel,
12499 filters: &[day_spec::present::FileFilter],
12500) {
12501 let exts: Vec<Retained<NSString>> = filters
12502 .iter()
12503 .flat_map(|f| f.extensions.iter())
12504 .map(|e| NSString::from_str(e))
12505 .collect();
12506 if !exts.is_empty() {
12507 let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
12508 let arr = objc2_foundation::NSArray::from_slice(&refs);
12509 unsafe { panel.setAllowedFileTypes(Some(&arr)) };
12510 }
12511}
12512
12513fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
12517 let mut paths = Vec::new();
12518 if resp == 1 {
12519 for url in unsafe { panel.URLs() }.iter() {
12520 if let Some(p) = unsafe { url.path() } {
12521 paths.push(p.to_string());
12522 }
12523 }
12524 }
12525 let result = if paths.is_empty() {
12526 present::PresentResult::Dismissed
12527 } else {
12528 present::PresentResult::Files(paths)
12529 };
12530 emit(WINDOW_NODE, Event::PresentResult { req, result });
12531 PRESENT_PANELS.with(|m| {
12532 m.borrow_mut().remove(&req);
12533 });
12534}
12535
12536fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
12538 let result = if resp == 1 {
12539 unsafe { panel.URL() }
12540 .and_then(|url| unsafe { url.path() })
12541 .map(|p| present::PresentResult::Files(vec![p.to_string()]))
12542 .unwrap_or(present::PresentResult::Dismissed)
12543 } else {
12544 present::PresentResult::Dismissed
12545 };
12546 emit(WINDOW_NODE, Event::PresentResult { req, result });
12547 PRESENT_PANELS.with(|m| {
12548 m.borrow_mut().remove(&req);
12549 });
12550}
12551
12552impl Platform for AppKit {
12553 const TARGET: &'static str = "macos-appkit";
12554 const TOOLKIT: &'static str = "appkit";
12555
12556 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
12557 let mtm = self.mtm;
12558 self.app_name = options
12562 .app_name
12563 .clone()
12564 .unwrap_or_else(|| options.title.clone());
12565 unsafe {
12574 objc2_foundation::NSProcessInfo::processInfo()
12575 .setProcessName(&NSString::from_str(&self.app_name));
12576 let bundle = objc2_foundation::NSBundle::mainBundle();
12577 let info: Option<Retained<objc2_foundation::NSDictionary>> =
12578 msg_send![&bundle, infoDictionary];
12579 if let Some(info) = info {
12580 let key = NSString::from_str("CFBundleName");
12581 let value = NSString::from_str(&self.app_name);
12582 if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
12586 let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
12587 }
12588 }
12589 }
12590 if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
12595 unsafe {
12596 use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
12597 let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
12598 .into_super()
12599 .into_super()
12600 .into_super();
12601 let dict = NSDictionary::from_retained_objects(
12602 &[
12603 &*NSString::from_str("AppleTextDirection"),
12604 &*NSString::from_str("NSForceRightToLeftWritingDirection"),
12605 ],
12606 &[yes.clone(), yes],
12607 );
12608 NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
12609 }
12610 }
12611 let app = NSApplication::sharedApplication(mtm);
12612 let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
12615 || unsafe {
12616 let bundle = objc2_foundation::NSBundle::mainBundle();
12617 let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
12618 &bundle,
12619 objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
12620 ];
12621 value.is_some_and(|v| {
12622 let on: bool = msg_send![&v, boolValue];
12623 on
12624 })
12625 };
12626 app.setActivationPolicy(if menu_bar_app {
12627 NSApplicationActivationPolicy::Accessory
12628 } else {
12629 NSApplicationActivationPolicy::Regular
12630 });
12631 let document_delegate = documents::delegate(mtm);
12632 app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
12633 if let Ok(theme) = std::env::var("DAY_THEME") {
12636 let name = match theme.as_str() {
12637 "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12638 "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12639 _ => None,
12640 };
12641 if let Some(name) = name {
12642 let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
12643 unsafe { app.setAppearance(appearance.as_deref()) };
12644 }
12645 }
12646 register_bundled_fonts();
12648
12649 let app_name = self.app_name.clone();
12653 install_main_menu(mtm, &app, &app_name);
12654 install_lifecycle_observers();
12656 install_appearance_observer();
12657 install_reduce_motion_observer();
12658
12659 let (window, delegate, content) = self.make_window(&options, false, None);
12660 let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
12664 Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12665 Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12666 _ => None,
12667 };
12668 if let Some(name) = appearance_name
12669 && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
12670 {
12671 window.setAppearance(Some(&appearance));
12672 }
12673 std::mem::forget(delegate);
12676
12677 self.window = Some(window.clone());
12678 self.content = Some(content.clone());
12679 PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
12680
12681 let layout = pin_below_title_bar(&window)
12683 .unwrap_or(Size::new(options.size.width, options.size.height));
12684 ready(self, content, layout);
12685
12686 if day_core::windows::new_window_action_id() == 0
12690 && options.tabbing == day_spec::WindowTabbing::Automatic
12691 {
12692 unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
12693 }
12694 if !day_core::has_app_menu() {
12699 install_main_menu(mtm, &app, &app_name);
12700 }
12701
12702 let deterministic =
12710 std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
12711 let autosave = NSString::from_str("day.main");
12712 if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
12713 window.center();
12714 window_chrome::place(&window, options.placement);
12716 }
12717 if let Some(screen) = capture_screen(mtm) {
12721 let (visible, frame) = (screen.visibleFrame(), window.frame());
12722 window.setFrameOrigin(NSPoint::new(
12723 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12724 visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12725 ));
12726 }
12727 if !deterministic {
12728 unsafe { window.setFrameAutosaveName(&autosave) };
12729 }
12730 if !options.start_hidden {
12731 window.makeKeyAndOrderFront(None);
12732 app.activate();
12733 }
12734 if let Some(content) = window.contentView() {
12739 mark_tree_needs_display(&content);
12740 }
12741 if std::env::var_os("DAY_DUMP").is_some() {
12742 std::thread::spawn(|| {
12743 std::thread::sleep(std::time::Duration::from_millis(2000));
12744 Self::post(Box::new(|| {
12745 if let Some(content) = primary_content() {
12747 let desc: Retained<NSString> =
12748 unsafe { msg_send![&*content, _subtreeDescription] };
12749 log::warn!("{desc}");
12750 }
12751 }));
12752 });
12753 }
12754 app.run();
12755 }
12756
12757 fn post(f: Box<dyn FnOnce() + Send>) {
12758 dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12761 }
12762
12763 fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12764 let when =
12768 dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12769 .unwrap_or(dispatch2::DispatchTime::FOREVER);
12770 if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12771 ffi_guard::contain((), f);
12772 }) {
12773 log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12774 }
12775 }
12776
12777 fn locale_hints(&self) -> Vec<String> {
12778 objc2_foundation::NSLocale::preferredLanguages()
12781 .iter()
12782 .map(|s| s.to_string())
12783 .collect()
12784 }
12785}
12786
12787unsafe extern "C" {
12792 fn CGWindowListCreateImage(
12793 bounds: objc2_core_foundation::CGRect,
12794 list_option: u32,
12795 window_id: u32,
12796 image_option: u32,
12797 ) -> *mut objc2_core_graphics::CGImage;
12798}
12799
12800const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12803const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12806
12807fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12814 let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12815 &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12816 objc2_app_kit::NSColorRenderingIntent::Default,
12817 );
12818 let rep = srgb.as_deref().unwrap_or(rep);
12819 let data = unsafe {
12820 rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12821 }
12822 .ok_or("png encode failed")?;
12823 Ok(data.to_vec())
12824}
12825
12826fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12839 let window = content.window().ok_or("view is not in a window")?;
12840 if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12843 return snapshot_via_window_server(&sheet, chrome);
12844 }
12845 let number = window.windowNumber();
12846 if number <= 0 {
12847 return Err(format!("window {number} is not on screen"));
12848 }
12849 unsafe { content.layoutSubtreeIfNeeded() };
12856 window.displayIfNeeded();
12857 CATransaction::flush();
12858 let null_rect = objc2_core_foundation::CGRect::new(
12860 objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12861 objc2_core_foundation::CGSize::new(0.0, 0.0),
12862 );
12863 let shot = unsafe {
12864 CGWindowListCreateImage(
12865 null_rect,
12866 CG_WINDOW_LIST_INCLUDING_WINDOW,
12867 number as u32,
12868 CG_WINDOW_IMAGE_IGNORE_FRAMING,
12869 )
12870 };
12871 if shot.is_null() {
12872 return Err("the window server has no image for this window".into());
12873 }
12874 let shot = unsafe {
12877 objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12878 };
12879
12880 if chrome {
12883 let rep = unsafe {
12884 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12885 objc2_app_kit::NSBitmapImageRep::alloc(),
12886 &shot,
12887 )
12888 };
12889 return png_of_rep(&rep);
12890 }
12891
12892 let frame = window.frame();
12896 if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12897 return Err("zero-size window".into());
12898 }
12899 let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12900 let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12903 let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12904 let crop = objc2_core_foundation::CGRect::new(
12905 objc2_core_foundation::CGPoint::new(
12906 (in_window.origin.x * scale).round(),
12907 (from_top * scale).round(),
12908 ),
12909 objc2_core_foundation::CGSize::new(
12910 (in_window.size.width * scale).round(),
12911 (in_window.size.height * scale).round(),
12912 ),
12913 );
12914 let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12915 .ok_or("crop to the content view failed")?;
12916 let rep = unsafe {
12917 objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12918 objc2_app_kit::NSBitmapImageRep::alloc(),
12919 &cropped,
12920 )
12921 };
12922 png_of_rep(&rep)
12923}
12924
12925fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12935 let [x, y, w, h] = base;
12936 let (sw, sh) = (w * t.sx, h * t.sy);
12937 let frame = NSRect::new(
12938 NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12939 NSSize::new(sw, sh),
12940 );
12941 unsafe {
12942 v.setFrameCenterRotation(0.0);
12945 v.setFrame(frame);
12946 v.setBoundsSize(NSSize::new(w, h));
12947 if t.rotate_deg != 0.0 {
12948 v.setFrameCenterRotation(t.rotate_deg);
12949 }
12950 }
12951}
12952
12953fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12954 let modal = content
12955 .window()
12956 .and_then(|w| w.attachedSheet())
12957 .and_then(|s| s.contentView());
12958 let content = modal.as_deref().unwrap_or(content);
12959 match snapshot_via_window_server(content, false) {
12960 Ok(bytes) => Ok(bytes),
12961 Err(_) => snapshot_view_cache(content),
12962 }
12963}
12964
12965fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12973 let modal = content
12974 .window()
12975 .and_then(|w| w.attachedSheet())
12976 .and_then(|s| s.contentView());
12977 let content = modal.as_deref().unwrap_or(content);
12978 match snapshot_via_window_server(content, true) {
12979 Ok(bytes) => Ok(bytes),
12980 Err(_) => snapshot_view_cache(content),
12981 }
12982}
12983
12984fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12988 let bounds = content.bounds();
12989 let rep =
12990 unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12991 let ctx =
12995 NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12996 NSGraphicsContext::saveGraphicsState_class();
12997 NSGraphicsContext::setCurrentContext(Some(&ctx));
12998 content
12999 .effectiveAppearance()
13000 .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
13001 NSColor::windowBackgroundColor().setFill();
13002 objc2_app_kit::NSRectFill(bounds);
13003 }));
13004 NSGraphicsContext::restoreGraphicsState_class();
13005 unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
13006 png_of_rep(&rep)
13007}
13008
13009fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
13015 let Some(screen) = primary.and_then(|w| w.screen()) else {
13016 return;
13017 };
13018 if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
13019 return;
13020 }
13021 let (visible, frame) = (screen.visibleFrame(), window.frame());
13022 window.setFrameOrigin(NSPoint::new(
13023 visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
13024 visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
13025 ));
13026}
13027
13028fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
13029 let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
13030 .ok()?
13031 .trim()
13032 .parse()
13033 .ok()?;
13034 let key = NSString::from_str("NSScreenNumber");
13035 objc2_app_kit::NSScreen::screens(mtm)
13036 .into_iter()
13037 .find(|screen| {
13038 let number: Option<Retained<objc2_foundation::NSNumber>> =
13039 unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
13040 number.is_some_and(|n| n.unsignedIntValue() == wanted)
13041 })
13042}
13043
13044fn mark_tree_needs_display(view: &NSView) {
13046 view.setNeedsDisplay(true);
13047 for sub in view.subviews() {
13048 mark_tree_needs_display(&sub);
13049 }
13050}
13051
13052pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
13057 phase.is_universal()
13058}
13059
13060fn install_appearance_observer() {
13066 use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
13067 let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
13068 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13069 dispatch2::DispatchQueue::main()
13070 .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
13071 });
13072 let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
13073 let token = unsafe {
13074 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13075 };
13076 std::mem::forget(token);
13077 let center = objc2_foundation::NSNotificationCenter::defaultCenter();
13079 let name = NSString::from_str("NSSystemColorsDidChangeNotification");
13080 let token = unsafe {
13081 center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13082 };
13083 std::mem::forget(token);
13084}
13085
13086fn install_reduce_motion_observer() {
13094 use objc2_foundation::NSNotification;
13095 let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
13096 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13097 dispatch2::DispatchQueue::main()
13098 .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
13099 });
13100 let token = unsafe {
13101 center.addObserverForName_object_queue_usingBlock(
13102 Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
13103 None,
13104 None,
13105 &block,
13106 )
13107 };
13108 std::mem::forget(token);
13109}
13110
13111fn install_lifecycle_observers() {
13114 use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
13115 let center = unsafe { NSNotificationCenter::defaultCenter() };
13116 let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
13117 let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13118 ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
13119 });
13120 let token = unsafe {
13121 center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
13122 };
13123 std::mem::forget(token); };
13125 unsafe {
13126 observe(
13127 NSApplicationDidBecomeActiveNotification,
13128 day_spec::Lifecycle::DidBecomeActive,
13129 );
13130 observe(
13131 NSApplicationWillResignActiveNotification,
13132 day_spec::Lifecycle::WillResignActive,
13133 );
13134 observe(
13135 NSApplicationWillTerminateNotification,
13136 day_spec::Lifecycle::WillTerminate,
13137 );
13138 observe(
13142 NSApplicationWillTerminateNotification,
13143 day_spec::Lifecycle::DidExit,
13144 );
13145 }
13146}
13147
13148day_localization_ui::locales!();
13149
13150fn install_application_menu(
13153 mtm: MainThreadMarker,
13154 menubar: &NSMenu,
13155 title: &str,
13156 about: Option<day_spec::MenuItem>,
13157 updates: Option<day_spec::MenuItem>,
13158 prefs: Option<day_spec::MenuItem>,
13159 quit: Option<day_spec::MenuItem>,
13160) -> Retained<NSMenu> {
13161 let app = NSApplication::sharedApplication(mtm);
13162 use day_spec::{MenuItem as M, MenuRole as R};
13163 let standard = |role, label| M::Action {
13164 id: None,
13165 action: 0,
13166 label,
13167 shortcut: None,
13168 enabled: true,
13169 checked: None,
13170 role: Some(role),
13171 icon: None,
13172 };
13173 let mut about =
13174 about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
13175 let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
13176 for (item, title) in [
13177 (&mut about, res::str::about_app(title).format()),
13178 (&mut quit, res::str::quit_app(title).format()),
13179 ] {
13180 if let M::Action { label, .. } = item {
13181 *label = title;
13182 }
13183 }
13184 if let M::Action { action, .. } = &mut about
13187 && *action == 0
13188 {
13189 *action = day_core::windows::about_action_id();
13190 }
13191 let updates_id = day_core::windows::check_for_updates_action_id();
13194 let updates = updates.or_else(|| {
13195 (updates_id != 0).then(|| {
13196 standard(
13197 R::CheckForUpdates,
13198 day_localization::t(day_localization::key::day_check_for_updates),
13199 )
13200 })
13201 });
13202 let mut head = vec![about];
13203 if let Some(mut updates) = updates {
13204 if let M::Action { action, .. } = &mut updates
13205 && *action == 0
13206 {
13207 *action = updates_id;
13208 }
13209 head.push(updates);
13210 }
13211 head.push(M::Separator);
13212 let menu = build_ns_menu(mtm, title, &head);
13213 if let Some(mut prefs) = prefs {
13214 if let M::Action { label, .. } = &mut prefs {
13215 *label = res::str::settings().format();
13216 }
13217 let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
13218 for item in section.itemArray() {
13219 section.removeItem(&item);
13220 menu.addItem(&item);
13221 }
13222 }
13223 let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
13226 if let Some(parent) = unsafe { services.supermenu() } {
13227 let index = parent.indexOfItemWithSubmenu(Some(&services));
13228 if index >= 0 {
13229 parent.itemAtIndex(index).unwrap().setSubmenu(None);
13230 }
13231 }
13232 let services_item = NSMenuItem::new(mtm);
13233 services_item.setTitle(&NSString::from_str(&res::str::services().format()));
13234 services_item.setSubmenu(Some(&services));
13235 menu.addItem(&services_item);
13236 menu.addItem(&NSMenuItem::separatorItem(mtm));
13237 for (label, selector, shortcut) in [
13238 (
13239 res::str::hide_app(title).format(),
13240 sel!(hide:),
13241 Some(day_spec::Shortcut::primary("h")),
13242 ),
13243 (
13244 res::str::hide_others().format(),
13245 sel!(hideOtherApplications:),
13246 Some(day_spec::Shortcut::primary("h").alt()),
13247 ),
13248 (
13249 res::str::show_all().format(),
13250 sel!(unhideAllApplications:),
13251 None,
13252 ),
13253 ] {
13254 let item = unsafe {
13255 NSMenuItem::initWithTitle_action_keyEquivalent(
13256 NSMenuItem::alloc(mtm),
13257 &NSString::from_str(&label),
13258 Some(selector),
13259 &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
13260 )
13261 };
13262 if let Some(shortcut) = shortcut {
13263 item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
13264 }
13265 unsafe { item.setTarget(Some(&app)) };
13267 menu.addItem(&item);
13268 }
13269 menu.addItem(&NSMenuItem::separatorItem(mtm));
13270 let section = build_ns_menu(mtm, title, &[quit]);
13271 let quit = section.itemAtIndex(0).unwrap();
13272 section.removeItem(&quit);
13273 menu.addItem(&quit);
13274 let item = NSMenuItem::new(mtm);
13275 item.setSubmenu(Some(&menu));
13276 menubar.addItem(&item);
13277 services
13278}
13279
13280fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
13283 let menubar = NSMenu::new(mtm);
13284
13285 let prefs_id = day_core::windows::preferences_action_id();
13286 let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
13287 id: None,
13288 action: prefs_id,
13289 label: res::str::settings().format(),
13290 shortcut: None,
13291 enabled: true,
13292 checked: None,
13293 role: Some(day_spec::MenuRole::Preferences),
13294 icon: None,
13295 });
13296 let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
13297
13298 let new_window_id = day_core::windows::new_window_action_id();
13303 if new_window_id != 0 {
13304 let file_item = NSMenuItem::new(mtm);
13305 let file_menu = unsafe {
13306 NSMenu::initWithTitle(
13307 NSMenu::alloc(mtm),
13308 &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
13309 )
13310 };
13311 let new_window = unsafe {
13312 NSMenuItem::initWithTitle_action_keyEquivalent(
13313 NSMenuItem::alloc(mtm),
13314 &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
13315 Some(sel!(fire:)),
13316 &NSString::from_str("n"),
13317 )
13318 };
13319 let target = menu_target(mtm);
13320 let tobj: &objc2::runtime::AnyObject = target.as_ref();
13321 unsafe { new_window.setTarget(Some(tobj)) };
13322 new_window.setTag(new_window_id as isize);
13323 file_menu.addItem(&new_window);
13324 file_menu.addItem(&NSMenuItem::separatorItem(mtm));
13325 let close = unsafe {
13327 NSMenuItem::initWithTitle_action_keyEquivalent(
13328 NSMenuItem::alloc(mtm),
13329 &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
13330 Some(sel!(performClose:)),
13331 &NSString::from_str("w"),
13332 )
13333 };
13334 file_menu.addItem(&close);
13335 file_item.setSubmenu(Some(&file_menu));
13336 menubar.addItem(&file_item);
13337 }
13338
13339 let edit_item = NSMenuItem::new(mtm);
13340 let edit_menu = unsafe {
13341 NSMenu::initWithTitle(
13342 NSMenu::alloc(mtm),
13343 &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
13344 )
13345 };
13346 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13347 let item = unsafe {
13348 NSMenuItem::initWithTitle_action_keyEquivalent(
13349 NSMenuItem::alloc(mtm),
13350 &NSString::from_str(&day_localization::t(key)),
13351 Some(action),
13352 &NSString::from_str(accel),
13353 )
13354 };
13355 edit_menu.addItem(&item);
13356 };
13357 add("day_undo", sel!(undo:), "z");
13358 add("day_redo", sel!(redo:), "Z");
13359 edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
13360 add("day_cut", sel!(cut:), "x");
13361 add("day_copy", sel!(copy:), "c");
13362 add("day_paste", sel!(paste:), "v");
13363 add("day_select_all", sel!(selectAll:), "a");
13364 edit_item.setSubmenu(Some(&edit_menu));
13365 menubar.addItem(&edit_item);
13366
13367 install_windows_menu(mtm, app, &menubar);
13368
13369 app.setMainMenu(Some(&menubar));
13370 unsafe { app.setServicesMenu(Some(&services)) };
13371}
13372
13373fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
13378 let menu = unsafe {
13379 NSMenu::initWithTitle(
13380 NSMenu::alloc(mtm),
13381 &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
13382 )
13383 };
13384 let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13385 let item = unsafe {
13386 NSMenuItem::initWithTitle_action_keyEquivalent(
13387 NSMenuItem::alloc(mtm),
13388 &NSString::from_str(&day_localization::t(key)),
13389 Some(action),
13390 &NSString::from_str(accel),
13391 )
13392 };
13393 menu.addItem(&item);
13394 };
13395 add("day_minimize", sel!(performMiniaturize:), "m");
13396 add("day_zoom", sel!(performZoom:), "");
13397 menu.addItem(&NSMenuItem::separatorItem(mtm));
13398 add("day_bring_all_front", sel!(arrangeInFront:), "");
13399 let item = NSMenuItem::new(mtm);
13400 item.setTitle(&NSString::from_str(&day_localization::t(
13401 day_localization::key::day_window,
13402 )));
13403 item.setSubmenu(Some(&menu));
13404 menubar.addItem(&item);
13405 unsafe { app.setWindowsMenu(Some(&menu)) };
13406}
13407
13408fn extract_app_role(
13411 items: &mut Vec<day_spec::MenuItem>,
13412 role: day_spec::MenuRole,
13413) -> Option<day_spec::MenuItem> {
13414 use day_spec::MenuItem as M;
13415 let mut found = None;
13416 let mut remaining = Vec::new();
13417 for mut item in items.drain(..) {
13418 match &mut item {
13419 M::Action { role: Some(r), .. } if *r == role => {
13420 found.get_or_insert(item);
13421 continue;
13422 }
13423 M::Submenu { items, .. } => {
13424 let nested = extract_app_role(items, role);
13425 if found.is_none() {
13426 found = nested;
13427 }
13428 if items.is_empty() {
13429 continue;
13430 }
13431 }
13432 M::Separator
13433 if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
13434 {
13435 continue;
13436 }
13437 _ => {}
13438 }
13439 remaining.push(item);
13440 }
13441 while matches!(remaining.last(), Some(M::Separator)) {
13442 remaining.pop();
13443 }
13444 *items = remaining;
13445 found
13446}
13447
13448fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
13450 items.iter().any(|it| match it {
13451 day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
13452 day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
13453 day_spec::MenuItem::Separator => false,
13454 })
13455}
13456
13457define_class!(
13463 #[unsafe(super(NSObject))]
13464 #[thread_kind = MainThreadOnly]
13465 #[name = "DayMenuTarget"]
13466 #[ivars = ()]
13467 struct DayMenuTarget;
13468
13469 unsafe impl NSObjectProtocol for DayMenuTarget {}
13470
13471 impl DayMenuTarget {
13472 #[unsafe(method(fire:))]
13473 fn fire(&self, sender: &NSMenuItem) {
13474 ffi_guard::contain((), || {
13475 let id = sender.tag() as u64;
13476 if id != 0 {
13477 emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
13478 }
13479 })
13480 }
13481 }
13482);
13483
13484pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
13493 let content = window.contentView()?;
13494 let full = content.frame().size;
13495 let layout = unsafe { window.contentLayoutRect() }.size;
13496 let top = (full.height - layout.height).max(0.0);
13497 if window_chrome::is_overlay(window) {
13501 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
13502 window_chrome::report_title_bar_inset(window, top);
13503 return Some(Size::new(full.width, full.height));
13504 }
13505 unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
13506 Some(Size::new(full.width, (full.height - top).max(0.0)))
13507}
13508
13509fn native_text(h: &NSView) -> Option<String> {
13513 if h.downcast_ref::<NSSecureTextField>().is_some() {
13514 return None;
13515 }
13516 if let Some(tf) = h.downcast_ref::<NSTextField>() {
13517 return Some(tf.stringValue().to_string());
13519 }
13520 if let Some(btn) = h.downcast_ref::<NSButton>() {
13521 if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
13522 return None;
13523 }
13524 return Some(btn.title().to_string());
13525 }
13526 let sv = h.downcast_ref::<NSScrollView>()?;
13528 let doc = sv.documentView()?;
13529 let tv = doc.downcast_ref::<NSTextView>()?;
13530 Some(tv.string().to_string())
13531}
13532
13533fn native_number(h: &NSView) -> Option<f64> {
13536 if let Some(sl) = h.downcast_ref::<NSSlider>() {
13537 return Some(sl.doubleValue());
13538 }
13539 let pi = h.downcast_ref::<NSProgressIndicator>()?;
13540 (!pi.isIndeterminate()).then(|| pi.doubleValue())
13541}
13542
13543fn native_frame(h: &NSView) -> Option<Rect> {
13547 let content = h.window()?.contentView()?;
13548 let r = h.convertRect_toView(h.bounds(), Some(&content));
13549 let y = if content.isFlipped() {
13550 r.origin.y
13551 } else {
13552 let b = content.bounds();
13553 b.origin.y + b.size.height - (r.origin.y + r.size.height)
13554 };
13555 Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
13556}
13557
13558fn title_bar_inset(content: &NSView) -> f64 {
13560 (-content.bounds().origin.y).max(0.0)
13561}
13562
13563fn primary_content() -> Option<Retained<NSView>> {
13564 PRIMARY_CONTENT.with(|c| c.borrow().clone())
13565}
13566
13567fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
13568 MENU_TARGET.with(|t| {
13569 t.borrow_mut()
13570 .get_or_insert_with(|| {
13571 let this = DayMenuTarget::alloc(mtm).set_ivars(());
13572 let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
13573 obj
13574 })
13575 .clone()
13576 })
13577}
13578
13579fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
13580 use objc2_app_kit::NSEventModifierFlags as F;
13581 let mut m = F::empty();
13582 if s.primary {
13583 m |= F::Command;
13584 }
13585 if s.shift {
13586 m |= F::Shift;
13587 }
13588 if s.alt {
13589 m |= F::Option;
13590 }
13591 if s.control {
13592 m |= F::Control;
13593 }
13594 m
13595}
13596
13597fn ns_key_equivalent(key: &str) -> String {
13600 match key {
13601 "Return" | "Enter" => "\r".into(),
13602 "Tab" => "\t".into(),
13603 "Delete" | "Backspace" => "\u{8}".into(),
13604 "Escape" => "\u{1b}".into(),
13605 "Space" => " ".into(),
13606 k if k.chars().count() == 1 => k.to_lowercase(),
13607 _ => String::new(), }
13609}
13610
13611fn role_spec(
13614 role: day_spec::MenuRole,
13615) -> (
13616 &'static str,
13617 Option<objc2::runtime::Sel>,
13618 Option<day_spec::Shortcut>,
13619) {
13620 use day_spec::MenuRole as R;
13621 use day_spec::Shortcut as S;
13622 match role {
13623 R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
13624 R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
13625 R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
13626 R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
13627 R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
13628 R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
13629 R::Delete => ("Delete", Some(sel!(delete:)), None),
13630 R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
13631 R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
13632 R::Preferences => ("Settings…", None, Some(S::primary(","))),
13633 R::Minimize => (
13634 "Minimize",
13635 Some(sel!(performMiniaturize:)),
13636 Some(S::primary("m")),
13637 ),
13638 R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
13639 R::Fullscreen => (
13640 "Enter Full Screen",
13641 Some(sel!(toggleFullScreen:)),
13642 Some(S::primary("f").control()),
13643 ),
13644 R::NewWindow => ("New Window", None, Some(S::primary("n"))),
13647 R::CheckForUpdates => ("Check for Updates…", None, None),
13649 }
13650}
13651
13652pub(crate) fn build_ns_menu(
13653 mtm: MainThreadMarker,
13654 title: &str,
13655 items: &[day_spec::MenuItem],
13656) -> Retained<NSMenu> {
13657 use day_spec::MenuItem as MI;
13658 let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
13659 let target = menu_target(mtm);
13660 for item in items {
13661 match item {
13662 MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
13663 MI::Submenu { label, items, .. } => {
13664 let sub = build_ns_menu(mtm, label, items);
13665 let it = NSMenuItem::new(mtm);
13666 it.setTitle(&NSString::from_str(label));
13667 it.setSubmenu(Some(&sub));
13668 menu.addItem(&it);
13669 }
13670 MI::Action {
13671 action,
13672 label,
13673 shortcut,
13674 enabled,
13675 checked,
13676 role,
13677 icon,
13678 ..
13679 } => {
13680 let (mut lbl, sel, mut sc) = match role {
13682 Some(r) => {
13683 let (dl, ds, dsc) = role_spec(*r);
13684 (dl.to_string(), ds, dsc)
13685 }
13686 None => (String::new(), None, None),
13687 };
13688 if !label.is_empty() {
13689 lbl = label.clone();
13690 }
13691 if shortcut.is_some() {
13692 sc = shortcut.clone();
13693 }
13694 let responder_role = matches!(
13700 role,
13701 Some(
13702 day_spec::MenuRole::Undo
13703 | day_spec::MenuRole::Redo
13704 | day_spec::MenuRole::Cut
13705 | day_spec::MenuRole::Copy
13706 | day_spec::MenuRole::Paste
13707 | day_spec::MenuRole::SelectAll
13708 )
13709 );
13710 let custom = *action != 0 && !responder_role;
13711 let key = sc
13712 .as_ref()
13713 .map(|s| ns_key_equivalent(&s.key))
13714 .unwrap_or_default();
13715 let it = unsafe {
13716 NSMenuItem::initWithTitle_action_keyEquivalent(
13717 NSMenuItem::alloc(mtm),
13718 &NSString::from_str(&lbl),
13719 if custom { Some(sel!(fire:)) } else { sel },
13720 &NSString::from_str(&key),
13721 )
13722 };
13723 if let Some(s) = &sc {
13724 it.setKeyEquivalentModifierMask(ns_modifiers(s));
13725 it.setAllowsAutomaticKeyEquivalentLocalization(true);
13731 it.setAllowsAutomaticKeyEquivalentMirroring(true);
13732 }
13733 if custom {
13734 let tobj: &objc2::runtime::AnyObject = target.as_ref();
13735 unsafe { it.setTarget(Some(tobj)) };
13736 it.setTag(*action as isize);
13737 }
13738 it.setEnabled(*enabled);
13739 if let Some(on) = checked {
13742 it.setState(if *on {
13743 NSControlStateValueOn
13744 } else {
13745 NSControlStateValueOff
13746 });
13747 }
13748 if let Some(icon) = icon
13751 && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13752 {
13753 img.setSize(NSSize::new(16.0, 16.0));
13754 it.setImage(Some(&img));
13755 }
13756 menu.addItem(&it);
13757 }
13758 }
13759 }
13760 menu
13761}
13762
13763fn release_bitmap(id: day_spec::BitmapId) {
13766 let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13767}
13768
13769#[cfg(test)]
13770mod bitmap_teardown_tests {
13771 use super::*;
13772
13773 #[test]
13774 fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13775 const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13777 if std::env::var_os(CHILD).is_some() {
13778 struct LateRelease;
13779 impl Drop for LateRelease {
13780 fn drop(&mut self) {
13781 assert!(BITMAPS.try_with(|_| ()).is_err());
13782 release_bitmap(day_spec::BitmapId(1));
13784 }
13785 }
13786 std::thread_local! {
13787 static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13788 }
13789 std::thread::spawn(|| {
13790 LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13791 BITMAPS.with(|_| ()); })
13793 .join()
13794 .unwrap();
13795 return;
13796 }
13797 let output = std::process::Command::new(std::env::current_exe().unwrap())
13798 .args([
13799 "--exact",
13800 "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13801 "--nocapture",
13802 ])
13803 .env(CHILD, "1")
13804 .output()
13805 .unwrap();
13806 assert!(
13807 output.status.success(),
13808 "{}",
13809 String::from_utf8_lossy(&output.stderr)
13810 );
13811 }
13812}